问:
Force to close SSH client session
I've written a SSH client to connect to network devices and I set a timeout through "select" once the running command takes more than 25 seconds. I noticed a few of devices that they have another IOS it can not drop the SSH session w/ them through Close() method once the timeout has been triggered and it causes goroutinge leaking. I need to keep up the client and disconnect the session to be ready for next command. looks the goroutine doesn't terminate for ever at that time!  Do you guys have any idea?

```<code>    go func() {
       r <- s.Run(cmd)
    }()

    select {
       case err := <-r:
         return err
       case <-time.After(time.Duration(timeout) * time.Second):
         s.Close()
         return fmt.Errorf("timeout after %d seconds", timeout)
    }
</code>```

Through the heap profiling I saw the below:
    2.77GB 99.44% 99.44%     2.77GB 99.44%  bytes.makeSlice

```<code>     0     0% 99.44%     2.77GB 99.44%  bytes.(*Buffer).ReadFrom

     0     0% 99.44%     2.77GB 99.44%  golang.org/x/crypto/ssh.(*Session).start.func1

     0     0% 99.44%     2.77GB 99.44%  golang.org/x/crypto/ssh.(*Session).stdout.func1

     0     0% 99.44%     2.77GB 99.44%  io.Copy

     0     0% 99.44%     2.77GB 99.44%  io.copyBuffer

     0     0% 99.44%     2.78GB 99.93%  runtime.goexit
</code>```

ROUTINE ======================== runtime.goexit in /usr/local/go/src/runtime/asm_amd64.s

```<code>     0     2.78GB (flat, cum) 99.93% of Total

     .          .   1993:   RET

     .          .   1994:

     .          .   1995:// The top-most function running on a goroutine

     .          .   1996:// returns to goexit+PCQuantum.

     .          .   1997:TEXT runtime·goexit(SB),NOSPLIT,$0-0

     .     2.78GB   1998:   BYTE    $0x90   // NOP

     .          .   1999:   CALL    runtime·goexit1(SB) // does not return

     .          .   2000:   // traceback from goexit1 must hit code range of goexit

     .          .   2001:   BYTE    $0x90   // NOP

     .          .   2002:

     .          .   2003:TEXT runtime·prefetcht0(SB),NOSPLIT,$0-8
</code>```

答:
Channel r blocks the Go routine from returning, as it is not being emptied. I've written an adapted version of your code and inserted a Wait group to demonstrate the problem:

```<code>func main() {
    var wg sync.WaitGroup // This is only added for demonstration purposes
    s := new(clientSession)

    r := make(chan error)

    go func(s *clientSession) {
        wg.Add(1)
        r <- s.Run()
        wg.Done() // Will only be called after s.Run() is able to return
    }(s)

    fmt.Println("Client has been opened")

    select {
    case err := <-r:
        fmt.Println(err)
    case <-time.After(1 * time.Second):
        s.Close()
        fmt.Println("Timed out, closing")
    }

    wg.Wait() // Waits until wg.Done() is called.

    fmt.Println("Main finished successfully")
}
</code>```

Go playground seems to terminate the program, so I've created a gist with the complete run-able code. When we run incorrect.go:

```<code>$ go run incorrect.go
Client has been opened
Timed out, closing
fatal error: all goroutines are asleep - deadlock!
....
</code>```

That's because our code is deadlocked on the wg.Wait() line. This demonstrated that wg.Done() in the Go routine was never reached.

As the comments point out, a buffered channel can help out here. But only if you don't care about the error anymore, after calling s.Close()

```<code>r := make(chan error, 1)
</code>```

buffered.go runs correctly, but the error is lost:

```<code>$ go run buffered.go
Client has been opened
Timed out, closing
Main finished successfully
</code>```

Another option would be to drain the channel exactly 1 time:

```<code>select {
    case err := <-r:
        fmt.Println(err)
    case <-time.After(1 * time.Second):
        s.Close()
        fmt.Println("Timed out, closing")
        fmt.Println(<-r)
    }
</code>```

Or by wrapping select in a for loop (without buffered channel):

```<code>X:
    for {
        select {
        case err := <-r:
            fmt.Println(err)
            break X // because we are in main(). Normally `return err`
        case <-time.After(1 * time.Second):
            s.Close()
            fmt.Println("Timed out, closing")
        }
    }
</code>```

When we run drain.go we see the error also printed:

```<code>$ go run incorrect.go
Client has been opened
Timed out, closing
Run() closed
Main finished successfully
</code>```

In real world, one would be running multiple Go routines. So you will want to use some counters on the for loop or further utilize Wait group functionality.

Title: Force to close SSH client session

Body:
I've written a SSH client to connect to network devices and I set a timeout through "select" once the running command takes more than 25 seconds. I noticed a few of devices that they have another IOS it can not drop the SSH session w/ them through Close() method once the timeout has been triggered and it causes goroutinge leaking. I need to keep up the client and disconnect the session to be ready for next command. looks the goroutine doesn't terminate for ever at that time!  Do you guys have any idea?

    go func() {
       r <- s.Run(cmd)
    }()

    select {
       case err := <-r:
         return err
       case <-time.After(time.Duration(timeout) * time.Second):
         s.Close()
         return fmt.Errorf("timeout after %d seconds", timeout)
    }

Through the heap profiling I saw the below:
    2.77GB 99.44% 99.44%     2.77GB 99.44%  bytes.makeSlice

     0     0% 99.44%     2.77GB 99.44%  bytes.(*Buffer).ReadFrom

     0     0% 99.44%     2.77GB 99.44%  golang.org/x/crypto/ssh.(*Session).start.func1

     0     0% 99.44%     2.77GB 99.44%  golang.org/x/crypto/ssh.(*Session).stdout.func1

     0     0% 99.44%     2.77GB 99.44%  io.Copy

     0     0% 99.44%     2.77GB 99.44%  io.copyBuffer

     0     0% 99.44%     2.78GB 99.93%  runtime.goexit

ROUTINE ======================== runtime.goexit in /usr/local/go/src/runtime/asm_amd64.s

     0     2.78GB (flat, cum) 99.93% of Total

     .          .   1993:   RET

     .          .   1994:

     .          .   1995:// The top-most function running on a goroutine

     .          .   1996:// returns to goexit+PCQuantum.

     .          .   1997:TEXT runtime·goexit(SB),NOSPLIT,$0-0

     .     2.78GB   1998:   BYTE    $0x90   // NOP

     .          .   1999:   CALL    runtime·goexit1(SB) // does not return

     .          .   2000:   // traceback from goexit1 must hit code range of goexit

     .          .   2001:   BYTE    $0x90   // NOP

     .          .   2002:

     .          .   2003:TEXT runtime·prefetcht0(SB),NOSPLIT,$0-8

Body:
Channel r blocks the Go routine from returning, as it is not being emptied. I've written an adapted version of your code and inserted a Wait group to demonstrate the problem:

func main() {
    var wg sync.WaitGroup // This is only added for demonstration purposes
    s := new(clientSession)

    r := make(chan error)

    go func(s *clientSession) {
        wg.Add(1)
        r <- s.Run()
        wg.Done() // Will only be called after s.Run() is able to return
    }(s)

    fmt.Println("Client has been opened")

    select {
    case err := <-r:
        fmt.Println(err)
    case <-time.After(1 * time.Second):
        s.Close()
        fmt.Println("Timed out, closing")
    }

    wg.Wait() // Waits until wg.Done() is called.

    fmt.Println("Main finished successfully")
}

Go playground seems to terminate the program, so I've created a gist with the complete run-able code. When we run incorrect.go:

$ go run incorrect.go
Client has been opened
Timed out, closing
fatal error: all goroutines are asleep - deadlock!
....

That's because our code is deadlocked on the wg.Wait() line. This demonstrated that wg.Done() in the Go routine was never reached.

As the comments point out, a buffered channel can help out here. But only if you don't care about the error anymore, after calling s.Close()

r := make(chan error, 1)

buffered.go runs correctly, but the error is lost:

$ go run buffered.go
Client has been opened
Timed out, closing
Main finished successfully

Another option would be to drain the channel exactly 1 time:

select {
    case err := <-r:
        fmt.Println(err)
    case <-time.After(1 * time.Second):
        s.Close()
        fmt.Println("Timed out, closing")
        fmt.Println(<-r)
    }

Or by wrapping select in a for loop (without buffered channel):

X:
    for {
        select {
        case err := <-r:
            fmt.Println(err)
            break X // because we are in main(). Normally `return err`
        case <-time.After(1 * time.Second):
            s.Close()
            fmt.Println("Timed out, closing")
        }
    }

When we run drain.go we see the error also printed:

$ go run incorrect.go
Client has been opened
Timed out, closing
Run() closed
Main finished successfully

In real world, one would be running multiple Go routines. So you will want to use some counters on the for loop or further utilize Wait group functionality.


来源: stackexchange

问:
AS3 call a just added element
i'm adding a movieclip element ("lastSlide") to an other movieclip element("endLogoButton"). The added element has a child which is a button("endLogoButton"). How can i call that button?

```<code>    mcSlideHolder.addChild(lastSlide);
  /*mcSlideHolder.getChildByName("endLogoButton").buttonMode = true;;
    mcSlideHolder.getChildByName("endLogoButton").mouseChildren = false;
    mcSlideHolder.getChildByName("endLogoButton").useHandCursor  = true;*/
    lastSlide.endLogoButton.addEventListener(MouseEvent.CLICK, linkClick);
</code>```

As a beginner i'm struggling around ... but can't make it work ...
It always tells me that the access to a Nullobject reference is not possible.

Thanks for any advice!

答:
or maybe: try casting the "lastSlide" to a MovieClip like:

```<code>MovieClip(mcSlideHolder.getChildByName("lastSlide")).getChildByName("endLogoButton").addEventListener(MouseEvent.CLICK, linkClick);
</code>```

This worked for me several times when the "possible unreferenced object" error popped up when referencing a movieclip that was clearly added to the stage

ContentLicense: CC BY-SA 3.0

Title: AS3 call a just added element

Body:
i'm adding a movieclip element ("lastSlide") to an other movieclip element("endLogoButton"). The added element has a child which is a button("endLogoButton"). How can i call that button?

    mcSlideHolder.addChild(lastSlide);
  /*mcSlideHolder.getChildByName("endLogoButton").buttonMode = true;;
    mcSlideHolder.getChildByName("endLogoButton").mouseChildren = false;
    mcSlideHolder.getChildByName("endLogoButton").useHandCursor  = true;*/
    lastSlide.endLogoButton.addEventListener(MouseEvent.CLICK, linkClick);

As a beginner i'm struggling around ... but can't make it work ...
It always tells me that the access to a Nullobject reference is not possible.

Thanks for any advice!

Body:
or maybe: try casting the "lastSlide" to a MovieClip like:

MovieClip(mcSlideHolder.getChildByName("lastSlide")).getChildByName("endLogoButton").addEventListener(MouseEvent.CLICK, linkClick);

This worked for me several times when the "possible unreferenced object" error popped up when referencing a movieclip that was clearly added to the stage


问:
Django Rest Framework gives 302 in Unit tests when force_login() on detail view?
I'm using Django Rest Framework to serve an API. I've got a couple tests which work great. To do a post the user needs to be logged in and I also do some checks for the detail view for a logged in user. I do this as follows:

```<code>class DeviceTestCase(APITestCase):
    USERNAME = "username"
    EMAIL = 'a@b.com'
    PASSWORD = "password"

    def setUp(self):
        self.sa_group, _ = Group.objects.get_or_create(name=settings.KEYCLOAK_SA_WRITE_PERMISSION_NAME)
        self.authorized_user = User.objects.create_user(self.USERNAME, self.EMAIL, self.PASSWORD)
        self.sa_group.user_set.add(self.authorized_user)

    def test_post(self):
        device = DeviceFactory.build()
        url = reverse('device-list')

        self.client.force_login(self.authorized_user)
        response = self.client.post(url, data={'some': 'test', 'data': 'here'}, format='json')
        self.client.logout()

        self.assertEqual(status.HTTP_201_CREATED, response.status_code)
        # And some more tests here

    def test_detail_logged_in(self):
        device = DeviceFactory.create()

        url = reverse('device-detail', kwargs={'pk': device.pk})

        self.client.force_login(self.authorized_user)
        response = self.client.get(url)
        self.client.logout()

        self.assertEqual(status.HTTP_200_OK, response.status_code, 'Wrong response code for {}'.format(url))
        # And some more tests here
</code>```

The first test works great. It posts the new record and all checks pass. The second test fails though. It gives an error saying

```<code>AssertionError: 200 != 302 : Wrong response code for /sa/devices/1/
</code>```

It turns out the list view redirects the user to the login screen. Why does the first test log the user in perfectly, but does the second test redirect the user to the login screen? Am I missing something?

Here is the view:

```<code>class APIAuthGroup(InAuthGroup):
    """
A permission to allow all GETS, but only allow a POST if a user is logged in,
and is a member of the slimme apparaten role inside keycloak.
    """
    allowed_group_names = [settings.KEYCLOAK_SA_WRITE_PERMISSION_NAME]

    def has_permission(self, request, view):
        return request.method in SAFE_METHODS \
               or super(APIAuthGroup, self).has_permission(request, view)

class DevicesViewSet(DatapuntViewSetWritable):
    """
    A view that will return the devices and makes it possible to post new ones
    """

    queryset = Device.objects.all().order_by('id')

    serializer_class = DeviceSerializer
    serializer_detail_class = DeviceSerializer

    http_method_names = ['post', 'list', 'get']

    permission_classes = [APIAuthGroup]
</code>```

答:
Your reasoning and code looks ok.

However you are not giving the full code, there must be error you are not seeing.

Suspicious fact

It isn't be default 302 when you are not logged in.
(@login_required, etc redirects but your code doesn't have it)

Your APIAuthGroup permission does allow GET requests for non-logged-in user ( return request.method in SAFE_METHODS), and you are using GET requests (self.client.get(url))

So it means you are not hitting the endpoint that you think you are hitting (your get request is not hitting the DevicesViewSet method)

Or it could be the case you have some global permission / redirect related setting in your settings.py which could be DRF related..
eg :

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}
</code>```

Guess

```<code>url = reverse('device-detail', kwargs={'pk': device.pk})
</code>```

might not point to the url you are thinking..
maybe there's another url (/sa/devices/1/) that overrides the viewset's url.  (You might have a django view based url)

And I didn't address why you are getting redirected after force_login.

If it's indeed login related redirect, all I can think of is self.authorized_user.refresh_from_db() or refreshing the request ..

I guess some loggin related property (such as session, or request.user) might point to old instance .. (I have no evidence or fact this can happen, but just a hunch) and you better off not logging out/in for every test case)

ContentLicense: CC BY-SA 4.0

Body:
I'm using Django Rest Framework to serve an API. I've got a couple tests which work great. To do a post the user needs to be logged in and I also do some checks for the detail view for a logged in user. I do this as follows:

class DeviceTestCase(APITestCase):
    USERNAME = "username"
    EMAIL = 'a@b.com'
    PASSWORD = "password"

    def setUp(self):
        self.sa_group, _ = Group.objects.get_or_create(name=settings.KEYCLOAK_SA_WRITE_PERMISSION_NAME)
        self.authorized_user = User.objects.create_user(self.USERNAME, self.EMAIL, self.PASSWORD)
        self.sa_group.user_set.add(self.authorized_user)

    def test_post(self):
        device = DeviceFactory.build()
        url = reverse('device-list')

        self.client.force_login(self.authorized_user)
        response = self.client.post(url, data={'some': 'test', 'data': 'here'}, format='json')
        self.client.logout()

        self.assertEqual(status.HTTP_201_CREATED, response.status_code)
        # And some more tests here

    def test_detail_logged_in(self):
        device = DeviceFactory.create()

        url = reverse('device-detail', kwargs={'pk': device.pk})

        self.client.force_login(self.authorized_user)
        response = self.client.get(url)
        self.client.logout()

        self.assertEqual(status.HTTP_200_OK, response.status_code, 'Wrong response code for {}'.format(url))
        # And some more tests here

The first test works great. It posts the new record and all checks pass. The second test fails though. It gives an error saying

AssertionError: 200 != 302 : Wrong response code for /sa/devices/1/

It turns out the list view redirects the user to the login screen. Why does the first test log the user in perfectly, but does the second test redirect the user to the login screen? Am I missing something?

Here is the view:

class APIAuthGroup(InAuthGroup):
    """
A permission to allow all GETS, but only allow a POST if a user is logged in,
and is a member of the slimme apparaten role inside keycloak.
    """
    allowed_group_names = [settings.KEYCLOAK_SA_WRITE_PERMISSION_NAME]

    def has_permission(self, request, view):
        return request.method in SAFE_METHODS \
               or super(APIAuthGroup, self).has_permission(request, view)

class DevicesViewSet(DatapuntViewSetWritable):
    """
    A view that will return the devices and makes it possible to post new ones
    """

    queryset = Device.objects.all().order_by('id')

    serializer_class = DeviceSerializer
    serializer_detail_class = DeviceSerializer

    http_method_names = ['post', 'list', 'get']

    permission_classes = [APIAuthGroup]

Body:
Your reasoning and code looks ok.

However you are not giving the full code, there must be error you are not seeing.

Suspicious fact

It isn't be default 302 when you are not logged in.
(@login_required, etc redirects but your code doesn't have it)

Your APIAuthGroup permission does allow GET requests for non-logged-in user ( return request.method in SAFE_METHODS), and you are using GET requests (self.client.get(url))

So it means you are not hitting the endpoint that you think you are hitting (your get request is not hitting the DevicesViewSet method)

Or it could be the case you have some global permission / redirect related setting in your settings.py which could be DRF related..
eg :

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

Guess

url = reverse('device-detail', kwargs={'pk': device.pk})

might not point to the url you are thinking..
maybe there's another url (/sa/devices/1/) that overrides the viewset's url.  (You might have a django view based url)

And I didn't address why you are getting redirected after force_login.

If it's indeed login related redirect, all I can think of is self.authorized_user.refresh_from_db() or refreshing the request ..

I guess some loggin related property (such as session, or request.user) might point to old instance .. (I have no evidence or fact this can happen, but just a hunch) and you better off not logging out/in for every test case)


问:
Finding most frequency number in array
By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.

```<code>class FindingMostFrequencyOccur {

    public static void main(String args[]) {
        int A[] = { 1, 2, 3, 3, 1, 3, 1};
        int M = 3; // Maximum Number in Array
        int result = findFrequency(M, A);
        System.out.println("Result "+result);
    }

    static int findFrequency(int M, int[] A) {
        int N = A.length;
        int[] count = new int[M + 1];
        for (int i = 0; i <= M; i++)
            count[i] = 0;
        int maxOccurence = 1;
        int index = -1;
        for (int i = 0; i < N; i++) {
            if (count[A[i]] > 0) {
                int tmp = count[A[i]];
                if (tmp > maxOccurence) {
                    maxOccurence = tmp;
                    index = i;
                }
                count[A[i]] = tmp + 1;
            } else {
                count[A[i]] = 1;
            }
        }
        return A[index];
    }
}
</code>```

Can you we improve in this line

```<code>if (count[A[i]] > 0) {
                    int tmp = count[A[i]];
                    if (tmp > maxOccurence) {
                        maxOccurence = tmp;
                        index = i;
                    }
                    count[A[i]] = tmp + 1;
                } else {
                    count[A[i]] = 1;
                }
</code>```

答:
To get the frequency of m in a use:

```<code>static int findFrequency(int m, int[] a) {
     return (int)IntStream.of(a).filter(i-> i==m).count();
}
</code>```

To get a map of all frequencies in a use:

```<code>static Map<Integer, Integer> findFrequency(int[] a) {
     Map<Integer, Integer> m = new HashMap<>();
     IntStream.of(a).distinct().forEach(i->{
            m.put(i, findFrequency(i,a));
     });
     return m;
}
</code>```

Title: Finding most frequency number in array

Body:
By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.

class FindingMostFrequencyOccur {

    public static void main(String args[]) {
        int A[] = { 1, 2, 3, 3, 1, 3, 1};
        int M = 3; // Maximum Number in Array
        int result = findFrequency(M, A);
        System.out.println("Result "+result);
    }

    static int findFrequency(int M, int[] A) {
        int N = A.length;
        int[] count = new int[M + 1];
        for (int i = 0; i <= M; i++)
            count[i] = 0;
        int maxOccurence = 1;
        int index = -1;
        for (int i = 0; i < N; i++) {
            if (count[A[i]] > 0) {
                int tmp = count[A[i]];
                if (tmp > maxOccurence) {
                    maxOccurence = tmp;
                    index = i;
                }
                count[A[i]] = tmp + 1;
            } else {
                count[A[i]] = 1;
            }
        }
        return A[index];
    }
}

Can you we improve in this line

if (count[A[i]] > 0) {
                    int tmp = count[A[i]];
                    if (tmp > maxOccurence) {
                        maxOccurence = tmp;
                        index = i;
                    }
                    count[A[i]] = tmp + 1;
                } else {
                    count[A[i]] = 1;
                }

Body:
To get the frequency of m in a use:

static int findFrequency(int m, int[] a) {
     return (int)IntStream.of(a).filter(i-> i==m).count();
}

To get a map of all frequencies in a use:

static Map<Integer, Integer> findFrequency(int[] a) {
     Map<Integer, Integer> m = new HashMap<>();
     IntStream.of(a).distinct().forEach(i->{
            m.put(i, findFrequency(i,a));
     });
     return m;
}


问:
Hyper-V - No Guest Internet
I'm using a Windows Server 2019 server from Microsoft Azure. I have installed Hyper-V with the management tools and am now trying to setup a Ubuntu 14.04LTS VM inside of Hyper-V. I create a new External Switch however when setting up the Ubuntu instance there it tells me that there is an issue with the DHCP server. When I check my network connections for the newly created switch there is IPV4 connectivity, with packets being sent and received.

Things that I have tried:

-Ensured that inside of the Virtual Switch Manager that in my newly created virtual switch, the external network is selected as my main internet adapter. And that the "Allow management os to share this network adapter".

-Tried selecting "Internal Network"

-Inside of the ubuntu server, tried dchlient -r and dhclient eth0 to try to retrieve a new IP (For internal network this has worked, but without internet access, for external ip it hangs on the command dhclient eth0)

-In Network Connections I have tried bridging the two connections (out of desperation, "bricks" the vps causing me to not be able to rdp, must create a new azure vm)

-I have tried right clicking the main "ethernet" inside the Network Connections and allowing sharing options to other users.

Please help as I'm quite lost as to why the Ubuntu Guest is not connecting to the internet with the new network switch

答:
The virtual switch connection types are very confusingly named, and sharing is somewhat flaky. I've had best results with the Internal Network. Most of the time it just works but there are certain situations when the NAT service breaks and you will have to restart some combination of the host and guest machines, possibly both -- I've not found a way to just restart the virtual switch service without restarting the host OS.

If you need to use the External Network type, be aware that your actual physical router will be in the mix, so you must make sure that it is properly configured, especially if you're doing MAC filtering on your router and the guest is not using the hardware MAC. This usually happens because of the virtualisation process itself, even if it's not something you've configured in the guest.

Title: Hyper-V - No Guest Internet


问:
How to pass the AJAX responseText into a variable
I want to know how to pass the AJAX responseText into a variable? I want to use it in another part of programe. The code "document.getElementById("showData").innerHTML = xhttp.responseText;" can display the return string correctly, but I cannot use a variable to receive it. </p>

```<code><?PHP
$currHr=date('H')-1;
?>

<form action="">

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}
}
?>
</Select>
</form>

<p id="showData">Let AJAX change this text.</p>

<script>

function rainSum(str)
{
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function ()
  {

 if (xhttp.readyState === 4 && xhttp.status === 200)
 {
   document.getElementById("showData").innerHTML = xhttp.responseText;
   window.x=xhttp.responseText;
    }
  };

  xhttp.open("GET", "barD.php?SelTime="+str, true);
  xhttp.send();
}

document.write(window.x);</script>
</code>```

答:
```<code>let res = rainSum("string")
function rainSum(str)
{
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function ()
  {

 if (xhttp.readyState === 4 && xhttp.status === 200)
 {
   return xhttp.responseText;
    }
  };

  xhttp.open("GET", "barD.php?SelTime="+str, true);
  xhttp.send();
}
</code>```

Body:
I want to know how to pass the AJAX responseText into a variable? I want to use it in another part of programe. The code "document.getElementById("showData").innerHTML = xhttp.responseText;" can display the return string correctly, but I cannot use a variable to receive it.

<?PHP
$currHr=date('H')-1;
?>

<form action="">

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}
?>
</Select>
</form>

Let AJAX change this text.


问:
How to construct an array of arrays with Powershell?
To group data, every time there's a "new person" as below, I want to add their info to that temporary array and reset that array to null.

Before each "new person" array is set to null, I want to add that array to an array of people.  An array of arrays.

How can I add one array into another?

```<code>$people = import-csv "./people.csv"

$h = @{}
$h.gettype()

$all_people

ForEach ($person in $people) {
  $new_person
  if ($person -match '[0-9]') {
    Write-host $person
  }
  else {
    write-host "new person"
    write-host $person
  }
}
</code>```

output:

```<code>thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}

thufir@dur:~/flwor/people$
</code>```

I have something like this:

```<code>$people = import-csv "./people.csv"

$all_people
$new_person = "new","person"

$new_person.GetType()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    $new_person.Add($person)
  }
  else {
    write-host "new person"
    write-host $person
    #$new_person = null
    $new_person = "new","person"
  }
}
</code>```

答:
Yes you can create array of arrays.

Example we create 3 arrays like

```<code>$a = 1..5
$b = 6..10
$c = 11..15
</code>```

Now we can add them in another array $d

```<code>$d = $a,$b,$c
</code>```

Now we can access them like:

```<code>$d[0]
# Output
# 1
# 2
# 3
# 4
# 5
$d[0][2]
# Output is $a arrays 3rd element
</code>```

Body:
To group data, every time there's a "new person" as below, I want to add their info to that temporary array and reset that array to null.

Before each "new person" array is set to null, I want to add that array to an array of people.  An array of arrays.

How can I add one array into another?

$people = import-csv "./people.csv"

$h = @{}
$h.gettype()

$all_people

ForEach ($person in $people) {
  $new_person
  if ($person -match '[0-9]') {
    Write-host $person
  }
  else {
    write-host "new person"
    write-host $person
  }
}

output:

thufir@dur:~/flwor/people$
thufir@dur:~/flwor/people$ pwsh foo.ps1

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
new person
@{people=joe}
@{people=phone1}
@{people=phone2}
@{people=phone3}
new person
@{people=sue}
@{people=cell4}
@{people=home5}
new person
@{people=alice}
@{people=atrib6}
@{people=x7}
@{people=y9}
@{people=z10}

thufir@dur:~/flwor/people$

I have something like this:

$people = import-csv "./people.csv"

$all_people
$new_person = "new","person"

$new_person.GetType()

ForEach ($person in $people) {

  if ($person -match '[0-9]') {
    Write-host $person
    $new_person.Add($person)
  }
  else {
    write-host "new person"
    write-host $person
    #$new_person = null
    $new_person = "new","person"
  }
}

Body:
Yes you can create array of arrays.

Example we create 3 arrays like

$a = 1..5
$b = 6..10
$c = 11..15

Now we can add them in another array $d

$d = $a,$b,$c

Now we can access them like:

$d[0]
# Output
# 1
# 2
# 3
# 4
# 5
$d[0][2]
# Output is $a arrays 3rd element


问:
Settimeout not clearing in react hooks- function component
I've trying to implement simple updates in a function component in react and seem to have stumbled onto some basic logical errors on my part. Can you help?

My code :

```<code>import React, { useState } from "react";
import "./App.css";

var timeout;  // this variable wasn't scoped inside the function?.

function App() {
  const [name, setUserName] = useState("");

  const [password, setUserPassword] = useState("");

  const [showHackMessage, setShowHackMessage] = useState(false);

  const enterUserName = e => {
    console.log(e.target.value);
    setUserName(e.target.value);
  };

  const enterUserPassword = (e) => {

    console.log(e.target.value,timeout);
    setUserPassword(e.target.value);
    if (e.target.value.length > 0) {
      timeout= setTimeout(()=>setShowHackMessage(true), 1000);
      console.log(timeout);

      /// Why did not  timeout= setTimeout(setShowHackMessage(true), 5000); work? is  setShowHackMessage not a function?
      //  timeout();
    }
    else if(e.target.value.length===0) {
      console.log("Tricky user!");
      console.log(timeout,'L29>>');
      //not working perfectly!
      clearTimeout(timeout);
      setShowHackMessage(false);
    }
  };

  return (
    <div className="App">
      <p>Login-Hacker</p>
      <input name={"email"} onChange={enterUserName}></input>
      <br></br>
      <br></br>

      <input name={"password"} onChange={(e)=>enterUserPassword(e)}></input>
      <p>Powered by Saurabh</p>
      {name.length > 0 && <p>Your name is {name}</p>}
      {password.length > 0 && <p>Your password is {password}</p>}
      {showHackMessage && <p className='awesome'>Now you are hacked!</p>}
    </div>
  );
}

export default App;
</code>```

So my first question would be:-

Why do i have to use callback while defining a setstate function in settimeout?
I tried

timeout= setTimeout(setShowHackMessage(true), 1000);
 and it didn't work, while

timeout= setTimeout(()=>setShowHackMessage(true), 1000);
works perfectly. Is setShowHackMessage (in useState not a function?)

If i define the variable var timeout inside the function, the cleartimeout doesn't work(shows as undefined in console), but works perfectly if i define it outside the function, as in the code. Is the whole function "rendered" after setstate( hence losing previous instance of variable timeout?).Should i have used refs for this?

Thank you.

答:
This is a simpler version. I removed the timeout variable as I don't see why you use it.

```<code>        import React, { useState, useCallback } from "react";
// import "./App.css";

// let timeout;  // this variable wasn't scoped inside the function?.
const EMPTY_STRING = "";

function App() {
const [name, setUserName] = useState("");
const [password, setUserPassword] = useState("");
const [showHackMessage, setShowHackMessage] = useState(false);
const [timer, setTimer] = useState(null);

const enterUserName = useCallback(
    value => {
    console.log(value);
    setUserName(value);
    },
    [setUserName]
);

const enterUserPassword = useCallback(
    value => {
    setShowHackMessage(false);
    setUserPassword(value);
    console.log("password value", value);
    if (timer) {
        console.log("clear Timer=>", timer);
        clearTimeout(timer);
    }
    if (value !== EMPTY_STRING) {
        setTimer(setTimeout(() => setShowHackMessage(true), 5000));
        console.log("set Timer=>", timer);
    }
    console.log("password", password);
    },
    [setUserPassword, setShowHackMessage, password, timer]
);

return (
    <div className="App">
    <p>Login-Hacker</p>
    <input
        name={"email"}
        value={name}
        onChange={e => enterUserName(e.target.value)}
    />
    <br />
    <br />

    <input
        name={"password"}
        value={password}
        onChange={e => enterUserPassword(e.target.value)}
    />
    <p>Powered by Saurabh</p>
    {name.length > 0 && <p>Your name is {name}</p>}
    {password.length > 0 && <p>Your password is {password}</p>}
    {showHackMessage && <p className="awesome">Now you are hacked!</p>}
    </div>
);
}

export default App;
</code>```

Body:
I've trying to implement simple updates in a function component in react and seem to have stumbled onto some basic logical errors on my part. Can you help?

My code :

import React, { useState } from "react";
import "./App.css";

var timeout;  // this variable wasn't scoped inside the function?.

function App() {
  const [name, setUserName] = useState("");

  const [password, setUserPassword] = useState("");

  const [showHackMessage, setShowHackMessage] = useState(false);

  const enterUserName = e => {
    console.log(e.target.value);
    setUserName(e.target.value);
  };

  const enterUserPassword = (e) => {

    console.log(e.target.value,timeout);
    setUserPassword(e.target.value);
    if (e.target.value.length > 0) {
      timeout= setTimeout(()=>setShowHackMessage(true), 1000);
      console.log(timeout);

      /// Why did not  timeout= setTimeout(setShowHackMessage(true), 5000); work? is  setShowHackMessage not a function?
      //  timeout();
    }
    else if(e.target.value.length===0) {
      console.log("Tricky user!");
      console.log(timeout,'L29>>');
      //not working perfectly!
      clearTimeout(timeout);
      setShowHackMessage(false);
    }
  };

  return (

Login-Hacker

      <input name={"email"} onChange={enterUserName}></input>

      <input name={"password"} onChange={(e)=>enterUserPassword(e)}></input>

Powered by Saurabh

      {name.length > 0 &&
Your name is {name}
}
      {password.length > 0 &&
Your password is {password}
}
      {showHackMessage &&
Now you are hacked!
}

  );
}

export default App;

So my first question would be:-

Why do i have to use callback while defining a setstate function in settimeout?
I tried

timeout= setTimeout(setShowHackMessage(true), 1000);
 and it didn't work, while

timeout= setTimeout(()=>setShowHackMessage(true), 1000);
works perfectly. Is setShowHackMessage (in useState not a function?)

If i define the variable var timeout inside the function, the cleartimeout doesn't work(shows as undefined in console), but works perfectly if i define it outside the function, as in the code. Is the whole function "rendered" after setstate( hence losing previous instance of variable timeout?).Should i have used refs for this?

Thank you.

Body:
This is a simpler version. I removed the timeout variable as I don't see why you use it.

        import React, { useState, useCallback } from "react";
// import "./App.css";

// let timeout;  // this variable wasn't scoped inside the function?.
const EMPTY_STRING = "";

function App() {
const [name, setUserName] = useState("");
const [password, setUserPassword] = useState("");
const [showHackMessage, setShowHackMessage] = useState(false);
const [timer, setTimer] = useState(null);

const enterUserName = useCallback(
    value => {
    console.log(value);
    setUserName(value);
    },
    [setUserName]
);

const enterUserPassword = useCallback(
    value => {
    setShowHackMessage(false);
    setUserPassword(value);
    console.log("password value", value);
    if (timer) {
        console.log("clear Timer=>", timer);
        clearTimeout(timer);
    }
    if (value !== EMPTY_STRING) {
        setTimer(setTimeout(() => setShowHackMessage(true), 5000));
        console.log("set Timer=>", timer);
    }
    console.log("password", password);
    },
    [setUserPassword, setShowHackMessage, password, timer]
);

return (
    <div className="App">
    <p>Login-Hacker</p>
    <input
        name={"email"}
        value={name}
        onChange={e => enterUserName(e.target.value)}
    />
    <br />
    <br />

    <input
        name={"password"}
        value={password}
        onChange={e => enterUserPassword(e.target.value)}
    />
    <p>Powered by Saurabh</p>
    {name.length > 0 && <p>Your name is {name}</p>}
    {password.length > 0 && <p>Your password is {password}</p>}
    {showHackMessage && <p className="awesome">Now you are hacked!</p>}
    </div>
);
}

export default App;


问:
Help creating Zend Framework Redirect
I'm trying to create a mod rewrite expression to redirect from localhost/1234 to localhost/controller/action?param=1234.

I have the following in my bootstrap.php, which redirects all requests in the form localhost/number

```<code>$routePublic = new Zend_Controller_Router_Route_Regex('^[\d]+(\.[\d]+){0,1}$', array( 1 => '' ,'controller' => 'content', 'action' => 'public'));
</code>```

However, I need to pass a param to my publicAction.

Thanks for the help. Newbies like me appreciate it more than you could ever believe!

答:
try this:

```<code>$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addRoute('name_of_route',
            new Zend_Controller_Router_Route('/url_of_route/*',
            array('controller'=>'controller_you_want_to_call','action'=>'action_you_want_to_call')));</code>```

note that the "*" after "url_of_route" is like a wildcard meaning anything can come after it

Also heres a link to a good article

Title: Help creating Zend Framework Redirect

Body:
I'm trying to create a mod rewrite expression to redirect from localhost/1234 to localhost/controller/action?param=1234.

I have the following in my bootstrap.php, which redirects all requests in the form localhost/number

$routePublic = new Zend_Controller_Router_Route_Regex('^[\d]+(\.[\d]+){0,1}$', array( 1 => '' ,'controller' => 'content', 'action' => 'public'));

However, I need to pass a param to my publicAction.

Thanks for the help. Newbies like me appreciate it more than you could ever believe!

Body:
try this:

$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addRoute('name_of_route',
            new Zend_Controller_Router_Route('/url_of_route/*',
            array('controller'=>'controller_you_want_to_call','action'=>'action_you_want_to_call')));

note that the "*" after "url_of_route" is like a wildcard meaning anything can come after it

Also heres a link to a good article


问:
How to extract the payload of a packet using Pyshark
I am trying to read the payload of all packets in a .pcap file using Pyshark. I am able to open and read the file, access the packets and their other information but I am not able to find the correct attribute/method to use to access the payload of a packet. Any suggestions ? Is there any other way to read packet payloads in .pcap files using python for windows 10 ?

(I tried using Scapy instead of Pyshark, but apparently there is some issue with running Scapy on Windows, it does not work on my system as well)

I found these lines in different code snippets of pyshark projects on the Internet and on StackOverflow. I tried them but none of them work :

```<code>import pyshark
cap = pyshark.FileCapture('file.pcap')
pkt = cap[1]

#for other information
print(pkt.tcp.flags_ack) #this works
print(pkt.tcp.flags_syn) #this works
print(pkt.tcp.flags_fin) #this works

#for payload
print(pkt.tcp.data) #does not work, AttributeError
print(pkt.tcp.payload) #does not work, AttributeError
print(pkt.data.data) #does not work, AttributeError
</code>```

答:
This code will print the value associated with the field name tcp.payload.

```<code>capture = pyshark.FileCapture(pcap_file, display_filter='tcp')
for packet in capture:
    field_names = packet.tcp._all_fields
    field_values = packet.tcp._all_fields.values()
    for field_name in field_names:
        for field_value in field_values:
            if field_name == 'tcp.payload':
               print(f'{field_name} -- {field_value}')

# outputs
tcp.payload -- \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7AP\xc2\xb7\xc2\xb7\xc2\xb7
tcp.payload -- 0x00001e2c
tcp.payload -- 113977858
...
</code>```

Body:
I am trying to read the payload of all packets in a .pcap file using Pyshark. I am able to open and read the file, access the packets and their other information but I am not able to find the correct attribute/method to use to access the payload of a packet. Any suggestions ? Is there any other way to read packet payloads in .pcap files using python for windows 10 ?

(I tried using Scapy instead of Pyshark, but apparently there is some issue with running Scapy on Windows, it does not work on my system as well)

I found these lines in different code snippets of pyshark projects on the Internet and on StackOverflow. I tried them but none of them work :

import pyshark
cap = pyshark.FileCapture('file.pcap')
pkt = cap[1]

#for other information
print(pkt.tcp.flags_ack) #this works
print(pkt.tcp.flags_syn) #this works
print(pkt.tcp.flags_fin) #this works

#for payload
print(pkt.tcp.data) #does not work, AttributeError
print(pkt.tcp.payload) #does not work, AttributeError
print(pkt.data.data) #does not work, AttributeError

Body:
This code will print the value associated with the field name tcp.payload.

capture = pyshark.FileCapture(pcap_file, display_filter='tcp')
for packet in capture:
    field_names = packet.tcp._all_fields
    field_values = packet.tcp._all_fields.values()
    for field_name in field_names:
        for field_value in field_values:
            if field_name == 'tcp.payload':
               print(f'{field_name} -- {field_value}')

# outputs
tcp.payload -- \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7AP\xc2\xb7\xc2\xb7\xc2\xb7
tcp.payload -- 0x00001e2c
tcp.payload -- 113977858
...


问:
Nmap can't find a listening port
I created a AWS instance today, and I am running a server and listen to 19999 port. let's see what I got:

```<code>root@ip-172-31-18-145:/home/ubuntu# sudo lsof -i -P -n | grep 19999
ssserver  20387            root    4u  IPv4  65547      0t0  TCP *:19999 (LISTEN)
ssserver  20387            root    5u  IPv4  65548      0t0  UDP *:19999
</code>```

But i couldn't connect my port on my remote client-side, so I was trying to use nmap. here what I got.

```<code>root@ip-172-31-18-145:/home/ubuntu# nmap -Pn 127.0.0.1

Starting Nmap 7.60 ( https://nmap.org ) at 2020-02-15 13:47 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000030s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
</code>```

My question is what's wrong with nmap? To make sure the port is listening I am running nc to try to listen the 19999 again. and here is the output:

```<code>ubuntu@ip-172-31-18-145:~$ nc -l 19999
nc: Address already in use
</code>```

答: Nothing is wrong with nmap by default it only scan a 1000 most common ports. You can you use nmap -Pn 127.0.0.1 -p 19999</p>

Title: Nmap can't find a listening port

Body:
I created a AWS instance today, and I am running a server and listen to 19999 port. let's see what I got:

root@ip-172-31-18-145:/home/ubuntu# sudo lsof -i -P -n | grep 19999
ssserver  20387            root    4u  IPv4  65547      0t0  TCP *:19999 (LISTEN)
ssserver  20387            root    5u  IPv4  65548      0t0  UDP *:19999

But i couldn't connect my port on my remote client-side, so I was trying to use nmap. here what I got.

root@ip-172-31-18-145:/home/ubuntu# nmap -Pn 127.0.0.1

Starting Nmap 7.60 ( https://nmap.org ) at 2020-02-15 13:47 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000030s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
22/tcp open  ssh

My question is what's wrong with nmap? To make sure the port is listening I am running nc to try to listen the 19999 again. and here is the output:

ubuntu@ip-172-31-18-145:~$ nc -l 19999
nc: Address already in use


问:
How do I get DeviceOrientationEvent and DeviceMotionEvent to work on Safari?
I'm trying to implement DeviceOrientationEvent and DeviceMotionEvent on my website for a 3D effect. However, the console doesn't log any info and apparently iOS 13 requires a user set permission to start doing this. I can't seem to figure out how to set it up properly.

I've done some research and this is what I found: https://github.com/w3c/deviceorientation/issues/57#issuecomment-498417027

All other methods provided online are not usable anymore sadly.

```<code>window.addEventListener('deviceorientation', function(event) {
    console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});
</code>```

I get the following error message:

[Warning] No device motion or orientation events will be fired until permission has been requested and granted.

答:
You need a click or a user gesture to call the requestPermission().
Like this :

```<code><script type="text/javascript">
    function requestOrientationPermission(){
        DeviceOrientationEvent.requestPermission()
        .then(response => {
            if (response == 'granted') {
                window.addEventListener('deviceorientation', (e) => {
                    // do something with e
                })
            }
        })
        .catch(console.error)
    }
</script>

<button onclick='requestOrientationPermission();'>Request orientation permission</button>
</code>```

Note : if you click on cancel on the permission prompt and want to test it again, you will need to quit Safari and launch it back for the prompt to come back.

Body:
I'm trying to implement DeviceOrientationEvent and DeviceMotionEvent on my website for a 3D effect. However, the console doesn't log any info and apparently iOS 13 requires a user set permission to start doing this. I can't seem to figure out how to set it up properly.

I've done some research and this is what I found: https://github.com/w3c/deviceorientation/issues/57#issuecomment-498417027

All other methods provided online are not usable anymore sadly.

window.addEventListener('deviceorientation', function(event) {
    console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});

I get the following error message:

[Warning] No device motion or orientation events will be fired until permission has been requested and granted.

Body:
You need a click or a user gesture to call the requestPermission().
Like this :

<script type="text/javascript">
    function requestOrientationPermission(){
        DeviceOrientationEvent.requestPermission()
        .then(response => {
            if (response == 'granted') {
                window.addEventListener('deviceorientation', (e) => {
                    // do something with e
                })
            }
        })
        .catch(console.error)
    }
</script>

<button onclick='requestOrientationPermission();'>Request orientation permission</button>

Note : if you click on cancel on the permission prompt and want to test it again, you will need to quit Safari and launch it back for the prompt to come back.


问:
TypeError: undefined is not an object (evaluating 'event.target.value')
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

```<code>export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}
</code>```

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

答:
That's not working as expected because react-native has 2 different onChange functions:

<TextInput
    onChange={e => console.log(e.nativeEvent.text)}
    onChangeText={text => console.log(text)} />
```

<p>The first one (<code>onChange</code>), is not structured like on the web:</p>

<pre class="lang-js prettyprint-override"><code>event : {
    nativeEvent : {
        eventCount,
        target,
        text
    }
}
</code>```

and the second one, which you appear to be using only gives you the text as a string so you don't have to dig through layers of event properties to get it. You will either have to change your handler function to expect text or bind to onChange rather than onChangeText on the TextInput.

Body:
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

Body:
That's not working as expected because react-native has 2 different onChange functions:

<TextInput
    onChange={e => console.log(e.nativeEvent.text)}
    onChangeText={text => console.log(text)} />

The first one (onChange), is not structured like on the web:

event : {
    nativeEvent : {
        eventCount,
        target,
        text
    }
}

and the second one, which you appear to be using only gives you the text as a string so you don't have to dig through layers of event properties to get it. You will either have to change your handler function to expect text or bind to onChange rather than onChangeText on the TextInput.


问:
Hashtable key with point
How do I issue a hash table key with a point character, such as FlatAppearance.BorderSize, so that it is correct?

```<code>$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry
    FlatAppearance.BorderSize = 0
}
</code>```

```<code>$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry too
    "FlatAppearance.BorderSize" = 0
}
</code>```

```<code>$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry too too
    FlatAppearance = @{ BorderSize = 0 }
}
</code>```

Of course, I can write it like that

```<code>$Button = [System.Windows.Forms.Button] @{}
$Button.FlatAppearance.BorderSize = 0
</code>```

However, it is more convenient to write inside the hash table. But how? Thanks

答:
Since the Button type's .FlatAppearance property is of type FlatButtonAppearance, there's no good solution in this case, because the FlatButtonAppearance type has no public, parameterless constructor.

If it did, you would be able to write:

```<code>using namespace System.Windows.Forms

$Button = [Button] @{

    # !! This is how you would generally do it, but
    # !! IN THIS CASE IT DOESN'T WORK, due to lack of an appropriate constructor.
    FlatAppearance = [FlatButtonAppearance] @{ BorderSize = 0 }
}
</code>```

The above syntax is akin to C#'s object initializer syntax, explained in the next section.

Object initializer syntax in PowerShell:

For a cast to a type literal ([...]) from a hashtable (@{ ... }) or preexisting [pscustomobject] instance[1] to perform implicit construction (implicit creation of an instance) and then multi-property initialization to work, the following prerequisites must be met:

The target type must have a constructor (possibly among others[2]) that is:

public

and takes no parameters[3]

The names of the type's public properties must match the hashtable entries' keys and the entries' values must be have the same or a compatible type as the target properties.

This allows PowerShell to create an instance behind the scenes simply by calling new SomeType() ([SomeType]::new() in PowerShell syntax), followed by assigning the public properties' values from the hashtable entries of the same name.

Note: Such casts, available in PowerShell v3+, are in effect syntactic sugar for calling the

New-Object cmdlet with the -Property parameter; only the latter works in v2.

Aside from consulting a type's documentation, you can easily inspect a type's constructors in PowerShell by calling the PowerShell-supplied static ::new method without parentheses (()):

```<code>PS> [System.Windows.Forms.FlatButtonAppearance]::new
# NO OUTPUT, which means the type has no public constructors at all.

# [ProcessStartInfo] has several public constructors, among them
# a public parameterless one, so you *can* initialize it by hashtable.
PS> [System.Diagnostics.ProcessStartInfo]::new

OverloadDefinitions
-------------------
System.Diagnostics.ProcessStartInfo new()
System.Diagnostics.ProcessStartInfo new(string fileName)
System.Diagnostics.ProcessStartInfo new(string fileName, string arguments)

</code>```

To determine a type's public, writeable instance properties:

```<code>PS> [System.Windows.Forms.FlatButtonAppearance].GetProperties('Public, Instance') |
       ? CanWrite | Select-Object Name, PropertyType

Name               PropertyType
----               ------------
BorderSize         System.Int32
BorderColor        System.Drawing.Color
CheckedBackColor   System.Drawing.Color
MouseDownBackColor System.Drawing.Color
MouseOverBackColor System.Drawing.Color
</code>```

[1] For instance, this is useful for objects deserialized from JSON, which become [pscustomobject] instances; e.g.: $obj = '{ "Text": "Submit" }' | ConvertFrom-Json; $button = [Button] $obj

[2] Edge case: There mustn't also be a single-parameter public constructor with one of the following parameter types, because it would bind the cast operand as-is:

[object] or

when casting from a hashtable (@{ ... }): [hashtable] or [System.Collections.IDictionary]

when casting from a [pscustomobject] instance: [psobject] or [pscustomobject]

[3] Conveniently, if you define a type (class) without declaring any constructor, you get a public parameterless one by default; e.g., in the following PowerShell example class Foo implicitly provides such a constructor:

class Foo { [string] $Bar }; $foo = [Foo] @{ Bar = 'None' }

Title: Hashtable key with point

Body:
How do I issue a hash table key with a point character, such as FlatAppearance.BorderSize, so that it is correct?

$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry
    FlatAppearance.BorderSize = 0
}

$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry too
    "FlatAppearance.BorderSize" = 0
}

$Button = [System.Windows.Forms.Button] @{

    # This is not a valid entry too too
    FlatAppearance = @{ BorderSize = 0 }
}

Of course, I can write it like that

$Button = [System.Windows.Forms.Button] @{}
$Button.FlatAppearance.BorderSize = 0

However, it is more convenient to write inside the hash table. But how? Thanks

Body:
Since the Button type's .FlatAppearance property is of type FlatButtonAppearance, there's no good solution in this case, because the FlatButtonAppearance type has no public, parameterless constructor.

If it did, you would be able to write:

using namespace System.Windows.Forms

$Button = [Button] @{

    # !! This is how you would generally do it, but
    # !! IN THIS CASE IT DOESN'T WORK, due to lack of an appropriate constructor.
    FlatAppearance = [FlatButtonAppearance] @{ BorderSize = 0 }
}

The above syntax is akin to C#'s object initializer syntax, explained in the next section.

Object initializer syntax in PowerShell:

For a cast to a type literal ([...]) from a hashtable (@{ ... }) or preexisting [pscustomobject] instance[1] to perform implicit construction (implicit creation of an instance) and then multi-property initialization to work, the following prerequisites must be met:

The target type must have a constructor (possibly among others[2]) that is:

public

and takes no parameters[3]

The names of the type's public properties must match the hashtable entries' keys and the entries' values must be have the same or a compatible type as the target properties.

This allows PowerShell to create an instance behind the scenes simply by calling new SomeType() ([SomeType]::new() in PowerShell syntax), followed by assigning the public properties' values from the hashtable entries of the same name.

Note: Such casts, available in PowerShell v3+, are in effect syntactic sugar for calling the

New-Object cmdlet with the -Property parameter; only the latter works in v2.

Aside from consulting a type's documentation, you can easily inspect a type's constructors in PowerShell by calling the PowerShell-supplied static ::new method without parentheses (()):

PS> [System.Windows.Forms.FlatButtonAppearance]::new
# NO OUTPUT, which means the type has no public constructors at all.

# [ProcessStartInfo] has several public constructors, among them
# a public parameterless one, so you *can* initialize it by hashtable.
PS> [System.Diagnostics.ProcessStartInfo]::new

OverloadDefinitions
-------------------
System.Diagnostics.ProcessStartInfo new()
System.Diagnostics.ProcessStartInfo new(string fileName)
System.Diagnostics.ProcessStartInfo new(string fileName, string arguments)

To determine a type's public, writeable instance properties:

PS> [System.Windows.Forms.FlatButtonAppearance].GetProperties('Public, Instance') |
       ? CanWrite | Select-Object Name, PropertyType

Name               PropertyType
----               ------------
BorderSize         System.Int32
BorderColor        System.Drawing.Color
CheckedBackColor   System.Drawing.Color
MouseDownBackColor System.Drawing.Color
MouseOverBackColor System.Drawing.Color

[1] For instance, this is useful for objects deserialized from JSON, which become [pscustomobject] instances; e.g.: $obj = '{ "Text": "Submit" }' | ConvertFrom-Json; $button = [Button] $obj

[2] Edge case: There mustn't also be a single-parameter public constructor with one of the following parameter types, because it would bind the cast operand as-is:

[object] or

when casting from a hashtable (@{ ... }): [hashtable] or [System.Collections.IDictionary]

when casting from a [pscustomobject] instance: [psobject] or [pscustomobject]

[3] Conveniently, if you define a type (class) without declaring any constructor, you get a public parameterless one by default; e.g., in the following PowerShell example class Foo implicitly provides such a constructor:

class Foo { [string] $Bar }; $foo = [Foo] @{ Bar = 'None' }


问:
Can't get display resolution for all devices using EnumDisplaySettings
I need to get the current display resolution of all monitors attached to the computer.

I can succesfully enum the display devices using the EnumDisplayDevicesA API but for an unknown reason I can't get the current display resolution for the device \\.\DISPLAY2 using the EnumDisplayDevicesA API.
Here is the code:

```<code>displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[index].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[index].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Collect the settings
    while(EnumDisplaySettingsA(devices[index].DeviceName, mode, (DEVMODEA *)&(settings[displays] ) ) )
    {
        mode++;
    };

    // Read the current settings
    result = EnumDisplaySettingsA(devices[index].DeviceName, ENUM_CURRENT_SETTINGS, (DEVMODEA *)&(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }
}
</code>```

Note that this code works flawlessly on some computers while on computers with multiple video cards it fails. For examle it fails on a laptop with an Intel HD Graphicw 630 + Nvidia Quadro M1200 where the active displays are the main laptop display and an exteral display attached through either the HDMI or DP port). More precisely on these computers I can get the correct resolution for the first display device (\\.\DISPLAY1) but on the second display device (\\.\DISPLAY2) the returned width and height is 0.

The EnumDisplaySettingsA API just return 0 as well as the GetLastError API.

What does  devices represent ? Are they a monitor attached to a single video card or are they just monitors attached to whatever video card ?

NOTE: Using EnumDisplayMonitors I can get the resolution of all monitors while EnumDisplaySettingsA fails.

答:
The problem is not related to the windows API nor related to the casting. The casting is not needed so I removed it.
This is caused by a wrong usage of the variables in the code. As I said I only want the current resolution of each monitor and on every index of both devices and settings structures I only want data related to active displays. This is ensured by the usage of the displays variable which is only incremented when the device has readable settings. Conversely the index variable should be incremented to each loop until the EnumEnumDisplayDevicesA fails.

Unfortunately I used index also for initializing the structure and passing the device name to EnumDisplaySettingsA. My bad. So I was filling the devices structure using the devices[displays] statement while the structure passed to EnumDisplaySettingsA was devices[index]. In other words the incorrect name was passed to the API ant this is the reason while it was failing. On some computers it was working because the active monitor were the first but as soon as the DISPLAY1 or DISPALY2 was not connected the application would behave incorrectly.

This is the correct code:

```<code>displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[displays].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[displays].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Cache the settings
    EnumDisplaySettingsA(devices[displays].DeviceName, 0, &(settings[displays] ) )

    // Read the current settings
    result = EnumDisplaySettingsA(devices[displays].DeviceName, ENUM_CURRENT_SETTINGS, &(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }
</code>```

Body:
I need to get the current display resolution of all monitors attached to the computer.

I can succesfully enum the display devices using the EnumDisplayDevicesA API but for an unknown reason I can't get the current display resolution for the device \\.\DISPLAY2 using the EnumDisplayDevicesA API.
Here is the code:

displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[index].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[index].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Collect the settings
    while(EnumDisplaySettingsA(devices[index].DeviceName, mode, (DEVMODEA *)&(settings[displays] ) ) )
    {
        mode++;
    };

    // Read the current settings
    result = EnumDisplaySettingsA(devices[index].DeviceName, ENUM_CURRENT_SETTINGS, (DEVMODEA *)&(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }
}

Note that this code works flawlessly on some computers while on computers with multiple video cards it fails. For examle it fails on a laptop with an Intel HD Graphicw 630 + Nvidia Quadro M1200 where the active displays are the main laptop display and an exteral display attached through either the HDMI or DP port). More precisely on these computers I can get the correct resolution for the first display device (\\.\DISPLAY1) but on the second display device (\\.\DISPLAY2) the returned width and height is 0.

The EnumDisplaySettingsA API just return 0 as well as the GetLastError API.

What does  devices represent ? Are they a monitor attached to a single video card or are they just monitors attached to whatever video card ?

NOTE: Using EnumDisplayMonitors I can get the resolution of all monitors while EnumDisplaySettingsA fails.

Body:
The problem is not related to the windows API nor related to the casting. The casting is not needed so I removed it.
This is caused by a wrong usage of the variables in the code. As I said I only want the current resolution of each monitor and on every index of both devices and settings structures I only want data related to active displays. This is ensured by the usage of the displays variable which is only incremented when the device has readable settings. Conversely the index variable should be incremented to each loop until the EnumEnumDisplayDevicesA fails.

Unfortunately I used index also for initializing the structure and passing the device name to EnumDisplaySettingsA. My bad. So I was filling the devices structure using the devices[displays] statement while the structure passed to EnumDisplaySettingsA was devices[index]. In other words the incorrect name was passed to the API ant this is the reason while it was failing. On some computers it was working because the active monitor were the first but as soon as the DISPLAY1 or DISPALY2 was not connected the application would behave incorrectly.

This is the correct code:

displays = 0;
result = 1;

for (index = 0; result != 0; index++)
{
    devices[displays].cb = sizeof(DISPLAY_DEVICEA);
    result = EnumDisplayDevicesA(NULL, index, &(devices[displays] ), 0);

    if (result == 0)
    {
            break;
    }

    settings[displays].dmSize = sizeof(DEVMODEA);
    mode = 0;

    // Cache the settings
    EnumDisplaySettingsA(devices[displays].DeviceName, 0, &(settings[displays] ) )

    // Read the current settings
    result = EnumDisplaySettingsA(devices[displays].DeviceName, ENUM_CURRENT_SETTINGS, &(settings[displays] ) );

    if (result != 0)
    {
        displays++;
    }
    else
    {
        result = GetLastError();
        printf("Error while readind display settings %d\n", result);

        //Skip this device
        result = 1;
    }


问:
ReactJS: How to display selected value from dropdown in input fields?
I am trying to do following:

The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.

I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?

Here is my code:

```<code>import React from 'react';

export default class Lisatehtava1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num1: 0,
            num2: 0,
            total: 0,
            results: [],
        }
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        this.setState({
            [name]: value
        })
    }

    add = () => {

        const { num1, num2 } = this.state;

        this.setState({
            total: (parseInt(num1) + parseInt(num2))

        }, () => {

            let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };

            const t = [...this.state.results, result];

            this.setState({ results: t }, () => {
                this.setState({ num1: "" }, () => {
                    this.setState({ num2: "" });

                });
            });
        })
    }

    render() {

        let dropdown = this.state.results.map((item, id) => {
            return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
        });

        return (
            <div>
                <div>
                    <label>Numero 1</label>
                    <input type="text" name="num1" onChange={this.handleChange} />
                </div>
                <div>
                    <label>Numero 2</label>
                    <input type="text" name="num2" onChange={this.handleChange} />
                </div>
                <button onClick={this.add}>Add</button>
                <div><select onChange={this.handleChange}>{dropdown}</select></div>
            </div>
        );
    }
}
</code>```

答:
```<code><input type="text" name="num2" onChange={this.handleChange} />
</code>```

Here in the input, you are not assigning the value you get after calling onChange function. So it's always empty.

Write it as:

```<code><input type="text" name="num2" onChange={this.handleChange} value={this.state.num1} />
</code>```

Body:
I am trying to do following:

The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.

I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?

Here is my code:

import React from 'react';

export default class Lisatehtava1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num1: 0,
            num2: 0,
            total: 0,
            results: [],
        }
    }

    handleChange = (e) => {
        const { name, value } = e.target;
        this.setState({
            [name]: value
        })
    }

    add = () => {

        const { num1, num2 } = this.state;

        this.setState({
            total: (parseInt(num1) + parseInt(num2))

        }, () => {

            let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };

            const t = [...this.state.results, result];

            this.setState({ results: t }, () => {
                this.setState({ num1: "" }, () => {
                    this.setState({ num2: "" });

                });
            });
        })
    }

    render() {

        let dropdown = this.state.results.map((item, id) => {
            return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
        });

        return (

                    Numero 1
                    <input type="text" name="num1" onChange={this.handleChange} />

                    Numero 2
                    <input type="text" name="num2" onChange={this.handleChange} />

                <button onClick={this.add}>Add</button>

<select onChange={this.handleChange}>{dropdown}</select>

        );
    }
}

Body:
<input type="text" name="num2" onChange={this.handleChange} />

Here in the input, you are not assigning the value you get after calling onChange function. So it's always empty.

Write it as:

<input type="text" name="num2" onChange={this.handleChange} value={this.state.num1} />


问:
How to add empty data row in Datatable using angular2+?
I want to add empty data row. My requirement is like columns are dynamic. I have tried using dtInstance to add the row. it's throwing some error.

here is the link

https://stackblitz.com/edit/how-to-replace-all-the-columns-dynamically-in-data-table-gvfose?file=app/app.component.ts

Please let me know if more details required.

答:
There is a simple demo for your requirement that puts the other button to save the empty column you want to access the data.

For easy to use, add DATA button that would be shown the blank row with input, the style you desire to set up the CSS and don't forgot the CSS scope for your by Encapsulation.

DEMO

If the operation field is superfluous, rid it off and place the event for three columns after entering with your logical condition.

Annoying Button

The add DATA could be replaced with the below code, setup the life hook instead for insert the method in the constructor.

ngAfterViewInit (){
  this.addData();
}
```


问:
ISerialization Constructor not getting called
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

```<code>public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }
</code>```

If I send the following XML to be deserialzed

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>
</code>```

using the following code to deserialize

```<code>serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");
</code>```

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

```<code><?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>
</code>```

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

答:
XmlSerializer does not use SerializableAttribute, ISerializable nor the constructor taking the SerializationInfo info and StreamingContext parameters.  Those constructs are used when using SoapFormatter (obsolete) and BinaryFormatter for serializing.</p>

```<code>        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            Class1 c1 = new Class1();
            bf.Serialize(ms, c1);

            ms.Position = 0;
            Class1 c2 = bf.Deserialize(ms) as Class1;
        }
</code>```

OwnerDisplayName: Paleta

ContentLicense: CC BY-SA 2.5

Body:
EDIT: The solution to my problem is to implement IXMLSerializer. Thanks everyone for the quick responses.

Hi everyone, I'm having this issue and I do not seem to a find a proper solution to it.

I have the following class

public class Child
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

        }
        [Serializable]
        public class Test: ISerializable
        {
            private int _id;

            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }

            private Child _child = new Child();

            public Child Child
            {
                get { return _child; }
                set { _child = value; }
            }

            public Test()
            {
            }
            protected Test(SerializationInfo info, StreamingContext context)
            {
                if (info.MemberCount > 1)
                    Child.Id = info.GetInt32("ChildId");
            }

            #region ISerializable Members

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("ChildId", Child.Id);
            }

            #endregion
        }

If I send the following XML to be deserialzed

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>

using the following code to deserialize

serializer.Deserialize(new StringReader("<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><ChildId>10</ChildId></Test>");

I supposed that would call my Serialization constructor, but the thing is that is never getting called.

I am using the above posted XML instead of this one

<?xml version="1.0" encoding="utf-16"?><Test><Id>0</Id><Child><Id>10</Id></Child></Test>

Because I'm getting the xml posted from another application, so I need to manually created child objects and assigned its value manually from within the constructor.

I'll really appreciate all the help and guidance you can provide me.

LastEditorDisplayName: Paleta

Body:
XmlSerializer does not use SerializableAttribute, ISerializable nor the constructor taking the SerializationInfo info and StreamingContext parameters.  Those constructs are used when using SoapFormatter (obsolete) and BinaryFormatter for serializing.

        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            Class1 c1 = new Class1();
            bf.Serialize(ms, c1);

            ms.Position = 0;
            Class1 c2 = bf.Deserialize(ms) as Class1;
        }


问:
How reliable is HTTP_REFERER?
I need to check and record the referrer of visitors to my web application. How reliable is using HTTP_REFERER? And are there other alternatives?

答:
Using HTTP_REFERER isn't reliable, its value is dependent on the HTTP Referer header sent by the browser or client application to the server and therefore can't be trusted because it can be manipulated.

Regarding the Referer header, section 15.1.2 of RFC2616 states:

Therefore, applications SHOULD supply
as much control over this information
as possible to the provider of that
information.

and

We suggest, though do not require,
that a convenient toggle interface be
provided for the user to enable or
disable the sending of From and
Referer information.

Many online privacy tools mangle this value and many browsers such as FireFox have for a long time permitted users to prevent this header being sent. So in a nutshell, I wouldn't rely on it for any serious purpose. For example, securing forms so that drive-by spammers can't post values, because the Referer can be spoofed.

For further reading see:

Using referer field for authentication or authorization (WayBackMachine)

Title: How reliable is HTTP_REFERER?