问:
Windows phone 7 reading XML with XDocument
Hi im trying to make my first windows phone 7 app. It involves querying a server about flight information. Then receiving a XML document. I then want to create a series of objects based on the XML I get back. However there is a problem since the object values are blank.

My Code

```<code>    private void SearchButton_Click(object sender, RoutedEventArgs e)
    {
        getResults("http://test.com/");
    }

    public void getResults(string websiteURL)
    {
        WebClient c = new WebClient();
        c.DownloadStringAsync(new Uri(websiteURL));
        c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
    }

    void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        lock (this)
        {
            string s = e.Result;
            XmlReader r = XmlReader.Create(new MemoryStream(System.Text.UnicodeEncoding.Unicode.GetBytes(s)));
            // So something with the XML we get back
            XDocument data = XDocument.Load(r);
            var ns = data.Root.GetDefaultNamespace();
            var flights = from query in data.Descendants(ns+"Flight")
                              select new Flight
                              {
                                  AircraftType = (int)query.Element(ns + "AircraftType"),
                                  ArrivalTerminal = (int)query.Element(ns + "ArrivalTerminal"),
                                  Carrier = (string)query.Element(ns + "Carrier"),
                                  DepartureTerminal = (int)query.Element(ns + "DepartureTerminal"),
                                  Duration = (string)query.Element(ns + "Duration"),
                                  EndDateTime = (string)query.Element(ns + "EndDateTime"),
                                  EndPoint = (string)query.Element(ns + "EndPoint"),
                                  FlightIndexNo = (int)query.Element(ns + "FlightIndexNo"),
                                  FlightNo = (int)query.Element(ns + "FlightNo"),
                                  NumStops = (int)query.Element(ns + "NumStops"),
                                  OperatedBy = (string)query.Element(ns + "OperatedBy"),
                                  StartDateTime = (string)query.Element(ns + "StartDateTime"),
                                  StartPoint = (string)query.Element(ns + "StartPoint")
                              };
            //checking if anything is there.
            string result ="";

            foreach (Flight i in flights)
            {
                result += i.Carrier;
            }
            resultsBlock.Text = result;

        }
    }

    public class Flight
    {
        public int aircraftType;
        public int arrivalTerminal;
        public string carrier;
        public int departureTerminal;
        public string duration;
        public string endDateTime;
        public string endPoint;
        public int flightIndexNo;
        public int flightNo;
        public int numStops;
        public string operatedBy;
        public string startDateTime;
        public string startPoint;

        //Getter and setters
</code>```

and the section of XML I want looks like this. This is also the first use of the Flight tag in the XML. Added the start of the XML whole thing is hundreds of lines long so won't but it all up. The Flight Tag I want is burred down in there.

```<code><FindFlightsResponse xmlns="urn:webjet.com.au" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<DisplayMessage i:nil="true" />
<OutboundFlightInfo>
          ...
              <Flight>
                    <AircraftType>734</AircraftType>
                    <ArrivalTerminal>3</ArrivalTerminal>
                    <Carrier>QF</Carrier>
                    <DepartureTerminal>1</DepartureTerminal>
                    <Duration>PT1H25M</Duration>
                    <EndDateTime>2011-04-20T07:25:00</EndDateTime>
                    <EndPoint>SYD</EndPoint>
                    <FlightIndexNo>1</FlightIndexNo>
                    <FlightNo>400</FlightNo>
                    <NumStops>0</NumStops>
                    <OperatedBy>QF</OperatedBy>
                    <StartDateTime>2011-04-20T06:00:00</StartDateTime>
                    <StartPoint>MEL</StartPoint>
                </Flight>
</code>```

I've probably made some simple mistake.
All help appreciated.
Thanks.
edit im now getting a method passing error. I changed the datetime to string for simplicity

答:
My guess is you're not showing us the complete XML and it likely has a default namespace specified. A namespace will look like xmlns="http://www.domain.com". If this is indeed the case then your LINQ to XML queries need to reference that namespace, and this can be done as follows:

```<code>var ns = data.Root.GetDefaultNamespace();
var flights = from query in data.Descendants(ns + "Flight")
              select new Flight
              {
                  AircraftType = (int)query.Element(ns + "AircraftType"),
                  ArrivalTerminal = (int)query.Element(ns + "ArrivalTerminal"),
                  Carrier = (string)query.Element(ns + "Carrier"),
                  DepartureTerminal = (int)query.Element(ns + "DepartureTerminal"),
                  Duration = (string)query.Element(ns + "Duration"),
                  EndDateTime = (DateTime)query.Element(ns + "EndDateTime"),
                  EndPoint = (string)query.Element(ns + "EndPoint"),
                  FlightIndexNo = (int)query.Element(ns + "FlightIndexNo"),
                  FlightNo = (int)query.Element(ns + "FlightNo"),
                  NumStops = (int)query.Element(ns + "NumStops"),
                  OperatedBy = (string)query.Element(ns + "OperatedBy"),
                  StartDateTime = (DateTime)query.Element(ns + "StartDateTime"),
                  StartPoint = (string)query.Element(ns + "StartPoint")
              };
</code>```

Notice that you need to prefix each element name with the namespace, hence the use of ns + throughout the code.

Body:
Hi im trying to make my first windows phone 7 app. It involves querying a server about flight information. Then receiving a XML document. I then want to create a series of objects based on the XML I get back. However there is a problem since the object values are blank.

My Code

    private void SearchButton_Click(object sender, RoutedEventArgs e)
    {
        getResults("http://test.com/");
    }

    public void getResults(string websiteURL)
    {
        WebClient c = new WebClient();
        c.DownloadStringAsync(new Uri(websiteURL));
        c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
    }

    void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        lock (this)
        {
            string s = e.Result;
            XmlReader r = XmlReader.Create(new MemoryStream(System.Text.UnicodeEncoding.Unicode.GetBytes(s)));
            // So something with the XML we get back
            XDocument data = XDocument.Load(r);
            var ns = data.Root.GetDefaultNamespace();
            var flights = from query in data.Descendants(ns+"Flight")
                              select new Flight
                              {
                                  AircraftType = (int)query.Element(ns + "AircraftType"),
                                  ArrivalTerminal = (int)query.Element(ns + "ArrivalTerminal"),
                                  Carrier = (string)query.Element(ns + "Carrier"),
                                  DepartureTerminal = (int)query.Element(ns + "DepartureTerminal"),
                                  Duration = (string)query.Element(ns + "Duration"),
                                  EndDateTime = (string)query.Element(ns + "EndDateTime"),
                                  EndPoint = (string)query.Element(ns + "EndPoint"),
                                  FlightIndexNo = (int)query.Element(ns + "FlightIndexNo"),
                                  FlightNo = (int)query.Element(ns + "FlightNo"),
                                  NumStops = (int)query.Element(ns + "NumStops"),
                                  OperatedBy = (string)query.Element(ns + "OperatedBy"),
                                  StartDateTime = (string)query.Element(ns + "StartDateTime"),
                                  StartPoint = (string)query.Element(ns + "StartPoint")
                              };
            //checking if anything is there.
            string result ="";

            foreach (Flight i in flights)
            {
                result += i.Carrier;
            }
            resultsBlock.Text = result;

        }
    }

    public class Flight
    {
        public int aircraftType;
        public int arrivalTerminal;
        public string carrier;
        public int departureTerminal;
        public string duration;
        public string endDateTime;
        public string endPoint;
        public int flightIndexNo;
        public int flightNo;
        public int numStops;
        public string operatedBy;
        public string startDateTime;
        public string startPoint;

        //Getter and setters

and the section of XML I want looks like this. This is also the first use of the Flight tag in the XML. Added the start of the XML whole thing is hundreds of lines long so won't but it all up. The Flight Tag I want is burred down in there.

<FindFlightsResponse xmlns="urn:webjet.com.au" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<DisplayMessage i:nil="true" />
<OutboundFlightInfo>
          ...
              <Flight>
                    <AircraftType>734</AircraftType>
                    <ArrivalTerminal>3</ArrivalTerminal>
                    <Carrier>QF</Carrier>
                    <DepartureTerminal>1</DepartureTerminal>
                    <Duration>PT1H25M</Duration>
                    <EndDateTime>2011-04-20T07:25:00</EndDateTime>
                    <EndPoint>SYD</EndPoint>
                    <FlightIndexNo>1</FlightIndexNo>
                    <FlightNo>400</FlightNo>
                    <NumStops>0</NumStops>
                    <OperatedBy>QF</OperatedBy>
                    <StartDateTime>2011-04-20T06:00:00</StartDateTime>
                    <StartPoint>MEL</StartPoint>
                </Flight>

I've probably made some simple mistake.
All help appreciated.
Thanks.
edit im now getting a method passing error. I changed the datetime to string for simplicity

Body:
My guess is you're not showing us the complete XML and it likely has a default namespace specified. A namespace will look like xmlns="http://www.domain.com". If this is indeed the case then your LINQ to XML queries need to reference that namespace, and this can be done as follows:

var ns = data.Root.GetDefaultNamespace();
var flights = from query in data.Descendants(ns + "Flight")
              select new Flight
              {
                  AircraftType = (int)query.Element(ns + "AircraftType"),
                  ArrivalTerminal = (int)query.Element(ns + "ArrivalTerminal"),
                  Carrier = (string)query.Element(ns + "Carrier"),
                  DepartureTerminal = (int)query.Element(ns + "DepartureTerminal"),
                  Duration = (string)query.Element(ns + "Duration"),
                  EndDateTime = (DateTime)query.Element(ns + "EndDateTime"),
                  EndPoint = (string)query.Element(ns + "EndPoint"),
                  FlightIndexNo = (int)query.Element(ns + "FlightIndexNo"),
                  FlightNo = (int)query.Element(ns + "FlightNo"),
                  NumStops = (int)query.Element(ns + "NumStops"),
                  OperatedBy = (string)query.Element(ns + "OperatedBy"),
                  StartDateTime = (DateTime)query.Element(ns + "StartDateTime"),
                  StartPoint = (string)query.Element(ns + "StartPoint")
              };

Notice that you need to prefix each element name with the namespace, hence the use of ns + throughout the code.


来源: stackexchange

问:
Conversion to Swift 5 produces 'Multiple commands produce x86_64.swiftmodule' error
I am trying to get Xcode 10.2 to convert my hybrid Objective-C / Swift project to use Swift 5. Whenever I do this, however, the compilation files due to the following error

```<code>error: Multiple commands produce '/Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPP.swiftmodule/x86_64.swiftmodule':
1) Target 'MYAPPTests' (project 'SurgEval'): Ditto /Users/alenox/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPP.swiftmodule/x86_64.swiftmodule /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Intermediates.noindex/SurgEval.build/Debug-iphonesimulator/MYAPPTests.build/Objects-normal/x86_64/MYAPP.swiftmodule
2) Target 'SurgEval' (project 'SurgEval'): Ditto /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPPL.swiftmodule/x86_64.swiftmodule /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Intermediates.noindex/SurgEval.build/Debug-iphonesimulator/SurgEval.build/Objects-normal/x86_64/MYAPP.swiftmodule
</code>```

I have already tried switching to using the 'Legacy Build System' as suggested in other similar questions, but I would like to migrate to the new build system.

I have also tried to change the product module name in my test target as suggested in another question, but that broke my tests.

The application and tests both build and run fine otherwise, I just get a compilation error while running the Swift 5 migration tool.

Any idea what's going on here, or some some docs I can look at to better understand this?

Thanks!

答:
I was able to partly solve this issue by adjusting SWIFT_MODULE_NAME property in Test target.

My test's target SWIFT_MODULE_NAME was same as main target name, so i changed it

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get Xcode 10.2 to convert my hybrid Objective-C / Swift project to use Swift 5. Whenever I do this, however, the compilation files due to the following error

error: Multiple commands produce '/Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPP.swiftmodule/x86_64.swiftmodule':
1) Target 'MYAPPTests' (project 'SurgEval'): Ditto /Users/alenox/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPP.swiftmodule/x86_64.swiftmodule /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Intermediates.noindex/SurgEval.build/Debug-iphonesimulator/MYAPPTests.build/Objects-normal/x86_64/MYAPP.swiftmodule
2) Target 'SurgEval' (project 'SurgEval'): Ditto /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Products/Debug-iphonesimulator/MYAPPL.swiftmodule/x86_64.swiftmodule /Users/<User>/Library/Developer/Xcode/DerivedData/SurgEval-chcbdqcuvbtwckedraqzdhwbsqpm/Build/Intermediates.noindex/SwiftMigration/SurgEval/Intermediates.noindex/SurgEval.build/Debug-iphonesimulator/SurgEval.build/Objects-normal/x86_64/MYAPP.swiftmodule

I have already tried switching to using the 'Legacy Build System' as suggested in other similar questions, but I would like to migrate to the new build system.

I have also tried to change the product module name in my test target as suggested in another question, but that broke my tests.

The application and tests both build and run fine otherwise, I just get a compilation error while running the Swift 5 migration tool.

Any idea what's going on here, or some some docs I can look at to better understand this?

Thanks!


问:
How to create and use an "out" parameter with a SQL Server database
I am working on a C# desktop application. I want to use a stored procedure (insert query) to add a new record to a data table. I need to return the primary key which is an identity insert (bigint) to avoid another round trip to the database. I have searched the MS Help(less) files for a couple of hours and found nothing on how to set the out parameter of the stored procedure or how to obtain the return value.

答:
Using an OUTPUT clause on the INSERT is great, and essential if you needed to capture the identity values in a multi-row batch. For a SQL beginner however the code is a little more complex, and in relation to this particular question it could be confused with the OUTPUT parameter of the stored proc, which is a completely unrelated concept.

For a single row insert however, the SCOPE_IDENTITY function works great and is simpler to use.

Here's a version of Larnu's stored proc using SCOPE_IDENTITY instead:

```<code>CREATE PROC dbo.InsertYourTable @SomeColumn varchar(20), @ID bigint OUTPUT AS
BEGIN

INSERT INTO dbo.YourTable(SomeColumn)
VALUES(@SomeColumn);

SET @ID = SCOPE_IDENTITY();
END;
</code>```

Body:
Using an OUTPUT clause on the INSERT is great, and essential if you needed to capture the identity values in a multi-row batch. For a SQL beginner however the code is a little more complex, and in relation to this particular question it could be confused with the OUTPUT parameter of the stored proc, which is a completely unrelated concept.

For a single row insert however, the SCOPE_IDENTITY function works great and is simpler to use.

Here's a version of Larnu's stored proc using SCOPE_IDENTITY instead:

CREATE PROC dbo.InsertYourTable @SomeColumn varchar(20), @ID bigint OUTPUT AS
BEGIN

INSERT INTO dbo.YourTable(SomeColumn)
VALUES(@SomeColumn);

SET @ID = SCOPE_IDENTITY();
END;


问:
ssh cannot use the IdentityFile config in file ~/.ssh/config
client：Mac 10.8，server：Ubuntu 10.04 LTS 64bit

I use 'ssh-keygen -t rsa' generate public/private keys.

First, I input: ssh -i /Users/phenix/.ssh/poponet_rsa root@popo.net, I can login to the server with the private key 'poponet_rsa'

Next, I create a config file: /Users/phenix/.ssh/config, with content:

```<code>Host popo
    Hostname popo.net
    User root
    PreferredAuthentications publickey
    IdentityFile /Users/phenix/.ssh/poponet_rsa
</code>```

and I input ssh root@popo.net, the Terminal ask me the password.

Next, I change poponet_rsa filename to id_rsa, and input ssh root@popo.net, OK, I login.

My question: ssh cannot use the IdentityFile config in file ~/.ssh/config, why?

```<code>$ ssh -vvv root@popo.net
OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /Users/phenix/.ssh/config
debug1: /Users/phenix/.ssh/config line 1: Applying options for popo.net
debug1: /Users/phenix/.ssh/config line 2: Applying options for popo.net
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to popo.net [111.111.111.111] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/Users/phenix/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /Users/phenix/.ssh/id_rsa type -1
debug1: identity file /Users/phenix/.ssh/id_rsa-cert type -1
debug1: identity file /Users/phenix/.ssh/id_dsa type -1
debug1: identity file /Users/phenix/.ssh/id_dsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3p1 Debian-3ubuntu7
debug1: match: OpenSSH_5.3p1 Debian-3ubuntu7 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "popo.net" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: **too much init, i delete them.**
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 135/256
debug2: bits set: 468/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
debug3: load_hostkeys: loading entries for host "popo.net" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: load_hostkeys: loading entries for host "111.111.111.111" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug1: Host 'popo.net' is known and matches the RSA host key.
debug1: Found key in /Users/phenix/.ssh/known_hosts:1
debug2: bits set: 516/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /Users/phenix/.ssh/id_rsa (0x0)
debug2: key: /Users/phenix/.ssh/id_dsa (0x0)
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /Users/phenix/.ssh/id_rsa
debug1: key_parse_private_pem: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug2: no passphrase given, try next key
debug1: Trying private key: /Users/phenix/.ssh/id_dsa
debug3: no such identity: /Users/phenix/.ssh/id_dsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
root@popo.net's password:
</code>```

答:
I think the answer lies in the mechanism of .ssh/config file.

If you try ssh root@popo, it should work.

The command ssh name@host first match the host in the Host field in .ssh/config, not the HostName sub-field.

It puzzles me for several weeks......

ContentLicense: CC BY-SA 3.0

Body:
client：Mac 10.8，server：Ubuntu 10.04 LTS 64bit

I use 'ssh-keygen -t rsa' generate public/private keys.

First, I input: ssh -i /Users/phenix/.ssh/poponet_rsa root@popo.net, I can login to the server with the private key 'poponet_rsa'

Next, I create a config file: /Users/phenix/.ssh/config, with content:

Host popo
    Hostname popo.net
    User root
    PreferredAuthentications publickey
    IdentityFile /Users/phenix/.ssh/poponet_rsa

and I input ssh root@popo.net, the Terminal ask me the password.

Next, I change poponet_rsa filename to id_rsa, and input ssh root@popo.net, OK, I login.

My question: ssh cannot use the IdentityFile config in file ~/.ssh/config, why?

$ ssh -vvv root@popo.net
OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /Users/phenix/.ssh/config
debug1: /Users/phenix/.ssh/config line 1: Applying options for popo.net
debug1: /Users/phenix/.ssh/config line 2: Applying options for popo.net
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to popo.net [111.111.111.111] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/Users/phenix/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /Users/phenix/.ssh/id_rsa type -1
debug1: identity file /Users/phenix/.ssh/id_rsa-cert type -1
debug1: identity file /Users/phenix/.ssh/id_dsa type -1
debug1: identity file /Users/phenix/.ssh/id_dsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3p1 Debian-3ubuntu7
debug1: match: OpenSSH_5.3p1 Debian-3ubuntu7 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "popo.net" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: **too much init, i delete them.**
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 135/256
debug2: bits set: 468/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
debug3: load_hostkeys: loading entries for host "popo.net" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug3: load_hostkeys: loading entries for host "111.111.111.111" from file "/Users/phenix/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/phenix/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys
debug1: Host 'popo.net' is known and matches the RSA host key.
debug1: Found key in /Users/phenix/.ssh/known_hosts:1
debug2: bits set: 516/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /Users/phenix/.ssh/id_rsa (0x0)
debug2: key: /Users/phenix/.ssh/id_dsa (0x0)
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /Users/phenix/.ssh/id_rsa
debug1: key_parse_private_pem: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug2: no passphrase given, try next key
debug1: Trying private key: /Users/phenix/.ssh/id_dsa
debug3: no such identity: /Users/phenix/.ssh/id_dsa
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
root@popo.net's password:


问:
Pass user selected value, from dropdown menu, to d3.csv
Somewhat similar to this previous question enter link description here, but for d3.

Basically, I have a dropdown menu that the user can select the year they would like to view. When the user selects the year, I would like to pass that data to the d3.csv command to select the relevant csv file.

The html code is as follows:

<form>
        Select year to see each team's scoring:
        <select id="year">
            <option value="Rugby - 2014">2014 - 2015</option>
            <option value="Rugby - 2015">2015 - 2016</option>
            <option value="Rugby - 2016">2016 - 2017</option>
            <option value="Rugby - 2017">2017 - 2018</option>
            <option value="Rugby - 2018">2018 - 2019</option>
            <option value="Rugby - Total">2014 - 2019</option>
        </select>
    <form>
```

<p>I've tried a few iterations, and this is the one I am on now:</p>

```
```

Edit: The error I'm getting is TypeError: d3.csv(...).then is not a function

Any suggestions on how to get the selected value from the dropdown into the d3.csv script?

答:
```<code>d3.csv(document.getElementById('year').value & ".csv", function(error,data) {
 ...
});
</code>```

https://github.com/d3/d3-fetch/blob/v1.1.2/README.md#csv

Body:
Somewhat similar to this previous question enter link description here, but for d3.

Basically, I have a dropdown menu that the user can select the year they would like to view. When the user selects the year, I would like to pass that data to the d3.csv command to select the relevant csv file.

The html code is as follows:

<form>
        Select year to see each team's scoring:
        <select id="year">
            <option value="Rugby - 2014">2014 - 2015</option>
            <option value="Rugby - 2015">2015 - 2016</option>
            <option value="Rugby - 2016">2016 - 2017</option>
            <option value="Rugby - 2017">2017 - 2018</option>
            <option value="Rugby - 2018">2018 - 2019</option>
            <option value="Rugby - Total">2014 - 2019</option>
        </select>
    <form>

I've tried a few iterations, and this is the one I am on now:

Edit: The error I'm getting is TypeError: d3.csv(...).then is not a function

Any suggestions on how to get the selected value from the dropdown into the d3.csv script?

Body:
d3.csv(document.getElementById('year').value & ".csv", function(error,data) {
 ...
});

https://github.com/d3/d3-fetch/blob/v1.1.2/README.md#csv


问:
BindRequired on DateTime
I have an issue with [BindRequired] attribute, it does not invalidate my model state:

```<code>public class PostModel
{
    [BindRequired]
    public DateTime Date { get; set; }
}
</code>```

Controller:

```<code>[ApiController]
public class BindTestController : ControllerBase
{
    [HttpPost("test")]
    public IActionResult SetValue([FromBody] PostModel request)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        return Ok();
    }
}
</code>```

if I post a body like this:

```<code>{}
</code>```

My modelstate is valid.
What is the good way of validating that Date is present on my body, and invalidate the model ?

Thanks

答: You could use RequiredAttribute instead of BindRequiredAttribute. In ASP.NET Core, the latter is only applicable for “non body” parameters

Title: BindRequired on DateTime

Body:
I have an issue with [BindRequired] attribute, it does not invalidate my model state:

public class PostModel
{
    [BindRequired]
    public DateTime Date { get; set; }
}

Controller:

[ApiController]
public class BindTestController : ControllerBase
{
    [HttpPost("test")]
    public IActionResult SetValue([FromBody] PostModel request)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        return Ok();
    }
}

if I post a body like this:

{}

My modelstate is valid.
What is the good way of validating that Date is present on my body, and invalidate the model ?

Thanks


问:
How to save multiple EditText data with button, and display it on another Activity with floating action button?
I have one Edittext in my App, I want to save the Text i wrote in this Edittext by clicking a button and than display it in another activity, but only by clicking a floating action button. And after i click the save button, the Edittext should be blank so i could write something else and again save the new text.

I tried with putextra but i can only pass one Edittext and only display it with one button. By clicking the Floating Button it displays blank Activity, I assume because it is a new Intent so he doesn't passes anything.

答:
If you're reading/writing multiple values from the EditText, you could use SharedPreferences to save these values in your Activity where the EditText is, then read all the values from SharedPreferences in your 2nd Activity. This will let you avoid creating a database for your app as that's a bit of overhead.

Since it's only String data that will be coming from the EditText, I would probably go with a Set - but this won't allow duplicates. You could just store each String under a different key and use the getAll() method instead. Something like below in your onClickListener for your FAB would save the data:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("UNIQUE_KEY_HERE", "EDIT_TEXT_VALUE_HERE");
editor.commit();
</code>```

And then when reading from SharedPreferences in your 2nd Activity:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String editTextValue = sharedPref.getString("UNIQUE_KEY_HERE", " "); // " " is a default value
</code>```

There's already plenty of documentation on SharedPreferences anyway, including the getAll() method

Body:
If you're reading/writing multiple values from the EditText, you could use SharedPreferences to save these values in your Activity where the EditText is, then read all the values from SharedPreferences in your 2nd Activity. This will let you avoid creating a database for your app as that's a bit of overhead.

Since it's only String data that will be coming from the EditText, I would probably go with a Set - but this won't allow duplicates. You could just store each String under a different key and use the getAll() method instead. Something like below in your onClickListener for your FAB would save the data:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("UNIQUE_KEY_HERE", "EDIT_TEXT_VALUE_HERE");
editor.commit();

And then when reading from SharedPreferences in your 2nd Activity:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String editTextValue = sharedPref.getString("UNIQUE_KEY_HERE", " "); // " " is a default value

There's already plenty of documentation on SharedPreferences anyway, including the getAll() method


问:
How to create mock/ dummy Initial context for Junit tests out of container
I am facing big problem instantiating weblogic Initial context while running jUnit tests.
Application uses Spring / hibernate / weblogic.
In application code,  methods  uses JMS proxy to send messages to JMS, Queues are setup on weblogic.

My problem is while JUnit tests currently I need to keep weblogic server running  on local machine just to initialize WeblogicInitialContext  which is  used in JMS proxies. My junit test don't need to send anything to server, NO JMS , NO datasources. All are handeled by spring unit test framework.
I want to decouple/ get rid of Weblogic for my junit tests.  Please suggest.
Here is my code:

This is my test application context XML:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
...
>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<util:properties id="webLogicInitialContext">
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
    <prop key="java.naming.provider.url">t3://localhost:7001</prop>
    <prop key="java.naming.security.principal">admin</prop>
    <prop key="java.naming.security.credentials">password</prop>
</util:properties>

<jee:jndi-lookup id="responseProxyConnectionFactory"
    jndi-name="jms/ConnectionFactory" environment-ref="webLogicInitialContext"/>

<bean id="responseProxyJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory"
        ref="responseProxyConnectionFactory" />
</bean>
</beans>
</code>```

This is One  Java class methods :

```<code>public class Order {
    public void addOrder(OrderRequest addOrderRequest) {
        PurchaseOrder newOrder = orderHelper.createOrder(addOrderRequest);
        orderDaoHibernate.addOrder(newOrder);
        responseProxy.send(newOrder);

    }
}
</code>```

My Test :

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class })
@ContextConfiguration(locations={"/test-application-context.xml"})
@TransactionConfiguration(defaultRollback=true)

public class TestOrder {

    @Test
    @Transactional
    public void testMyOrder(){
        Order ord = new Order();
        OrderRequest req = new OrderRequest();
        ....
        ord.addOrder(req);
    }

}
</code>```

If I run this test the Spring framework try to load the WeblogicInitialContext , and if local weblogic not running it throws exceptions.

I don't want to send any JMS message when I call this method from Junit.
How can I create dummy WeblogicInitialContext.

Please help.

Some part of Exception;

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean     with name 'responseProxyConnectionFactory': Invocation of init method failed; nested exception is javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:7001: Destination unreachable; nested exception is:
</code>```

答:
One way to deal with this problem is this:

Split your application configuration in two parts,

a core part - where your normal classes are defined, injected, scanned, ...

a server dependent part (containing all the stuff which can not been created in the test)

Add a spring config, that import them both, and use this when you start your application.

So for test you can use the core-part-configuration. If this configuration can not be instanciated, because some beans (form the server dependent part) are missing you need to mock them. Here you have two choices:

create a test mock configuration, that simulated the server dependent part by mocks.

you could try to add the mocks programaticaly to the application context, before you load the core part. (much more compicated)

Anyway: I strongly recommend to rethink the way you build tests. May a better way is to build some (not all) tests completely without spring and create the class under test by hand (new) and "inject" the objects needed for the test by hand. The objects not needed for the test (at all, or because the make the test only more difficult but not better) should be replaced by Mocks.

To create mocked, I prefere the mocking framwork jMock. I have implemented a Helper Class with a Factory method, which create a class, and create and inject Mocks for all fields annoted by @Autorwird/@Ressourse.

Body:
I am facing big problem instantiating weblogic Initial context while running jUnit tests.
Application uses Spring / hibernate / weblogic.
In application code,  methods  uses JMS proxy to send messages to JMS, Queues are setup on weblogic.

My problem is while JUnit tests currently I need to keep weblogic server running  on local machine just to initialize WeblogicInitialContext  which is  used in JMS proxies. My junit test don't need to send anything to server, NO JMS , NO datasources. All are handeled by spring unit test framework.
I want to decouple/ get rid of Weblogic for my junit tests.  Please suggest.
Here is my code:

This is my test application context XML:

<beans xmlns="http://www.springframework.org/schema/beans"
...
>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<util:properties id="webLogicInitialContext">
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
    <prop key="java.naming.provider.url">t3://localhost:7001</prop>
    <prop key="java.naming.security.principal">admin</prop>
    <prop key="java.naming.security.credentials">password</prop>
</util:properties>

<jee:jndi-lookup id="responseProxyConnectionFactory"
    jndi-name="jms/ConnectionFactory" environment-ref="webLogicInitialContext"/>

<bean id="responseProxyJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory"
        ref="responseProxyConnectionFactory" />
</bean>
</beans>

This is One  Java class methods :

public class Order {
    public void addOrder(OrderRequest addOrderRequest) {
        PurchaseOrder newOrder = orderHelper.createOrder(addOrderRequest);
        orderDaoHibernate.addOrder(newOrder);
        responseProxy.send(newOrder);

    }
}

My Test :

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class })
@ContextConfiguration(locations={"/test-application-context.xml"})
@TransactionConfiguration(defaultRollback=true)

public class TestOrder {

    @Test
    @Transactional
    public void testMyOrder(){
        Order ord = new Order();
        OrderRequest req = new OrderRequest();
        ....
        ord.addOrder(req);
    }

}

If I run this test the Spring framework try to load the WeblogicInitialContext , and if local weblogic not running it throws exceptions.

I don't want to send any JMS message when I call this method from Junit.
How can I create dummy WeblogicInitialContext.

Please help.

Some part of Exception;

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean     with name 'responseProxyConnectionFactory': Invocation of init method failed; nested exception is javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:7001: Destination unreachable; nested exception is:


问:
Get JSON to HTML JavaScript table
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

```<code>{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}
</code>```

Table like this:

```<code>| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....
</code>```

答:
First, you need to create a
 in HTML, Apply some styles to it (see example below, you can run it)

Then run a loop on you data set and add rows to you table.

Use string literals to replace data from you variable to rowHTML, or you can use any templating library to create a html template for cleaner code.

var myData = {
 query: {
  count: 10,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 test1: {
  count: 16,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 bold: {
  count: 1,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 home: {
  count: 1,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 }
};

var myDataKeys = Object.keys(myData);

var myTable = document.getElementById("myTable");

for(var i=0; i<myDataKeys.length; i++) {
 const rowData = myData[myDataKeys[i]];
 const rowHTML = `<tr><td>${myDataKeys[i]}</td><td>${rowData.count}</td><td>${rowData.created}</td><td>${rowData.lang}</td>`;
 myTable.innerHTML += rowHTML;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, th, td {
  border: 1px solid black;
}</code>```

Name	Count	Time	Language

```

Title: Get JSON to HTML JavaScript table

Body:
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}

Table like this:

| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....

Body:
First, you need to create a <table> in HTML, Apply some styles to it (see example below, you can run it)

Then run a loop on you data set and add rows to you table.

Use string literals to replace data from you variable to rowHTML, or you can use any templating library to create a html template for cleaner code.

var myData = {
 query: {
  count: 10,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 test1: {
  count: 16,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 bold: {
  count: 1,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 },
 home: {
  count: 1,
  created: "2015-12-09T17:12:09Z",
  lang: "en-US",
  diagnostics: {},
 }
};

var myDataKeys = Object.keys(myData);

var myTable = document.getElementById("myTable");

for(var i=0; i<myDataKeys.length; i++) {
 const rowData = myData[myDataKeys[i]];
 const rowHTML = `<tr><td>${myDataKeys[i]}</td><td>${rowData.count}</td><td>${rowData.created}</td><td>${rowData.lang}</td>`;
 myTable.innerHTML += rowHTML;
}

table, th, td {
  border: 1px solid black;
}

<table id="myTable">
 <tr><td>Name</td><td>Count</td><td>Time</td><td>Language</td></tr>
</table>


问:
AWS Lambda get data from external public API (basic)
I am trying to write a simple AWS Lambda function to retrieve data from an external public API. I have copied and pasted code from all over the internet without any luck.

I have stripped down the code to be a simple as possible to keep it simple. The public API is : https://swapi.co/api/people/1/

How can I get the data back from the public API?

```<code>const https = require('https');

exports.handler = async (event) => {

    var options = {
      method: 'GET',
      host: 'https://swapi.co/api/people/1/',

    };

     console.log('options', options);

     const req = https.request(options, (res) => {
         console.log('statusCode: ${res.statusCode}')
         console.log(JSON.stringify(res))
     });

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};
</code>```

The log file within the AWS editor shows:

```<code>START RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728 Version: $LATEST
2019-05-27T16:17:44.839Z    3ba3f23a-11c2-40af-b9e7-0258a6531728    INFO    options { method: 'GET', host: 'https://swapi.co/api/people/1/' }
END RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728
REPORT RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728  Duration: 305.90 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 26 MB
</code>```

答:
The below code is working</p>

```<code>const http = require("https");

exports.handler = async(event, context, callback) => {

  var options = {
    "method": "GET",
    "hostname": "app.casejacket.com",
    "port": null,
    "path": "/api/",
    "headers": {
      "cache-control": "no-cache",
      "Content-Type": "application/json"
    }
  };

  await new Promise((resolve, reject) => {
    console.log('Promise.. ');

    var req = http.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
        var body = Buffer.concat(chunks);
        let result = JSON.parse(body.toString());
        console.log(body.toString());
        resolve(body.toString());
        callback(null, result)
      });
    });

    req.end();
  });

  callback();

};
</code>```

Body:
I am trying to write a simple AWS Lambda function to retrieve data from an external public API. I have copied and pasted code from all over the internet without any luck.

I have stripped down the code to be a simple as possible to keep it simple. The public API is : https://swapi.co/api/people/1/

How can I get the data back from the public API?

const https = require('https');

exports.handler = async (event) => {

    var options = {
      method: 'GET',
      host: 'https://swapi.co/api/people/1/',

    };

     console.log('options', options);

     const req = https.request(options, (res) => {
         console.log('statusCode: ${res.statusCode}')
         console.log(JSON.stringify(res))
     });

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

The log file within the AWS editor shows:

START RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728 Version: $LATEST
2019-05-27T16:17:44.839Z    3ba3f23a-11c2-40af-b9e7-0258a6531728    INFO    options { method: 'GET', host: 'https://swapi.co/api/people/1/' }
END RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728
REPORT RequestId: 3ba3f23a-11c2-40af-b9e7-0258a6531728  Duration: 305.90 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 26 MB

Body:
The below code is working

const http = require("https");

exports.handler = async(event, context, callback) => {

  var options = {
    "method": "GET",
    "hostname": "app.casejacket.com",
    "port": null,
    "path": "/api/",
    "headers": {
      "cache-control": "no-cache",
      "Content-Type": "application/json"
    }
  };

  await new Promise((resolve, reject) => {
    console.log('Promise.. ');

    var req = http.request(options, function (res) {
      var chunks = [];

      res.on("data", function (chunk) {
        chunks.push(chunk);
      });

      res.on("end", function () {
        var body = Buffer.concat(chunks);
        let result = JSON.parse(body.toString());
        console.log(body.toString());
        resolve(body.toString());
        callback(null, result)
      });
    });

    req.end();
  });

  callback();

};


问:
laravel file_put_contents(): Exclusive locks are not supported for this stream
I tried to upload my site to laravel to host and be configured but I couldn't load the project. The error is as follows:

file_put_contents(): Exclusive locks are not supported for this stream

How do I fix this?

答:
You have to close the server by closing your batch window you used in starting the server initially.

Refresh your browser and make sure the the server has been closed.

Start a new development server by typing $ php artisan serve

Go to your browser and enter the server address generated by the artisan. It's usually http://127.0.0.1:8000


问:
How to compare two dates in different zones in ruby
How to compare these two dates in different time zones in ruby

Code:

```<code>if (mydate.to_datetime -
        (120).minutes).to_datetime >
            DateTime.now

puts mydate # 2019-05-30 20:42:34
mydate.to_time # 2019-05-30T20:42:34+00:00
# after subtracting 120 minutes 2019-05-30T18:42:34+00:00
puts DateTime.now # 2019-05-30T20:24:12+05:30
</code>```

I need to subtract 120 minutes from mydate and compare with currentdate.

Body:
How to compare these two dates in different time zones in ruby

Code:

if (mydate.to_datetime -
        (120).minutes).to_datetime >
            DateTime.now

puts mydate # 2019-05-30 20:42:34
mydate.to_time # 2019-05-30T20:42:34+00:00
# after subtracting 120 minutes 2019-05-30T18:42:34+00:00
puts DateTime.now # 2019-05-30T20:24:12+05:30

I need to subtract 120 minutes from mydate and compare with currentdate.

Body:
Time.parse can handle Time Zones with no issue:

2.5.1 :001 > require 'time'
 => true
2.5.1 :002 > t1 = Time.parse('2019-05-30T19:37:18+00:00')
 => 2019-05-30 19:37:18 +0000
2.5.1 :003 > t2 = Time.parse('2019-05-30T19:37:30+05:30')
 => 2019-05-30 19:37:30 +0530
2.5.1 :004 > t1 > t2
 => true
2.5.1 :005 > t2 > t1
 => false
2.5.1 :006 > t1 == t2
 => false
2.5.1 :007 > t1 - t2
 => 19788.0 # result is in seconds, convert to whatever you need

Assuming you already have declared these two variables as DateTime instances where t1 is 2019-05-30T19:37:18+00:00 and t2 is 2019-05-30T19:37:30+05:30, you can run comparisons directly and get the results in seconds using .to_time

2.5.1 :009 > t1 > t2
 => true
2.5.1 :010 > t2 > t1
 => false
2.5.1 :011 > t1 == t2
 => false
2.5.1 :012 > t1.to_time - t2.to_time
 => 19788.0


问:
Calling a base abstract method in an override of that method
If I have the following:

e.g.

```<code>public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}
</code>```

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

```<code>public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}
</code>```

Ok then we still have:

```<code>public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }
</code>```

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.

答:
Well, it calls ClassC's override method... which happens to call ClassB's implementation. It's not "including" the logic of ClassB's implementation directly within the compiled code of ClassC, or anything like that - it's just another method call.

It's not entirely clear what's confusing you - the behaviour, the design intention, or what Find Usages is showing you.

Note that despite your subject line, you're not calling a "base abstract method" - you're calling the implementation of that method. The compiler knows that ClassC derives from ClassB, which is providing an implementation of the method, so it's making that call explicitly. You couldn't do the same thing from ClassB itself, because then base.ValidateTransaction really would be trying to call an abstract base method.

Fun fact: despite this calling a virtual method, it's a non-virtual method call: the compiler knows the exact implementation to use, and bakes that into the call. If it was a virtual call, you'd end up back in the ClassC implementation as that overrides it :)

Body:
If I have the following:

e.g.

public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}

Ok then we still have:

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.


问:
Delete row from dataframe having "None" value in all the columns - Python
I need to delete the row completely in a dataframe having "None" value in all the columns. I am using the following code -

```<code>df.dropna(axis=0,how='all',thresh=None,subset=None,inplace=True)
</code>```

This does not bring any difference to the dataframe. The rows with "None" value are still there.

How to achieve this?

答:
You should be dropping in the axis 1. Use the how keyword to drop columns with any or all NaN values. Check the docs

import pandas as pd
import numpy as np

df = pd.DataFrame({'a':[1,2,3], 'b':[-1, 0, np.nan], 'c':[np.nan, np.nan, np.nan]})
df
   a    b    c
0  1 -1.0  NaN
1  2  0.0  NaN
2  3  NaN  5.0

df.dropna(axis=1, how='any')
   a
0  1
1  2
2  3

df.dropna(axis=1, how='all')
   a    b
0  1 -1.0
1  2  0.0
2  3  NaN
```

Body:
I need to delete the row completely in a dataframe having "None" value in all the columns. I am using the following code -

df.dropna(axis=0,how='all',thresh=None,subset=None,inplace=True)

This does not bring any difference to the dataframe. The rows with "None" value are still there.

How to achieve this?


问:
Programatically mount network location securely in Linux with Go
In Linux I can mount a network location programatically with Go like this:

```<code>func main() {
  var user, pass string
  fmt.Println("username:")
  fmt.Scanln(&user) // ignore errors for brevity
  fmt.Println("password:")
  fmt.Scanln(&pass)

  cmd := exec.Command("mount", "-t", "cifs", "-o", "username="+user+",password="+pass, "//server/dir", "media/dir")
  cmd.Run()
}
</code>```

The problems:

I can't run this without elevating privileges with sudo

Username and password will be provided by the user. This seems very unsafe. Can anyone confirm on the safety or danger of this approach?

Here's a similar approach with variables:

```<code>cmd := exec.Command("mount", "-t", "cifs", "-o", "username=$USER,password=$PASS", "//server/dir", "media/dir")
cmd.Env = []string{"USER="+user, "PASS="+pass}
cmd.Run()
</code>```

That does not work. It seems that exec.Command() function escapes the dollar sign, so the values in the env variables aren't replaced there. So this seems to indicate some type of safety or escaping going on here.

Editing the etc/fstab file would allow me to run mount without sudo but then I'd need sudo to edit the fstab file, so back to square one.

答:
We can use gvfs to mount shares in userspace, which means we don't need to elevate privileges with sudo. The gio command can be used for this.

The code snippet below excludes error handling for brevity:

cmd := exec.Command("gio", "mount", "smb://server/share")
inPipe, _ := cmd.StdinPipe()
cmd.Start()

// Get credentials whichever way you find best, including scanning the Stdin.
// Concatenate them together with line breaks in between and a line break at the end.
auth := "Username\nDomain\nPassword\n"
inPipe.Write([]byte(auth))

// Wait for the command to finish.
cmd.Wait()
```

Scanning the Stdin seems to be an acceptable way to capture credentials, since that's how the gio command works.

Body:
In Linux I can mount a network location programatically with Go like this:

func main() {
  var user, pass string
  fmt.Println("username:")
  fmt.Scanln(&user) // ignore errors for brevity
  fmt.Println("password:")
  fmt.Scanln(&pass)

  cmd := exec.Command("mount", "-t", "cifs", "-o", "username="+user+",password="+pass, "//server/dir", "media/dir")
  cmd.Run()
}

The problems:

I can't run this without elevating privileges with sudo

Username and password will be provided by the user. This seems very unsafe. Can anyone confirm on the safety or danger of this approach?

Here's a similar approach with variables:

cmd := exec.Command("mount", "-t", "cifs", "-o", "username=$USER,password=$PASS", "//server/dir", "media/dir")
cmd.Env = []string{"USER="+user, "PASS="+pass}
cmd.Run()

That does not work. It seems that exec.Command() function escapes the dollar sign, so the values in the env variables aren't replaced there. So this seems to indicate some type of safety or escaping going on here.

Editing the etc/fstab file would allow me to run mount without sudo but then I'd need sudo to edit the fstab file, so back to square one.

Body:
We can use gvfs to mount shares in userspace, which means we don't need to elevate privileges with sudo. The gio command can be used for this.

The code snippet below excludes error handling for brevity:

cmd := exec.Command("gio", "mount", "smb://server/share")
inPipe, _ := cmd.StdinPipe()
cmd.Start()

// Get credentials whichever way you find best, including scanning the Stdin.
// Concatenate them together with line breaks in between and a line break at the end.
auth := "Username\nDomain\nPassword\n"
inPipe.Write([]byte(auth))

// Wait for the command to finish.
cmd.Wait()

Scanning the Stdin seems to be an acceptable way to capture credentials, since that's how the gio command works.


问:
Incorrect syntax near the keyword 'DECLARE' in view
Can someone please confirm how to get rid of the following error.</p>

```<code>DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)
SELECT
dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount AS Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

FROM
dbo.General_Ledger_Detail
INNER JOIN dbo.Account_Codes_Sales_OPEX$
ON dbo.General_Ledger_Detail.Accounting_ID =
    dbo.Account_Codes_Sales_OPEX$.[Account Code]
INNER JOIN dbo.LogSolOpexCC
ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre

GROUP BY dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN @startdate AND @enddate)
</code>```

答: You cannot pass parameters to SQL Server views. https://www.mssqltips.com/sqlservertip/5147/limitations-when-working-with-sql-server-views/</p>

Body:
Can someone please confirm how to get rid of the following error.

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)
SELECT
dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount AS Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

FROM
dbo.General_Ledger_Detail
INNER JOIN dbo.Account_Codes_Sales_OPEX$
ON dbo.General_Ledger_Detail.Accounting_ID =
    dbo.Account_Codes_Sales_OPEX$.[Account Code]
INNER JOIN dbo.LogSolOpexCC
ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre

GROUP BY dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN @startdate AND @enddate)


Title: How to compare two dates in different zones in ruby

Body:
Difference in days:

%w[2019-05-30T19:37:18+00:00 2019-05-30T19:37:30+05:30].
  map { |d| DateTime.iso8601(d) }.reduce(:-)
#⇒ (1649/7200)

In hours:

%w[2019-05-30T19:37:18+00:00 2019-05-30T19:37:30+05:30].
  map { |d| DateTime.iso8601(d) }.reduce(:-) * 24
#⇒ (1649/300)

In minutes:

%w[2019-05-30T19:37:18+00:00 2019-05-30T19:37:30+05:30].
  map { |d| DateTime.iso8601(d) }.reduce(:-) * 24 * 60
#⇒ (1649/5)

The outcome is Rational to preserve accuracy. One might convert it to integer, float, or decimal.


问:
idleTimerDisabled not working with (Autonomous) Single App Mode
We have a kiosk app where we use idleTimerDisabled to keep the screen from turning off during the working hours, and let it switch off in the evening.

I do this with a timer created in the applicationDidBecomeActive method:

```<code>self.screenLockTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(setupScreenLock) userInfo:nil repeats:YES];
</code>```

-

```<code>- (void)setupScreenLock {
    NSDate *currentDate = [NSDate date];
    NSDate *closingDate = [[NSCalendar currentCalendar] dateBySettingHour:17 minute:0 second:0 ofDate:currentDate options:0];
    BOOL isOpeningHours = [currentDate compare:closingDate] == NSOrderedAscending;
    [UIApplication sharedApplication].idleTimerDisabled = isOpeningHours;
}
</code>```

This used to work fine until we started using Autonomous Single App Mode. Now the screen no longer turns off in the evening. Is there an explanation (and a workaround) for this? I know that there is a bug in iOS 12 where idleTimerDisabled no longer works with Guided Access, but I haven't seen reports on similar issues with Single App Mode.

答:
Triggering a native operation might "fix" the problem. I was able to resolve my issues using the code below.

Try using the following code:

```<code>    [UIApplication sharedApplication].idleTimerDisabled = isOpeningHours;

    // Guided access idle timer fix
    UITextField *textField = [[UITextField alloc] init];
    [self.view addSubview:textField]; // self.view or whatever relevant view is accessible.
    [textField becomeFirstResponder];
    [textField resignFirstResponder];
    [textField removeFromSuperView];
</code>```

Body:
We have a kiosk app where we use idleTimerDisabled to keep the screen from turning off during the working hours, and let it switch off in the evening.

I do this with a timer created in the applicationDidBecomeActive method:

self.screenLockTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(setupScreenLock) userInfo:nil repeats:YES];

-

- (void)setupScreenLock {
    NSDate *currentDate = [NSDate date];
    NSDate *closingDate = [[NSCalendar currentCalendar] dateBySettingHour:17 minute:0 second:0 ofDate:currentDate options:0];
    BOOL isOpeningHours = [currentDate compare:closingDate] == NSOrderedAscending;
    [UIApplication sharedApplication].idleTimerDisabled = isOpeningHours;
}

This used to work fine until we started using Autonomous Single App Mode. Now the screen no longer turns off in the evening. Is there an explanation (and a workaround) for this? I know that there is a bug in iOS 12 where idleTimerDisabled no longer works with Guided Access, but I haven't seen reports on similar issues with Single App Mode.

Body:
Triggering a native operation might "fix" the problem. I was able to resolve my issues using the code below.

Try using the following code:

    [UIApplication sharedApplication].idleTimerDisabled = isOpeningHours;

    // Guided access idle timer fix
    UITextField *textField = [[UITextField alloc] init];
    [self.view addSubview:textField]; // self.view or whatever relevant view is accessible.
    [textField becomeFirstResponder];
    [textField resignFirstResponder];
    [textField removeFromSuperView];


问:
How to delete element from xml file in C#
I have list of people with some data called Person. I would like to delete selected person based on its name (in this example).

That's my code which saves list of Persons to an XML file:

```<code>        string path = "E:\\test.xml";
        var list = new List<Person>();
        list.Add(new Person { Name = "Tom", Value = 40 });
        list.Add(new Person { Name = "John", Value = 33 });
        var serializer = new XmlSerializer(typeof(List<Person>));
        var writer = new StreamWriter(path);
        serializer.Serialize(writer, list);
        writer.Close();
</code>```

Now i would like to delete Person object John and all data tied with this object from an xml file.

I tried few things, but none of them seemed to work. I would like to find out how to this using this simple example which will help me to step ahead.

Kind Regards,
Tamara

答:
As it has been mentioned in the comments, you need to read the XML file into an XDocument object. Once the XDocument has been created, you can work with the elements inside that XDocument. Below is how you would remove the element where the Value is "John"</p>

```<code> var xml = File.ReadAllText(path);
            XDocument doc = XDocument.Parse(xml);
            doc.Descendants().Elements("Person")
                .Where(x => x.Element("Name")?.Value == "John")
                .Remove();
            var result = doc.ToString();
</code>```

Body:
I have list of people with some data called Person. I would like to delete selected person based on its name (in this example).

That's my code which saves list of Persons to an XML file:

        string path = "E:\\test.xml";
        var list = new List<Person>();
        list.Add(new Person { Name = "Tom", Value = 40 });
        list.Add(new Person { Name = "John", Value = 33 });
        var serializer = new XmlSerializer(typeof(List<Person>));
        var writer = new StreamWriter(path);
        serializer.Serialize(writer, list);
        writer.Close();

Now i would like to delete Person object John and all data tied with this object from an xml file.

I tried few things, but none of them seemed to work. I would like to find out how to this using this simple example which will help me to step ahead.

Kind Regards,
Tamara

Body:
As it has been mentioned in the comments, you need to read the XML file into an XDocument object. Once the XDocument has been created, you can work with the elements inside that XDocument. Below is how you would remove the element where the Value is "John"

 var xml = File.ReadAllText(path);
            XDocument doc = XDocument.Parse(xml);
            doc.Descendants().Elements("Person")
                .Where(x => x.Element("Name")?.Value == "John")
                .Remove();
            var result = doc.ToString();


问:
Simple-git requesting username and password on each git command
Here is the problem https://www.npmjs.com/package/simple-git. I am using npm module simple-git to work with a local git-repository. The local git repository is already checkout locally and I can work with the repository via git-bash (commit/push/pull all works).
In the same time when any command performed on the same repository via simple-git requires me to enter username and password each time.

How can I make simple-git use my existing credentials and stop asking me for username and password on each git command ?

PS When simple-git is initialized I simply provide the path to the repository. This should be enough and it should use the .git/config file. Maybe something in this .git/config need to be / can be set to help it stop asking for username and password.

答:
The recommended way is to clone the repository with the credentials (so the remote will already contain the username and password).

If the repository is already cloned and you don't want to mess with the remote, you can pass the URL with the credentials in them to the git command. Here's an example for push.

const remotes = await git.getRemotes(true);
if (remotes.length) { // Otherwise it's a local repository, no push
    let remote = remotes[0].name;
    if (remotes[0].refs.push.indexOf("@") < 0) { // credentials aren't in the remote ref
        remote = remotes[0].refs.push.replace("://", `://${USER}:${PASSWORD}@`);
    }
    const pushRes = await git.push(remote, "master");
}
```


问:
Java util Logger not writing to file
I have written a silly Logger for my application. It writes into a log file info, warning and severe messages. It worked perfectly some time ago, but suddenly, it stopped working for no aparent reason.
It keeps creating the log file if it does not exist, but no content is written.
I can't find why it is not working now. I would thank some help.

Debugging with my IDE, I realise that messages are passed correctly to logger, and logger.info() is being executed.

```<code>public class FsLogger {

    private static FsLogger instance;

    private final String filename = "Logs/LogFsForensics.log";
    private final String loggerName = "FsLogger";
    private static Logger logger;
        private FileHandler fh;
        private final int limit = 1024*10000; //10 MB
        private SimpleFormatter sf;

    private FsLogger() {
        logger =  Logger.getLogger(loggerName);

        sf = new SimpleFormatter();
        try {
            fh = new FileHandler(filename, limit, 1, true);
            sf = new SimpleFormatter();
            fh.setFormatter(sf);

            logger.addHandler(fh);
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
    }

    public static FsLogger getInstance() {
        if(instance == null) {
            instance = new FsLogger();
        }
        return instance;
    }

    public void info(String message) {
        logger.info(message);
    }

    public void warning(String message) {
        logger.warning(message);
    }

    public void severe(String message) {
        logger.severe(message);
    }
</code>```

Example of a logger call:

```<code>private FsLogger logger = FsLogger.getInstance();
logger.severe(e1.getMessage());
</code>```

答:
From the code you are using a relative path of Logs/LogFsForensics.log  This means that if the current working directory if the process changes the path will be invalid.  When that happens the FileHandler will create a file in the default location.  Use an absolute path or specify one of the FileHandler special components. For example:

/Logs/LogFsForensics.log as absolute path or %h/Logs/LogFsForensics.log as relative from home directory.

You can modify the test program from Logging not showing to print the logger tree and and handlers. It is possible the levels are not set correctly or the handler was not installed.

Looking at the code, I would think that you want getInstance to be synchronized so you never attempt to create more than one handler.

Title: Java util Logger not writing to file

Body:
I have written a silly Logger for my application. It writes into a log file info, warning and severe messages. It worked perfectly some time ago, but suddenly, it stopped working for no aparent reason.
It keeps creating the log file if it does not exist, but no content is written.
I can't find why it is not working now. I would thank some help.

Debugging with my IDE, I realise that messages are passed correctly to logger, and logger.info() is being executed.

public class FsLogger {

    private static FsLogger instance;

    private final String filename = "Logs/LogFsForensics.log";
    private final String loggerName = "FsLogger";
    private static Logger logger;
        private FileHandler fh;
        private final int limit = 1024*10000; //10 MB
        private SimpleFormatter sf;

    private FsLogger() {
        logger =  Logger.getLogger(loggerName);

        sf = new SimpleFormatter();
        try {
            fh = new FileHandler(filename, limit, 1, true);
            sf = new SimpleFormatter();
            fh.setFormatter(sf);

            logger.addHandler(fh);
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
    }

    public static FsLogger getInstance() {
        if(instance == null) {
            instance = new FsLogger();
        }
        return instance;
    }

    public void info(String message) {
        logger.info(message);
    }

    public void warning(String message) {
        logger.warning(message);
    }

    public void severe(String message) {
        logger.severe(message);
    }

Example of a logger call:

private FsLogger logger = FsLogger.getInstance();
logger.severe(e1.getMessage());


问:
How can I access an element (of a custom component) by its 'id' within its parent? (ReactJS.Net)
I expect the following is excessively easy, which probably plays into why I've had trouble finding the solution on the web:

I would like to reference elements made from my custom components by there IDs using document.getElementById("id") from within a parent component.

I have created a couple of react components, one of which includes the other in the render function. I have given the inner element (I will refer to this as 'c1', and the outer as 'c0') an id="myID", and I would like to reference it using document.getElementById("myID").myValue. However, whenever I try to access it this way, I receive the error message TypeError: Unable to get property 'myValue' of undefined or null reference. C1 does have a property 'myValue', although I don't think that should matter to this particular error.

This effectively the pair of components, simplified to the relevant parts:

```<code>import React, {Component} from 'react';
import {c1} from './c1.js';

export class c0 extends Component
{
    displayName = c0.name

    constructor(props)
    {
        super(props);
        this.state = {
            testValue: ""
        }
    {

    componentDidUpdate() {
        this.setState({
            testValue: document.getElementById("myID").id
        });
    }

    render() {
        return (
            <div id="testID">
                <c1 id="myID" />
            </div>
        );
    }
}
</code>```

```<code>import React, {Component} from 'react';

export class c1 extends Component
{
    displayName = c1.name

    constructor(props)
    {
        super(props);
    {

    render() {
        return (
            <div>
                <p>Here is some content</p>
            </div>
        );
    }
}
</code>```

To be clear, c1 is rendering from within c2. I just can't access it from the document for some reason.

My searches have basically resulted in non-reactjs, explanations for what is "better" than using document.getElementById(), and questions that assume I've already gotten this far. The last is understandable, but not very helpful to me. Any help would be greatly appreciated.

Edit:
Upon further inspection, the component seems to render exclusively as the set of html elements it contains. In the sample provided, document.getElementById("testID").firstChild returns HTMLDivElement. Specifically, it returns whichever HTMLElement is outermost in c1's render() function. I assume this is normal to some degree, but I wouldn't know for sure. Directly accessing by 'id' still returns null.

答:
I did manage to find a workable solution. However, the following may not be sufficient for all users, so bear that in mind.

Within the render function of c1, I assigned the outermost
 the same id as c1 itself, like so:

.

It feels a bit patchwork, but it does the job. From this point, the properties of c1 can be changed or accessed when necessary, so long as those properties have also been assigned to that outermost
.

Body:
I expect the following is excessively easy, which probably plays into why I've had trouble finding the solution on the web:

I would like to reference elements made from my custom components by there IDs using document.getElementById("id") from within a parent component.

I have created a couple of react components, one of which includes the other in the render function. I have given the inner element (I will refer to this as 'c1', and the outer as 'c0') an id="myID", and I would like to reference it using document.getElementById("myID").myValue. However, whenever I try to access it this way, I receive the error message TypeError: Unable to get property 'myValue' of undefined or null reference. C1 does have a property 'myValue', although I don't think that should matter to this particular error.

This effectively the pair of components, simplified to the relevant parts:

import React, {Component} from 'react';
import {c1} from './c1.js';

export class c0 extends Component
{
    displayName = c0.name

    constructor(props)
    {
        super(props);
        this.state = {
            testValue: ""
        }
    {

    componentDidUpdate() {
        this.setState({
            testValue: document.getElementById("myID").id
        });
    }

    render() {
        return (

                <c1 id="myID" />

        );
    }
}

import React, {Component} from 'react';

export class c1 extends Component
{
    displayName = c1.name

    constructor(props)
    {
        super(props);
    {

    render() {
        return (

Here is some content

        );
    }
}

To be clear, c1 is rendering from within c2. I just can't access it from the document for some reason.

My searches have basically resulted in non-reactjs, explanations for what is "better" than using document.getElementById(), and questions that assume I've already gotten this far. The last is understandable, but not very helpful to me. Any help would be greatly appreciated.

Edit:
Upon further inspection, the component seems to render exclusively as the set of html elements it contains. In the sample provided, document.getElementById("testID").firstChild returns HTMLDivElement. Specifically, it returns whichever HTMLElement is outermost in c1's render() function. I assume this is normal to some degree, but I wouldn't know for sure. Directly accessing by 'id' still returns null.

Body:
I did manage to find a workable solution. However, the following may not be sufficient for all users, so bear that in mind.

Within the render function of c1, I assigned the outermost <div> the same id as c1 itself, like so:

<div id={this.props.id}>.

It feels a bit patchwork, but it does the job. From this point, the properties of c1 can be changed or accessed when necessary, so long as those properties have also been assigned to that outermost <div>.


问:
Will Android ListView load faster than Customized View?
I need to display a complicated list in my app. On each row there will be a checkbox and some TextView.

I know this could be done via ListView/Adapter, but I was worried it requires too much tweaking to make it fits my specific requirement, so I just created my own customized MyListView inheriting LinearLayout. On initiating, it adds MyListViewItem (inherited from RelativeLayout) dynamically.

The customized view functions fine. However, I notice that the rendering speed of MyListView is a little too slow, so I wondered will it be faster if I use ListView/Adapter instead?

Thanks,

答: ListView recycles its items. So, yes, it will work much more efficiently in case of a large number of list items. And as a result you'll obtain a less complicated view hierarchy.</p>


问:
How to concat a calculation and use leading '0' in a view
I have a question about concat function an dleading '0' in a view.
the code I used in the view is:

```<code>SELECT DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week, YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year
</code>```

This gives me the correct result.
I would preferably want to have the data that is now spread over 2 columns in the same column.

Also it would be great to have a leading '0' when the result of 'Week' is a sigle digit.

Everything i tried gave an error.

Thanks for your help,

Kind regards

I expect output of (column1: '9') and (column2: '19') to be (column1: '0919')

答:
You could convert your resiult to varchar, and append 00 to the start of the weeks, then take the right2 of these chars - leaving you the desired output:</p>

```<code> SELECT
 RIGHT('00'+CONVERT(VARCHAR,DATEPART(ISO_WEEK, GETDATE()) + 1),2) +''+ CONVERT(VARCHAR,YEAR(CURRENT_TIMESTAMP) % 2000 % 100) [yourcol]
 FROM YOURTABLE
</code>```

Body:
I have a question about concat function an dleading '0' in a view.
the code I used in the view is:

SELECT DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week, YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year

This gives me the correct result.
I would preferably want to have the data that is now spread over 2 columns in the same column.

Also it would be great to have a leading '0' when the result of 'Week' is a sigle digit.

Everything i tried gave an error.

Thanks for your help,

Kind regards

I expect output of (column1: '9') and (column2: '19') to be (column1: '0919')

Body:
You could convert your resiult to varchar, and append 00 to the start of the weeks, then take the right2 of these chars - leaving you the desired output:

 SELECT
 RIGHT('00'+CONVERT(VARCHAR,DATEPART(ISO_WEEK, GETDATE()) + 1),2) +''+ CONVERT(VARCHAR,YEAR(CURRENT_TIMESTAMP) % 2000 % 100) [yourcol]
 FROM YOURTABLE


问:
How to write a plugin loader for a module written in typescript
I'm working on a module that as part of its startup will load in dynamically other modules based on a configuration file, which provided the name of packages or files to import. I had something written up in vanilla JS that worked well, but I'm struggling to translating it to Typescript.

In Javascript, I was doing:

./src/main.js (assume config.plugins = ['./plugin']):

```<code>class ModuleName {
  constructor(config) {
    for (let plugin of config.plugins) {
      let register = require(plugin);
      register(this);
    }
  }
}
</code>```

./src/plugin.js:

```<code>class Plugin() {
}

module.exports = (main_module) => {
  main_module.plugin = new Plugin();
}
</code>```

Attempting to translate this to Typescript got me to (with the main perceived difference being that the plugins are loaded now asynchronously, which is a problem, but that at least compiles, so not my focus here):

./src/main.ts:

```<code>interface Config {
  plugins: string[];
}

interface Plugin {
  register(main_module: ModuleName): void;
}

export class ModuleName {
  public config: Config;
  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<string[]> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<string[]> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
    return plugins;
  }
}
</code>```

./src/plugin.ts:

```<code>import { ModuleName } from './index';

declare module './index' {
  export interface ModuleName {
    plugin: Plugin;
  }
}

export class Plugin {
  public foo(): void {
    console.log('Plugin::foo');
  }
}

export function register(main_module: ModuleName): void {
  main_module.plugin = new Plugin();
}
</code>```

now, in the main.ts it allows me to reference this.plugin freely. However, when I attempt to import this into a project, I don't can't reference the plugin.

For example, compiling the above to the ./dist folder, and having the following (at the root of my project):

./test.ts

```<code>import { ModuleName } from './dist';

let a = new ModuleName({plugins: ['./plugin']});
a.init().then(a.plugin.foo()).catch(console.error);
</code>```

errors with tsc saying Property 'plugin' does not exist on type 'ModuleName'.

答:
It looks like you're loading it asynchronously and probably attempting to access it too quickly. It's definitely not a good idea to use setTimeout to ensure asynchronous processes are completed when you need them (what if the process takes 50 ms on a fast computer, but 500 on a slow one?); instead, you want to access the Promise directly so you can use Promise.then(). The problem is you never want to return anything but the object itself from a constructor, so you never want to have asynchronous constructors. A better pattern would be to have a separate initialization function that performs the asynchronous process.

Furthermore, import(plugin) returns a Promise, not the plugin itself. Therefore, you must also handle this accordingly and wait to resolve the Promise returned by loadPlugins until after all of the imports resolve. That's probably not a very easy statement to read, so here's some code which can explain it far better than I can:

```<code>export class ModuleName {
  private config: Config;

  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<void> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<void> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
  }
}
</code>```

Now, when initializing, you need to properly handle the asynchronous initialization:

let a = new ModuleName(config);
a.init().then(() => {
  a.plugin.foo();
}).catch(err => console.error(err));
```

<p>or even just this will work:</p>

<pre class="lang-js prettyprint-override"><code>let a = new ModuleName(config);
a.init().then(a.plugin.foo).catch(console.error)
</code>```

Body:
I'm working on a module that as part of its startup will load in dynamically other modules based on a configuration file, which provided the name of packages or files to import. I had something written up in vanilla JS that worked well, but I'm struggling to translating it to Typescript.

In Javascript, I was doing:

./src/main.js (assume config.plugins = ['./plugin']):

class ModuleName {
  constructor(config) {
    for (let plugin of config.plugins) {
      let register = require(plugin);
      register(this);
    }
  }
}

./src/plugin.js:

class Plugin() {
}

module.exports = (main_module) => {
  main_module.plugin = new Plugin();
}

Attempting to translate this to Typescript got me to (with the main perceived difference being that the plugins are loaded now asynchronously, which is a problem, but that at least compiles, so not my focus here):

./src/main.ts:

interface Config {
  plugins: string[];
}

interface Plugin {
  register(main_module: ModuleName): void;
}

export class ModuleName {
  public config: Config;
  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<string[]> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<string[]> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
    return plugins;
  }
}

./src/plugin.ts:

import { ModuleName } from './index';

declare module './index' {
  export interface ModuleName {
    plugin: Plugin;
  }
}

export class Plugin {
  public foo(): void {
    console.log('Plugin::foo');
  }
}

export function register(main_module: ModuleName): void {
  main_module.plugin = new Plugin();
}

now, in the main.ts it allows me to reference this.plugin freely. However, when I attempt to import this into a project, I don't can't reference the plugin.

For example, compiling the above to the ./dist folder, and having the following (at the root of my project):

./test.ts

import { ModuleName } from './dist';

let a = new ModuleName({plugins: ['./plugin']});
a.init().then(a.plugin.foo()).catch(console.error);

errors with tsc saying Property 'plugin' does not exist on type 'ModuleName'.

Body:
It looks like you're loading it asynchronously and probably attempting to access it too quickly. It's definitely not a good idea to use setTimeout to ensure asynchronous processes are completed when you need them (what if the process takes 50 ms on a fast computer, but 500 on a slow one?); instead, you want to access the Promise directly so you can use Promise.then(). The problem is you never want to return anything but the object itself from a constructor, so you never want to have asynchronous constructors. A better pattern would be to have a separate initialization function that performs the asynchronous process.

Furthermore, import(plugin) returns a Promise, not the plugin itself. Therefore, you must also handle this accordingly and wait to resolve the Promise returned by loadPlugins until after all of the imports resolve. That's probably not a very easy statement to read, so here's some code which can explain it far better than I can:

export class ModuleName {
  private config: Config;

  public constructor(config: Config) {
    this.config = config;
  }

  public async init(): Promise<void> {
    return this.loadPlugins(this.config.plugins);
  }

  // You don't need to return anything from here because `async` functions
  // always return a `Promise`.
  private async loadPlugins(plugins: string[]): Promise<void> {
    for (let plugin of plugins) {
      // Here using `async`/`await` is a lot less complicated than using
      // `then()` because of the `for...of` loop
      let loaded: Plugin = await import(plugin);
      loaded.register(this);
    }
  }
}

Now, when initializing, you need to properly handle the asynchronous initialization:

let a = new ModuleName(config);
a.init().then(() => {
  a.plugin.foo();
}).catch(err => console.error(err));

or even just this will work:

let a = new ModuleName(config);
a.init().then(a.plugin.foo).catch(console.error)


问:
check if item can be converted to string?
I am writing a debug method.

What I have is

```<code>if(is_xxx($item)){
 //echo output info for type
}
</code>```

what I want to do at the end is

```<code>if(can_be_string($item))
echo $item;
</code>```

Is there a can_be_string type function?

答:
It's very simple:

```<code>function can_be_string($var)
{
    return method_exists($var, '__toString') || (is_scalar($var) && !is_null($var));
}
</code>```

The code has already been tested.
The method_exists() function returns false if $var is not an object, so this verification is not necessary.

Body:
I am writing a debug method.

What I have is

if(is_xxx($item)){
 //echo output info for type
}

what I want to do at the end is

if(can_be_string($item))
echo $item;

Is there a can_be_string type function?

Body:
It's very simple:

function can_be_string($var)
{
    return method_exists($var, '__toString') || (is_scalar($var) && !is_null($var));
}

The code has already been tested.
The method_exists() function returns false if $var is not an object, so this verification is not necessary.