问:
Looking for exact cause and resolution of : java.io.IOException: An existing connection was forcibly closed by the remote host
The exception is thrown using Apache FTPClient in LOCAL_PASSIVE_MODE. The process is running from a PC in a remote site over a satellite connection which I know to be less than stable. The same code works flawlessly over a stable connection to the same server, but I'm not sure if the difference comes from the stability of the connection, or the speed (ie, server configured timeouts)

My questions are as follows :

Is it necessarily the case that the connection was closed by the remote host (as stated in the exception), or is it possible that an interupted internet connection will generate the same exception ?

If it is true that an interupted internet connection will cause this exception how can I parameterize the FTPClient, or the underlying Socket to retry and resume the connection ?

How can I test if the connection was closed by the remote server or interupted ?

The FTPClient is configured for :

Connection timeout : 10 minutes

Data timeout : 10 minutes

Keep alive : enabled

Keep alive signals sent every 10 seconds

Keep alive reply from server timeout : 10 minutes

FTP buffer size : 1024 x 1024

I am waiting to receive the server configuration file and the server logs.

The stack trace is as follows :

```<code>java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:317)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:45)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:683)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:659)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:648)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$600(AbstractPollingIoProcessor.java:68)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1120)
    at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
</code>```

答:
Is it necessarily the case that the connection was closed by the remote host (as stated in the exception), or is it possible that an interupted internet connection will generate the same exception?

No. The localhost received an RST from the peer. If the Internet connection was interrupted this would cause the local TCP to abort the connection, eventually, with a different message, such as 'software caused connection abort' or 'the connection was aborted by the software in your local host', whatever the exact wording is on your system. If it says 'by the remote host', it means it.

If it is true that an interupted internet connection will cause this exception

It isn't.

how can I parameterize the FTPClient, or the underlying Socket to retry and resume the connection?

I can't answer for the FTPClient, but a Socket that has had this exception is dead and must be closed. It cannot retry anything.

It would be more to the point to examine why the peer aborted the connection. For example, you may be violating an upload-size limit.

How can I test if the connection was closed by the remote server or interrupted?

Via the error message, unfortunately. They could have mapped the various errno values that can arise in sockets to different IOException or indeed SocketException subclasses, but they only did so in a few cases, such as ConnectException, SocketTimeoutException, ...

Body:
The exception is thrown using Apache FTPClient in LOCAL_PASSIVE_MODE. The process is running from a PC in a remote site over a satellite connection which I know to be less than stable. The same code works flawlessly over a stable connection to the same server, but I'm not sure if the difference comes from the stability of the connection, or the speed (ie, server configured timeouts)

My questions are as follows :

Is it necessarily the case that the connection was closed by the remote host (as stated in the exception), or is it possible that an interupted internet connection will generate the same exception ?

If it is true that an interupted internet connection will cause this exception how can I parameterize the FTPClient, or the underlying Socket to retry and resume the connection ?

How can I test if the connection was closed by the remote server or interupted ?

The FTPClient is configured for :

Connection timeout : 10 minutes

Data timeout : 10 minutes

Keep alive : enabled

Keep alive signals sent every 10 seconds

Keep alive reply from server timeout : 10 minutes

FTP buffer size : 1024 x 1024

I am waiting to receive the server configuration file and the server logs.

The stack trace is as follows :

java.io.IOException: An existing connection was forcibly closed by the remote host
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(Unknown Source)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:317)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:45)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:683)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:659)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:648)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$600(AbstractPollingIoProcessor.java:68)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1120)
    at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


来源: stackexchange

问:
Python Guessing Game Error?
I created a number guessing game. However, I keep on running into an error.

The problem is when I run it and enter the number it will eventually say the number is higher than 74 (this is an example) but lower than 75... If I set a specific number it works fine, but when I generate a random number it doesn't work.

```<code>import random
from tkinter import *

def checkInput():

   randomNumber = random.randint(1,100)
   user_guess = int(user_input.get())

   if user_guess == randomNumber:
        print("You got it!")
   if user_guess > randomNumber:
        print("Guess lower!")
   if user_guess < randomNumber:
        print("Guess higher!")

root = Tk()

user_input = Entry(root)
user_input.pack()
check_button = Button(root,text="Check",command=checkInput) .pack()
reset_button = Button(root,text="Reset") .pack()

root.mainloop
</code>```

答:
the problem is that you are generating the random number in the "checkInput" function which will be called and changed everytime you press the "Check" button. What you should do is to generate the random number once and outside the "checkInput" function, for example look at the following code:

```<code>import random
from tkinter import *

def checkInput():

   user_guess = int(user_input.get())

   if user_guess == randomNumber:
        print("You got it!")
   if user_guess > randomNumber:
        print("Guess lower!")
   if user_guess < randomNumber:
        print("Guess higher!")

randomNumber = random.randint(1,100)
root = Tk()

user_input = Entry(root)
user_input.pack()
check_button = Button(root,text="Check",command=checkInput) .pack()
reset_button = Button(root,text="Reset") .pack()

root.mainloop()
</code>```

It is basically your own code with a minor change which is that the line where you generate the random number has been now moved out of the "checkInput" function.

Good Luck ...

ContentLicense: CC BY-SA 3.0

Title: Python Guessing Game Error?

Body:
I created a number guessing game. However, I keep on running into an error.

The problem is when I run it and enter the number it will eventually say the number is higher than 74 (this is an example) but lower than 75... If I set a specific number it works fine, but when I generate a random number it doesn't work.

import random
from tkinter import *

def checkInput():

   randomNumber = random.randint(1,100)
   user_guess = int(user_input.get())

   if user_guess == randomNumber:
        print("You got it!")
   if user_guess > randomNumber:
        print("Guess lower!")
   if user_guess < randomNumber:
        print("Guess higher!")

root = Tk()

user_input = Entry(root)
user_input.pack()
check_button = Button(root,text="Check",command=checkInput) .pack()
reset_button = Button(root,text="Reset") .pack()

root.mainloop

Body:
the problem is that you are generating the random number in the "checkInput" function which will be called and changed everytime you press the "Check" button. What you should do is to generate the random number once and outside the "checkInput" function, for example look at the following code:

import random
from tkinter import *

def checkInput():

   user_guess = int(user_input.get())

   if user_guess == randomNumber:
        print("You got it!")
   if user_guess > randomNumber:
        print("Guess lower!")
   if user_guess < randomNumber:
        print("Guess higher!")

randomNumber = random.randint(1,100)
root = Tk()

user_input = Entry(root)
user_input.pack()
check_button = Button(root,text="Check",command=checkInput) .pack()
reset_button = Button(root,text="Reset") .pack()

root.mainloop()

It is basically your own code with a minor change which is that the line where you generate the random number has been now moved out of the "checkInput" function.

Good Luck ...


问:
Angular ui-grid editable feature should work on one click only
Here is the tutorial link for angular ui-grid editable feature Angular ui-grid editable tutorial link.

As per the tutorial/ official plnkr of editable ui-grid feature, editable rows/fields can be edited only when user double-clicks on it.

Which approach should I follow to make the rows/field editable only on single click?

答: There is additional functionality which I come to know Rows/field editable with one click . Cells or fields will be editable on one click too</p>


问:
Trying to get the host and port out of a url in php
Hi all hope this makes sense.

I am wondering if there is a way to split the following with php

so

```<code>$url = "http://50.7.71.219:7183/listen.mp3";
</code>```

I then need to split it into 2 more strings so i should get a result of :

```<code>$ip = "http://50.7.71.219";
$port = "7183";
</code>```

Thanks,
Jamie

答:
There is actually a built in way of doing this in PHP.  Use the parse_url function.  This method also returns a host of other information that could be useful, click here to learn more.

```<code><?php

$url = "http://50.7.71.219:7183/listen.mp3";
$parsedUrl = parse_url($url);
$ip = $parsedUrl['host'];
$port = (string) $parsedUrl['port'];

echo $ip . "<br />" . $port;

?>
</code>```

Body:
Hi all hope this makes sense.

I am wondering if there is a way to split the following with php

so

$url = "http://50.7.71.219:7183/listen.mp3";

I then need to split it into 2 more strings so i should get a result of :

$ip = "http://50.7.71.219";
$port = "7183";

Thanks,
Jamie

Body:
There is actually a built in way of doing this in PHP.  Use the parse_url function.  This method also returns a host of other information that could be useful, click here to learn more.

<?php

$url = "http://50.7.71.219:7183/listen.mp3";
$parsedUrl = parse_url($url);
$ip = $parsedUrl['host'];
$port = (string) $parsedUrl['port'];

echo $ip . "<br />" . $port;

?>


问:
Mongodb Increment value inside nested array not working
I'm building a app where you can vote on user submitted polls. Here's the schema for my polls:

```<code>const pollSchema = new Schema({
    userID: String,
    pollQuestion: String,
    pollOptions: [
        {
            name: String,
            quantity: Number
        }
    ]
})
</code>```

This is the express route that handles incrementing the quantity of a poll option:

```<code>app.put('/vote', (req, res) => {
    Poll.update(
        {
            id: req.body.id,
            'pollOptions.name': req.body.selection
        },
        { $inc: { 'pollOptions.$.quantity': 1 } }
    ).then(updatedPoll => {
        console.log('poll', updatedPoll)
        res.send(updatedPoll)
    })
})
</code>```

here req.body.selection is the option that the user has chosen to vote for.

I basically want the quantity of the user's chosen option to increment by one. This way of updating the database I derived from the answer to this question

When I send a request to this route I get some very unexpected behaviour. For one thing, the database doesn't get updated or changed in any way. The second thing is the updatedPoll is a really bizarre object. Here's what i get from the console.log:

```<code>poll { n: 0,
  nModified: 0,
  opTime:
   { ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1510783687 },
     t: 1 },
  electionId: 7fffffff0000000000000001,
  ok: 1 }
</code>```

The one thing I've tried is include { new: true } as a third parameter after the object with the $inc operator. I doesn't change anything. Can someone please help with this issue?

答:
Thanks to Neil Lunn in the comments, changing my route to the following worked for me:</p>

```<code>poll.put('/vote', (req, res) => {
    Poll.findOneAndUpdate(
        {
            _id: req.body.id,
            pollOptions: {
                $elemMatch: { name: req.body.selection }
            }
        },
        { $inc: { 'pollOptions.$.quantity': 1 } },
        { new: true }
    ).then(poll => {
        res.send(poll)
    })
})
</code>```

Body:
I'm building a app where you can vote on user submitted polls. Here's the schema for my polls:

const pollSchema = new Schema({
    userID: String,
    pollQuestion: String,
    pollOptions: [
        {
            name: String,
            quantity: Number
        }
    ]
})

This is the express route that handles incrementing the quantity of a poll option:

app.put('/vote', (req, res) => {
    Poll.update(
        {
            id: req.body.id,
            'pollOptions.name': req.body.selection
        },
        { $inc: { 'pollOptions.$.quantity': 1 } }
    ).then(updatedPoll => {
        console.log('poll', updatedPoll)
        res.send(updatedPoll)
    })
})

here req.body.selection is the option that the user has chosen to vote for.

I basically want the quantity of the user's chosen option to increment by one. This way of updating the database I derived from the answer to this question

When I send a request to this route I get some very unexpected behaviour. For one thing, the database doesn't get updated or changed in any way. The second thing is the updatedPoll is a really bizarre object. Here's what i get from the console.log:

poll { n: 0,
  nModified: 0,
  opTime:
   { ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1510783687 },
     t: 1 },
  electionId: 7fffffff0000000000000001,
  ok: 1 }

The one thing I've tried is include { new: true } as a third parameter after the object with the $inc operator. I doesn't change anything. Can someone please help with this issue?

Body:
Thanks to Neil Lunn in the comments, changing my route to the following worked for me:

poll.put('/vote', (req, res) => {
    Poll.findOneAndUpdate(
        {
            _id: req.body.id,
            pollOptions: {
                $elemMatch: { name: req.body.selection }
            }
        },
        { $inc: { 'pollOptions.$.quantity': 1 } },
        { new: true }
    ).then(poll => {
        res.send(poll)
    })
})


问:
How to reverse an array in Swift?
How can I print the following array in reverse order?</p>

```<code>var toDoListReverse = ["Take out garbage", "Pay bills", "Cross off finished items"]
</code>```

答:
Swift 4

```<code>let numbers = [10, 50, 40]

for number in numbers.reversed() {

    print(number)
}
</code>```

// We can reverse an Array without allocating new space for its elements by calling this reversed() method.

OwnerDisplayName: anon

LastEditorDisplayName: anon

ContentLicense: CC BY-SA 4.0

Title: How to reverse an array in Swift?

Body:
How can I print the following array in reverse order?

var toDoListReverse = ["Take out garbage", "Pay bills", "Cross off finished items"]

Body:
Swift 4

let numbers = [10, 50, 40]

for number in numbers.reversed() {

    print(number)
}

// We can reverse an Array without allocating new space for its elements by calling this reversed() method.


问:
Node.js sever on ubuntu not receiving requests
When I place the IP Adress of the server and the port on the browser, there is no response and it does not get to the server. Here are some stats from the server; I am running the server on port 5403

```<code>sudo ufw status verbose

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere
80                         ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
5403                       ALLOW IN    Anywhere
22 (v6)                    ALLOW IN    Anywhere (v6)
80 (v6)                    ALLOW IN    Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
5403 (v6)                  ALLOW IN    Anywhere (v6)
</code>```

Another command

```<code>netstat -an | grep "LISTEN "

tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:25324           0.0.0.0:*               LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 :::5403                 :::*                    LISTEN
</code>```

答: You only listen to ipv6, this often pose a problem. Try to disable IPv6 and run on IPv4 address in stead.</p>

Body:
When I place the IP Adress of the server and the port on the browser, there is no response and it does not get to the server. Here are some stats from the server; I am running the server on port 5403

sudo ufw status verbose

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere
80                         ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
5403                       ALLOW IN    Anywhere
22 (v6)                    ALLOW IN    Anywhere (v6)
80 (v6)                    ALLOW IN    Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
5403 (v6)                  ALLOW IN    Anywhere (v6)

Another command

netstat -an | grep "LISTEN "

tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:25324           0.0.0.0:*               LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 :::5403                 :::*                    LISTEN


问:
Converting SQL Server HashBytes varbinary to Bigint
I have seen several blogs that show how to convert the result from HashBytes to a bigint when generating a hash for a set of values. This seems really common in data warehousing.  This has the advantage storing the hash as an integer which is great for joins and provides for good partition distribution.

I'm wondering though, if this is a good practice.  It has been brought to my attention that using Sha1 with HashBytes produces a 16 byte result.  Since bigint is an 8 byte data type, wouldn't this result in having to truncate the 16 bytes down 8 before converting it to the bigint?  If so, this seems like it would increase the possibility of collisions.

We have been converting our varbinary hashes to bigint for quite some time and have yet to encounter a collision, but it certainly seems like dumb luck if the assumptions above are true.

To test this I tried converting some hashes to see if I can get back to the original hash from the bigint, but was unable to do so which may be an indication of the problem (or I'm doing the conversion incorrectly).

Do any of your math gurus have any thoughts on this?
Thanks in advance!

```<code>DECLARE @value varchar(5) = '12345'
DECLARE @hash varbinary(max) = hashbytes('SHA1', @Value)

SELECT @hash AS OriginalHash
SELECT CAST(@hash as nvarchar(max)) AS StringHash
SELECT CAST(CAST(@hash as nvarchar(max)) as varbinary(max)) AS StringBackToOriginalHash
SELECT CAST(@hash as bigint) AS BigIntHash
SELECT CAST(CAST(@hash as bigint) as varbinary(max)) AS BigIntBackToOriginalHash
</code>```

With the recent indication from SQL 2016 that they are going to deprecate the older hashing algorithms, we will end up having to use Sha2_256 and Sha2_512 which are longer hashes which will take up quite a bit more space.  This would also be another reason why the use of bigint would be great if it was as collision resistant as the old Sha1 hashes.

答:
Actually I think I may have come across the answer in this article.
https://blogs.msdn.microsoft.com/sqlcat/2005/09/16/using-hashing-to-obscure-sensitive-data/

2)  Using a bigint built from a truncated hash may create an unacceptable risk of a hash collision if you are working with millions of SSN values.  The likelihood of a hash collision can be computed using the estimate that there is a 50% chance of a collision given 2^(#bits/2) input values.  For the bigint computed using 7 bytes, that means that there is a 50% chance of a collision if you hash 2^28 different values – or 268 million different SSNs.   So if your universe of input values is large, you may want to use the full hash string, or convert a longer substring of the hash to a Decimal value.

Body:
I have seen several blogs that show how to convert the result from HashBytes to a bigint when generating a hash for a set of values. This seems really common in data warehousing.  This has the advantage storing the hash as an integer which is great for joins and provides for good partition distribution.

I'm wondering though, if this is a good practice.  It has been brought to my attention that using Sha1 with HashBytes produces a 16 byte result.  Since bigint is an 8 byte data type, wouldn't this result in having to truncate the 16 bytes down 8 before converting it to the bigint?  If so, this seems like it would increase the possibility of collisions.

We have been converting our varbinary hashes to bigint for quite some time and have yet to encounter a collision, but it certainly seems like dumb luck if the assumptions above are true.

To test this I tried converting some hashes to see if I can get back to the original hash from the bigint, but was unable to do so which may be an indication of the problem (or I'm doing the conversion incorrectly).

Do any of your math gurus have any thoughts on this?
Thanks in advance!

DECLARE @value varchar(5) = '12345'
DECLARE @hash varbinary(max) = hashbytes('SHA1', @Value)

SELECT @hash AS OriginalHash
SELECT CAST(@hash as nvarchar(max)) AS StringHash
SELECT CAST(CAST(@hash as nvarchar(max)) as varbinary(max)) AS StringBackToOriginalHash
SELECT CAST(@hash as bigint) AS BigIntHash
SELECT CAST(CAST(@hash as bigint) as varbinary(max)) AS BigIntBackToOriginalHash

With the recent indication from SQL 2016 that they are going to deprecate the older hashing algorithms, we will end up having to use Sha2_256 and Sha2_512 which are longer hashes which will take up quite a bit more space.  This would also be another reason why the use of bigint would be great if it was as collision resistant as the old Sha1 hashes.


问:
How do you inner join, left join AND full join in one query?
I'm writing a web api in C# and I have a complicated SQL query to do in my get method. I've received an SQL file from a co-worker (who isn't here or reachable right now) which contains this:

```<code>FROM orsrg ors WITH (NOLOCK)
 INNER JOIN orkrg ork WITH (NOLOCK) ON ork.ordernr = ors.ordernr
 LEFT JOIN cicmpy c1 WITH (NOLOCK) ON ork.debnr = c1.debnr
 LEFT JOIN cicmpy c2 WITH (NOLOCK) ON ork.fakdebnr = c2.debnr
 LEFT JOIN cicmpy c3 WITH (NOLOCK) ON ork.verzdebnr = c3.debnr
 FULL JOIN humres h with (nolock) on h.res_id = ork.represent_id
</code>```

So far, here's the C#-code that I have for this:

```<code>// This "using" is used to make the tables in the SQL query run as "WITH (NOLOCK)" ! (IsolationLevel.ReadUncommitted)

using (var txn = new TransactionScope(
    TransactionScopeOption.Required,
    new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadUncommitted
    }
))
{
    // Your LINQ to SQL query goes here
    var query = (from ors in _context.Orsrg
                 join ork in _context.Orkrg on ors.Ordernr equals ork.Ordernr
                 join c1 in _context.Cicmpy.DefaultIfEmpty() on ork.Debnr equals c1.Debnr
                 join c2 in _context.Cicmpy.DefaultIfEmpty() on ork.Fakdebnr equals c2.Debnr
                 join c3 in _context.Cicmpy.DefaultIfEmpty() on ork.Verzdebnr equals c3.Debnr
                 // FULL JOIN MUST COME HERE
                 );
}
</code>```

As you can see, i've inner joined tables ors & ork and then did three left joins on tables c1, c2, c3 (all from Cicmpy though). So all that's left is the full join.

I've found following code also here on stackoverflow (this isn't my code):

```<code>var firstNames = new[]
{
    new { ID = 1, Name = "John" },
    new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
    new { ID = 1, Name = "Doe" },
    new { ID = 3, Name = "Smith" },
};
var leftOuterJoin = from first in firstNames
                    join last in lastNames
                    on first.ID equals last.ID
                    into temp
                    from last in temp.DefaultIfEmpty(new { first.ID, Name = default(string) })
                    select new
                    {
                        first.ID,
                        FirstName = first.Name,
                        LastName = last.Name,
                    };
var rightOuterJoin = from last in lastNames
                     join first in firstNames
                     on last.ID equals first.ID
                     into temp
                     from first in temp.DefaultIfEmpty(new { last.ID, Name = default(string) })
                     select new
                     {
                         last.ID,
                         FirstName = first.Name,
                         LastName = last.Name,
                     };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
</code>```

That code is doing the full outer join by partitioning it in 2 halves, once he does left outer join, once right outer join & then puts them together in one variable.

I have no idea how I could do this in my original C#-code where now it says

```<code>// FULL JOIN MUST COME HERE
</code>```

These SQL queries are a lot harder than in school...

答:
Some (somewhat) complicated extension methods will implement the full outer join for AsQueryable and translate to SQL, though perhaps not as efficiently as calling SQL directly with FULL OUTER JOIN.

First the extensions (there are some variations for IEnumerable in another answer here):

```<code>private static Expression<Func<TP, TC, TResult>> CastSMBody<TP, TC, TResult>(LambdaExpression ex, TP unusedP, TC unusedC, TResult unusedRes) => (Expression<Func<TP, TC, TResult>>)ex;

public static IQueryable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    var sampleAnonLR = new { left = (TLeft)null, rightg = (IEnumerable<TRight>)null };
    var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
    var parmC = Expression.Parameter(typeof(TRight), "c");
    var argLeft = Expression.PropertyOrField(parmP, "left");
    var newleftrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, parmC), parmP, parmC), sampleAnonLR, (TRight)null, (TResult)null);

    return leftItems.AsQueryable().GroupJoin(rightItems, leftKeySelector, rightKeySelector, (left, rightg) => new { left, rightg }).SelectMany(r => r.rightg.DefaultIfEmpty(), newleftrs);
}

private static Expression<Func<TParm, TResult>> CastSBody<TParm, TResult>(LambdaExpression ex, TParm unusedP, TResult unusedRes) => (Expression<Func<TParm, TResult>>)ex;

public static IQueryable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    var sampleAnonLgR = new { leftg = (IEnumerable<TLeft>)null, right = (TRight)null };
    var parmLgR = Expression.Parameter(sampleAnonLgR.GetType(), "lgr");
    var argLeft = Expression.Constant(null, typeof(TLeft));
    var argRight = Expression.PropertyOrField(parmLgR, "right");
    var newrightrs = CastSBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, argRight), parmLgR), sampleAnonLgR, (TResult)null);

    return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).Where(lgr => !lgr.leftg.Any()).Select(newrightrs);
}

public static IQueryable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
}
</code>```

You can then create your query. I had to modify it since you had the LEFT OUTER JOIN emulation incorrect. Also, I had to put in a select since their is no query comprehension syntax for full outer join and I didn't want to translate the rest of your query to lambda syntax.

NOTE: Your transaction will not do what you want since the creation of the query variable does not actually call the database. You need to do something to pull results from the query for the transaction (NOLOCK work around) to effect the query on SQL.

```<code>var query = (from ors in _context.Orsrg
             join ork in _context.Orkrg on ors.Ordernr equals ork.Ordernr
             join c1 in _context.Cicmpy on ork.Debnr equals c1.Debnr into c1j
             from c1 in c1j.DefaultIfEmpty()
             join c2 in _context.Cicmpy on ork.Fakdebnr equals c2.Debnr into c2j
             from c2 in c2j.DefaultIfEmpty()
             join c3 in _context.Cicmpy on ork.Verzdebnr equals c3.Debnr into c3j
             from c3 in c3j.DefaultIfEmpty()
             select new { ors, ork, c1, c2, c3 })
             .FullOuterJoin(_context.Humres, left => left.ork.represent_id, h => h.res_id, (_, left, h) => new { left.ors, left.ork, left.c1, left.c2, left.c3, h });
</code>```

Body:
I'm writing a web api in C# and I have a complicated SQL query to do in my get method. I've received an SQL file from a co-worker (who isn't here or reachable right now) which contains this:

FROM orsrg ors WITH (NOLOCK)
 INNER JOIN orkrg ork WITH (NOLOCK) ON ork.ordernr = ors.ordernr
 LEFT JOIN cicmpy c1 WITH (NOLOCK) ON ork.debnr = c1.debnr
 LEFT JOIN cicmpy c2 WITH (NOLOCK) ON ork.fakdebnr = c2.debnr
 LEFT JOIN cicmpy c3 WITH (NOLOCK) ON ork.verzdebnr = c3.debnr
 FULL JOIN humres h with (nolock) on h.res_id = ork.represent_id

So far, here's the C#-code that I have for this:

// This "using" is used to make the tables in the SQL query run as "WITH (NOLOCK)" ! (IsolationLevel.ReadUncommitted)

using (var txn = new TransactionScope(
    TransactionScopeOption.Required,
    new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadUncommitted
    }
))
{
    // Your LINQ to SQL query goes here
    var query = (from ors in _context.Orsrg
                 join ork in _context.Orkrg on ors.Ordernr equals ork.Ordernr
                 join c1 in _context.Cicmpy.DefaultIfEmpty() on ork.Debnr equals c1.Debnr
                 join c2 in _context.Cicmpy.DefaultIfEmpty() on ork.Fakdebnr equals c2.Debnr
                 join c3 in _context.Cicmpy.DefaultIfEmpty() on ork.Verzdebnr equals c3.Debnr
                 // FULL JOIN MUST COME HERE
                 );
}

As you can see, i've inner joined tables ors & ork and then did three left joins on tables c1, c2, c3 (all from Cicmpy though). So all that's left is the full join.

I've found following code also here on stackoverflow (this isn't my code):

var firstNames = new[]
{
    new { ID = 1, Name = "John" },
    new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
    new { ID = 1, Name = "Doe" },
    new { ID = 3, Name = "Smith" },
};
var leftOuterJoin = from first in firstNames
                    join last in lastNames
                    on first.ID equals last.ID
                    into temp
                    from last in temp.DefaultIfEmpty(new { first.ID, Name = default(string) })
                    select new
                    {
                        first.ID,
                        FirstName = first.Name,
                        LastName = last.Name,
                    };
var rightOuterJoin = from last in lastNames
                     join first in firstNames
                     on last.ID equals first.ID
                     into temp
                     from first in temp.DefaultIfEmpty(new { last.ID, Name = default(string) })
                     select new
                     {
                         last.ID,
                         FirstName = first.Name,
                         LastName = last.Name,
                     };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);

That code is doing the full outer join by partitioning it in 2 halves, once he does left outer join, once right outer join & then puts them together in one variable.

I have no idea how I could do this in my original C#-code where now it says

// FULL JOIN MUST COME HERE

These SQL queries are a lot harder than in school...

Body:
Some (somewhat) complicated extension methods will implement the full outer join for AsQueryable and translate to SQL, though perhaps not as efficiently as calling SQL directly with FULL OUTER JOIN.

First the extensions (there are some variations for IEnumerable in another answer here):

private static Expression<Func<TP, TC, TResult>> CastSMBody<TP, TC, TResult>(LambdaExpression ex, TP unusedP, TC unusedC, TResult unusedRes) => (Expression<Func<TP, TC, TResult>>)ex;

public static IQueryable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    var sampleAnonLR = new { left = (TLeft)null, rightg = (IEnumerable<TRight>)null };
    var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
    var parmC = Expression.Parameter(typeof(TRight), "c");
    var argLeft = Expression.PropertyOrField(parmP, "left");
    var newleftrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, parmC), parmP, parmC), sampleAnonLR, (TRight)null, (TResult)null);

    return leftItems.AsQueryable().GroupJoin(rightItems, leftKeySelector, rightKeySelector, (left, rightg) => new { left, rightg }).SelectMany(r => r.rightg.DefaultIfEmpty(), newleftrs);
}

private static Expression<Func<TParm, TResult>> CastSBody<TParm, TResult>(LambdaExpression ex, TParm unusedP, TResult unusedRes) => (Expression<Func<TParm, TResult>>)ex;

public static IQueryable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    var sampleAnonLgR = new { leftg = (IEnumerable<TLeft>)null, right = (TRight)null };
    var parmLgR = Expression.Parameter(sampleAnonLgR.GetType(), "lgr");
    var argLeft = Expression.Constant(null, typeof(TLeft));
    var argRight = Expression.PropertyOrField(parmLgR, "right");
    var newrightrs = CastSBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, argRight), parmLgR), sampleAnonLgR, (TResult)null);

    return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).Where(lgr => !lgr.leftg.Any()).Select(newrightrs);
}

public static IQueryable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
    this IQueryable<TLeft> leftItems,
    IQueryable<TRight> rightItems,
    Expression<Func<TLeft, TKey>> leftKeySelector,
    Expression<Func<TRight, TKey>> rightKeySelector,
    Expression<Func<TLeft, TRight, TResult>> resultSelector) where TLeft : class where TRight : class where TResult : class {

    return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
}

You can then create your query. I had to modify it since you had the LEFT OUTER JOIN emulation incorrect. Also, I had to put in a select since their is no query comprehension syntax for full outer join and I didn't want to translate the rest of your query to lambda syntax.

NOTE: Your transaction will not do what you want since the creation of the query variable does not actually call the database. You need to do something to pull results from the query for the transaction (NOLOCK work around) to effect the query on SQL.

var query = (from ors in _context.Orsrg
             join ork in _context.Orkrg on ors.Ordernr equals ork.Ordernr
             join c1 in _context.Cicmpy on ork.Debnr equals c1.Debnr into c1j
             from c1 in c1j.DefaultIfEmpty()
             join c2 in _context.Cicmpy on ork.Fakdebnr equals c2.Debnr into c2j
             from c2 in c2j.DefaultIfEmpty()
             join c3 in _context.Cicmpy on ork.Verzdebnr equals c3.Debnr into c3j
             from c3 in c3j.DefaultIfEmpty()
             select new { ors, ork, c1, c2, c3 })
             .FullOuterJoin(_context.Humres, left => left.ork.represent_id, h => h.res_id, (_, left, h) => new { left.ors, left.ork, left.c1, left.c2, left.c3, h });


问:
Python 2: How do I limit " from file import * " ONLY import defined symbols?
In Python2:

We all know about __all__ to limit the imports from a module using __init__.py This allows you to limit what gets imported when you issue:

```<code>from some_module import *
</code>```

How do you do this for all symbols in FILE (some_file.py) without generating a nasty __all__ list?

Say you have a local defs.py which contains all the global variables, classes, etc you want to use thruout your code. This typically occurs when you are refactoring code and/or do not want every symbol to have a namespace prefix and/or do not want a humongo from ... import statement. In many cases, you DO NOT want to include the symbols defs.py imports (perhaps the import itself has a side effect you want to preserve, or you do NOT want a symbol that defs.py imported)

How do you do this?

答:
One answer in Python2 (likely different in Python 3) is to generate a symbol table after the imports but before your code, and at the end. Then you define __all__ to be the difference of the two sets:

Example:

```<code>from some_gross_package import some_gross_symbol
import another_gross_package
from some_other_gross_package import *

# Anything above this line will be ignored.
excluded_symbols = set(dir())

from some_package_I_like import a_useful_symbol

# Now start generating symbols. Note that there will be a problem
# if you re-define a symbol from the excluded zone. Don't do that.
export_this1 = 1
export_this2 = "abc"

# Put this as the last line of your file
all_symbols = set(dir())
__all__ = list(all_symbols - excluded_symbols - {'excluded_symbols'})
</code>```

Caveats:

As noted, this will break if you redefine a symbol that you actually want to export that was originally in the excluded set. But don't do that.

Note also that this is really only for those cases in your local module where you want one defs.py file that contains all the various global symbols/classes (typically because you are refactoring code). But this is more of a religious issue of using from XYZ import *.

It is NOT the purpose of this question to get into a religious fight about import * :)

Body:
In Python2:

We all know about __all__ to limit the imports from a module using __init__.py This allows you to limit what gets imported when you issue:

from some_module import *

How do you do this for all symbols in FILE (some_file.py) without generating a nasty __all__ list?

Say you have a local defs.py which contains all the global variables, classes, etc you want to use thruout your code. This typically occurs when you are refactoring code and/or do not want every symbol to have a namespace prefix and/or do not want a humongo from ... import statement. In many cases, you DO NOT want to include the symbols defs.py imports (perhaps the import itself has a side effect you want to preserve, or you do NOT want a symbol that defs.py imported)

How do you do this?

Body:
One answer in Python2 (likely different in Python 3) is to generate a symbol table after the imports but before your code, and at the end. Then you define __all__ to be the difference of the two sets:

Example:

from some_gross_package import some_gross_symbol
import another_gross_package
from some_other_gross_package import *

# Anything above this line will be ignored.
excluded_symbols = set(dir())

from some_package_I_like import a_useful_symbol

# Now start generating symbols. Note that there will be a problem
# if you re-define a symbol from the excluded zone. Don't do that.
export_this1 = 1
export_this2 = "abc"

# Put this as the last line of your file
all_symbols = set(dir())
__all__ = list(all_symbols - excluded_symbols - {'excluded_symbols'})

Caveats:

As noted, this will break if you redefine a symbol that you actually want to export that was originally in the excluded set. But don't do that.

Note also that this is really only for those cases in your local module where you want one defs.py file that contains all the various global symbols/classes (typically because you are refactoring code). But this is more of a religious issue of using from XYZ import *.

It is NOT the purpose of this question to get into a religious fight about import * :)


问:
input for def in if statement trouble
When i start this code i want it to restart def start() inside my if part and make it so i can input 1 again and itll post it again but that doesnt work. I really dont know why and i would appreciate the help. I need this answered fairly quickly so i can finish my assignment. If it helps im using python in visual studio 2017.</p>

```<code>def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

if choice=="1":
    print("You call out")
    print("No one came")
    print(start())

else:
   print("nope")
</code>```

答:
You'll want to wrap the rest of the logic in a function and call it at the end again instead of start()

```<code>def question():

    def start():
        print("\nWhat would you like to do?")
        print("1) Call out to someone")
        print("2) Stand up")
        print("3) Touch your head")
        print("4) Sleep\n")
        choice = input("Make your decision!: ")

        return choice

    choice = start()

    if str(choice) == "1":
        print("You call out")
        print("No one came")
        question()
    else:
        print("nope")

question()
</code>```

Title: input for def in if statement trouble

Body:
When i start this code i want it to restart def start() inside my if part and make it so i can input 1 again and itll post it again but that doesnt work. I really dont know why and i would appreciate the help. I need this answered fairly quickly so i can finish my assignment. If it helps im using python in visual studio 2017.

def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

if choice=="1":
    print("You call out")
    print("No one came")
    print(start())

else:
   print("nope")

Body:
You'll want to wrap the rest of the logic in a function and call it at the end again instead of start()

def question():

    def start():
        print("\nWhat would you like to do?")
        print("1) Call out to someone")
        print("2) Stand up")
        print("3) Touch your head")
        print("4) Sleep\n")
        choice = input("Make your decision!: ")

        return choice

    choice = start()

    if str(choice) == "1":
        print("You call out")
        print("No one came")
        question()
    else:
        print("nope")

question()


问:
Android Architecture Components with Data Binnding
In Android Architecture Components docs on the Handling Lifecycle page in Best practices paragraph, written:

Use Data Binding to maintain a clean interface between your views and the UI controller.

Can someone provide me with link to example on how to use this libraries together?

答: You can take a look into this Google Sample, which applies Architecture Components and the Data Binding Library together.</p>


问:
What are the generic functions defined by the standard?
In Common Lisp there are a few generic functions defined by the standard, for instance functions to manipulate sequences.

However looking at Graham's book ANSI Common Lisp and Steele's book Common Lisp – The language at the relevant chapters, I could not find any list of the generic functions defined in the standard.

What are the generic functions defined by the standard?

答:
The question you asked

Functions that manipulate sequences
are not generic-functions.
They are listed in the section 17.3 The Sequences
Dictionary.

All symbols specified by the
standard are listed in the section 1.9 Symbols in the COMMON-LISP
Package.

A partial list of standardized
generic functions can be
found in section 7.7 The Objects
Dictionary (e.g.,
print-object is listed in
section 22.4 The Printer Dictionary).

The question you might have meant to ask

Finding existing Lisp functionality should not be hard using
apropos.
Once you see a plausibly looking symbol, use
describe to find out what it
actually does.

Remember that most implementations offer more that the standard specifies.
You can do something like this:

```<code>(dolist (pack (package-use-list "COMMON-LISP-USER"))
  (format t "~S~%" pack)
  (do-external-symbols (s pack)
    (when (and (fboundp s)
               (typep (fdefinition s) 'generic-function))
      (format t "  ~S~%" s))))
</code>```

Body:
The question you asked

Functions that manipulate sequences
are not generic-functions.
They are listed in the section 17.3 The Sequences
Dictionary.

All symbols specified by the
standard are listed in the section 1.9 Symbols in the COMMON-LISP
Package.

A partial list of standardized
generic functions can be
found in section 7.7 The Objects
Dictionary (e.g.,
print-object is listed in
section 22.4 The Printer Dictionary).

The question you might have meant to ask

Finding existing Lisp functionality should not be hard using
apropos.
Once you see a plausibly looking symbol, use
describe to find out what it
actually does.

Remember that most implementations offer more that the standard specifies.
You can do something like this:

(dolist (pack (package-use-list "COMMON-LISP-USER"))
  (format t "~S~%" pack)
  (do-external-symbols (s pack)
    (when (and (fboundp s)
               (typep (fdefinition s) 'generic-function))
      (format t "  ~S~%" s))))


问:
Are arrays covariant in their size?
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

```<code>void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}
</code>```

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

```<code>std::array<int, 10> arr;
DoSomething(arr);
</code>```

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

答:
No, but you can fake it:

```<code>// Hide this function however you like: "detail" namespace, use "_detail"
// in the name, etc.; since it's not part of the public interface.
void f_detail(int size, int *data) {
  use(data, /* up to */ data + size);
}

int const f_min_len = 5;

template<int N>
void f(int (&data)[N]) {
  static_assert(N >= f_min_len);
  f_detail(N, data);
}

template<int N>
void f(std::array<int, N> &data) {
  static_assert(N >= f_min_len);
  f_detail(N, &data[0]);
}
</code>```

This is a complete example, and should work exactly as presented.  You'd only have to change the data type from int (or make it a template parameter) and add const as required.

ContentLicense: CC BY-SA 2.5

Title: Are arrays covariant in their size?

Body:
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

std::array<int, 10> arr;
DoSomething(arr);

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

Body:
No, but you can fake it:

// Hide this function however you like: "detail" namespace, use "_detail"
// in the name, etc.; since it's not part of the public interface.
void f_detail(int size, int *data) {
  use(data, /* up to */ data + size);
}

int const f_min_len = 5;

template<int N>
void f(int (&data)[N]) {
  static_assert(N >= f_min_len);
  f_detail(N, data);
}

template<int N>
void f(std::array<int, N> &data) {
  static_assert(N >= f_min_len);
  f_detail(N, &data[0]);
}

This is a complete example, and should work exactly as presented.  You'd only have to change the data type from int (or make it a template parameter) and add const as required.


问:
Atom for a list in Erlang
Can I create a list with atoms as reference for them to later use it in my move method?

```<code>createLists(X) ->
  List = [
    listA = lists:seq(1, X),
    listB = [],
    listC = []
  ],
  List.
</code>```

Then I create like T = hello:createLists(10).

```<code>move(List, A, B) ->
  ...
</code>```

How can I obtain A and B using atoms? I'm pretty new to Erlang so the answer might be obvious.

move is supposed to move top element of the from A to B but I struggle to pass A and B when I do like hello:move(List, ?, ?).

答:
Regarding the code in your comment, @armedor:

```<code>1 move(List, a, b, c) ->
2   Source = proplists:get_value(a, List),
3   Dest = proplists:get_value(b, List),
4   Help = proplists:get_value(c, List),
5   Temp1 = [lists:nth(1,Source)],
6   NewDest = [lists:append(Dest,Temp1)],
7   NewSource = lists:subtract(Source,Temp1),
8   List1=[NewSource,NewDest,Help].
</code>```

Say List is defined as [ {a, lists:seq(1, 3)}, {b, []}, {c, []} ].
Line 8 isn't going to be a proplist anymore, but just the sublists themselves. Instead, create List1 as [{a, NewSource}, {b, NewDest}, Help].

You also don't need to assign to List1 in line 8, since the function is returning - just make the new list itself the last line, which will be the return value.

And the lists:nth and lists:subtract you're doing can be combined as

[Temp1 | NewSource] = Source

Title: Atom for a list in Erlang

Body:
Can I create a list with atoms as reference for them to later use it in my move method?

createLists(X) ->
  List = [
    listA = lists:seq(1, X),
    listB = [],
    listC = []
  ],
  List.

Then I create like T = hello:createLists(10).

move(List, A, B) ->
  ...

How can I obtain A and B using atoms? I'm pretty new to Erlang so the answer might be obvious.

move is supposed to move top element of the from A to B but I struggle to pass A and B when I do like hello:move(List, ?, ?).

Body:
Regarding the code in your comment, @armedor:

1 move(List, a, b, c) ->
2   Source = proplists:get_value(a, List),
3   Dest = proplists:get_value(b, List),
4   Help = proplists:get_value(c, List),
5   Temp1 = [lists:nth(1,Source)],
6   NewDest = [lists:append(Dest,Temp1)],
7   NewSource = lists:subtract(Source,Temp1),
8   List1=[NewSource,NewDest,Help].

Say List is defined as [ {a, lists:seq(1, 3)}, {b, []}, {c, []} ].
Line 8 isn't going to be a proplist anymore, but just the sublists themselves. Instead, create List1 as [{a, NewSource}, {b, NewDest}, Help].

You also don't need to assign to List1 in line 8, since the function is returning - just make the new list itself the last line, which will be the return value.

And the lists:nth and lists:subtract you're doing can be combined as

[Temp1 | NewSource] = Source


问:
Why is the Android test runner reporting "Empty test suite"?
I am banging my head against the wall here trying to figure out why IntelliJ/Android is reporting  "Empty test suite". I have a small project with two IntelliJ Modules ("Projects" in Eclipse). The Unit test module has its own AndroidManifest.xml, which I have pasted at the bottom. I am trying to run an ActivityUnitTestCase, since the tests will be dependent upon the Context-object.

The package name of the main module is nilzor.myapp. The pacakge name of the test module is nilzor.myapp.tests

Why is not the test runner detecting the testBlah()-method as a test?

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="nilzor.myapp.tests"
          android:versionCode="1"
          android:versionName="1.0">
    <!-- We add an application tag here just so that we can indicate that
         this package needs to link against the android.test library,
         which is needed when building test cases. -->
    <application>
        <uses-library android:name="android.test.runner"/>
    </application>
    <!--
    This declares that this application uses the instrumentation test runner targeting
    the package of nilzor.myapp.  To run the tests use the command:
    "adb shell am instrument -w nilzor.myapp.tests/android.test.InstrumentationTestRunner"
    -->
    <instrumentation android:name="android.test.InstrumentationTestRunner"
                     android:targetPackage="nilzor.myapp"
                     android:label="Tests for nilzor.myapp"/>
</manifest>
</code>```

And here is my test class:;

```<code>package nilzor.myapp.tests;

public class NilzorSomeTest<T extends Activity> extends ActivityUnitTestCase<T>{
    public NilzorSomeTest(Class<T> activityClass){
        super(activityClass);
    }

    @SmallTest
    public void testBlah(){
        assertEquals(1,1);
    }
}
</code>```

I have read the testing fundamentals, the activity testing document, and tried following this Hello world test blog, even though it is for Eclipse. I cannot get the test runner to find and run my test. What am I doing wrong?

Some of the questions I still feel unsure about are:

Do I need an Annotation above the Unit test method?

Do I need to prefix the method with "test", or is that just for JUnit tests?

Can I have tests in sub-packages of nilzor.myapp.tests?

But the main question of this post is why does not the test runner detect my test?

答: I had the same issue, and the reason was my test class did not have Test at the end of the class name!</p>

Body:
I am banging my head against the wall here trying to figure out why IntelliJ/Android is reporting  "Empty test suite". I have a small project with two IntelliJ Modules ("Projects" in Eclipse). The Unit test module has its own AndroidManifest.xml, which I have pasted at the bottom. I am trying to run an ActivityUnitTestCase, since the tests will be dependent upon the Context-object.

The package name of the main module is nilzor.myapp. The pacakge name of the test module is nilzor.myapp.tests

Why is not the test runner detecting the testBlah()-method as a test?

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="nilzor.myapp.tests"
          android:versionCode="1"
          android:versionName="1.0">

    <application>
        <uses-library android:name="android.test.runner"/>
    </application>

    <instrumentation android:name="android.test.InstrumentationTestRunner"
                     android:targetPackage="nilzor.myapp"
                     android:label="Tests for nilzor.myapp"/>
</manifest>

And here is my test class:;

package nilzor.myapp.tests;

public class NilzorSomeTest<T extends Activity> extends ActivityUnitTestCase<T>{
    public NilzorSomeTest(Class<T> activityClass){
        super(activityClass);
    }

    @SmallTest
    public void testBlah(){
        assertEquals(1,1);
    }
}

I have read the testing fundamentals, the activity testing document, and tried following this Hello world test blog, even though it is for Eclipse. I cannot get the test runner to find and run my test. What am I doing wrong?

Some of the questions I still feel unsure about are:

Do I need an Annotation above the Unit test method?

Do I need to prefix the method with "test", or is that just for JUnit tests?

Can I have tests in sub-packages of nilzor.myapp.tests?

But the main question of this post is why does not the test runner detect my test?


问:
Shared Preferences Not Applying Changes
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

```<code>    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}
</code>```

Activity (B):

```<code>        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }
</code>```

答:
Use commit() and not apply()

Unlike commit(), which writes its preferences out to persistent
  storage synchronously, apply() commits its changes to the in-memory
  SharedPreferences immediately but starts an asynchronous commit to
  disk and you won't be notified of any failures. If another editor on
  this SharedPreferences does a regular commit() while a apply() is
  still outstanding, the commit() will block until all async commits are
  completed as well as the commit itself.

https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

Title: Shared Preferences Not Applying Changes

Body:
I have an activity (A) that checks my server for APK updates. When this function is called, whether there is or is not an update, I need the shared preferences to be edited so the application knows to skip or run the actual update activity (B). Question 1 is, why are the shared preferences not being edited by activity (A)? Question 2 is, if they are being edited, why isn't activity (B) reading them?

Thank You in advance!

Shared preferences should be edited here (Activity (A)):

    private void parseJson(String result) {
    try {

        JSONObject obj = new JSONObject(result);
        String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
        String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
        int apkCode = obj.getInt(Constants.APK_VERSION_CODE);

        int versionCode = AppUtils.getVersionCode(mContext);

        if (apkCode > versionCode) {
            if (mType == Constants.TYPE_NOTIFICATION) {
                showNotification(mContext, updateMessage, apkUrl);
            } else if (mType == Constants.TYPE_DIALOG) {
                SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = pref.edit();
                ed.putBoolean("activity_update", true);
                ed.apply();
                showDialog(mContext, updateMessage, apkUrl);
            }
        } else if (mShowProgressDialog) {
            SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putBoolean("activity_update", false);
            ed.apply();
            Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "parse json error");
    }
}

Activity (B):

        SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_update", false)){
        Intent intent = new Intent(this, Main.class);
        deleteCache(getApplicationContext());
        startActivity(intent);
        finish();
    } else {
        functionUp();
    }


问:
convert each words into one list dataframe
I have a dataframe df:

Suppose a,b,c,d,e,f,g,h,j is a word ,not a single letter.

```<code>cate  word
apple [['a','b'],['c','d','e']]
pen   [['f','g','h'],['j']]
</code>```

I want to get one list in word column.So the expected output should be word_list =[u'a b c d e',u'f g h j']

However,when I use the following code:

```<code>word_list =[]

for line in df['word']:
    for word in line:
        word_list.append(word)
</code>```

So the output is not what I expected.

答:
One efficient solution would be using np.concatenate + str.join:

```<code>df['word'] = df.word.apply(np.concatenate).str.join(' ')
df

    cate       word
0  apple  a b c d e
1    pen    f g h j

df.word.tolist()
['a b c d e', 'f g h j']
</code>```

If df['word'] is not a column of lists (but of strings), you'll need to convert it using ast.literal_eval (the safe eval):

```<code>import ast
df['word'] = df.word.apply(ast.literal_eval)
</code>```

The rest of the solution is the same.

Body:
I have a dataframe df:

Suppose a,b,c,d,e,f,g,h,j is a word ,not a single letter.

cate  word
apple [['a','b'],['c','d','e']]
pen   [['f','g','h'],['j']]

I want to get one list in word column.So the expected output should be word_list =[u'a b c d e',u'f g h j']

However,when I use the following code:

word_list =[]

for line in df['word']:
    for word in line:
        word_list.append(word)

So the output is not what I expected.

Body:
One efficient solution would be using np.concatenate + str.join:

df['word'] = df.word.apply(np.concatenate).str.join(' ')
df

    cate       word
0  apple  a b c d e
1    pen    f g h j

df.word.tolist()
['a b c d e', 'f g h j']

If df['word'] is not a column of lists (but of strings), you'll need to convert it using ast.literal_eval (the safe eval):

import ast
df['word'] = df.word.apply(ast.literal_eval)

The rest of the solution is the same.


问:
react-day-picker: Set date inside navbarElement
I have a component that uses the react-day-picker component. I wan't to have a datepicker where the year and the month can be increased or decreased seperatly.
So I've overwritten the navbarElement (as you can see in the last line). In the arrow function handleNextYearClick the year should be increased by 1. But how can I access and set the date from the parent Component DayPicker. I can only call onNextClick which just increases the month+1.

```<code>export interface IDatePickerNavbarProps {
    date?: Date,
    nextMonth?: Date,
    previousMonth?: Date,
    localeUtils?: any,
    locale?: string,
    onNextClick?: () => {}
}

export interface IDatePickerNavbarState {

}

class DatePickerNavBar extends Component<IDatePickerNavbarProps, IDatePickerNavbarState> {

    constructor(props: IDatePickerNavbarProps) {
        super(props);
    }

    handleNextMonthClick = (event: React.MouseEvent<HTMLElement>) => {
        this.props.onNextClick();
    }

    handleNextYearClick = (event: React.MouseEvent<HTMLElement>) => {
        // How to set the new date => current date + 1 year
        // I am only able to call this.props.onNextClick() but that does
        // +1 only month count
    }

    render() {
        return (
            <div className={Styles.DayPickerSelectBox}>
                <div className={Styles.DayPickerNavbarYear}>
                    year:
                    <span>last</span>  -  <span onClick={this.handleNextYearClick}>next</span>
                </div>
                <div className={Styles.DayPickerNavbarMonth}>
                    month:
                    <span>last</span>  -  <span onClick={this.handleNextMonthClick}>next</span>
                </div>
            </div>
        );
    }
}
</code>```

... this is my code inside the render() method in my main date-picker component...

```<code><DayPicker navbarElement={<DatePickerNavBar />} captionElement={<DatePickerCaption />} />
</code>```

Do not feel disturbed by the typescript notation.

答:
Sadly, the current month it is not exposed to navbarElement:

http://react-day-picker.js.org/api/DayPicker#navbarElement

It has previousMonth tough :)

A month prop will be added in the next release: https://github.com/gpbl/react-day-picker/pull/552

```<code>navbarElement={
  (month) => <DatePickerNavBar currentMonth={month} />
}
</code>```

Body:
I have a component that uses the react-day-picker component. I wan't to have a datepicker where the year and the month can be increased or decreased seperatly.
So I've overwritten the navbarElement (as you can see in the last line). In the arrow function handleNextYearClick the year should be increased by 1. But how can I access and set the date from the parent Component DayPicker. I can only call onNextClick which just increases the month+1.

export interface IDatePickerNavbarProps {
    date?: Date,
    nextMonth?: Date,
    previousMonth?: Date,
    localeUtils?: any,
    locale?: string,
    onNextClick?: () => {}
}

export interface IDatePickerNavbarState {

}

class DatePickerNavBar extends Component<IDatePickerNavbarProps, IDatePickerNavbarState> {

    constructor(props: IDatePickerNavbarProps) {
        super(props);
    }

    handleNextMonthClick = (event: React.MouseEvent<HTMLElement>) => {
        this.props.onNextClick();
    }

    handleNextYearClick = (event: React.MouseEvent<HTMLElement>) => {
        // How to set the new date => current date + 1 year
        // I am only able to call this.props.onNextClick() but that does
        // +1 only month count
    }

    render() {
        return (

                    year:
                    last  -  next

                    month:
                    last  -  next

        );
    }
}

... this is my code inside the render() method in my main date-picker component...

<DayPicker navbarElement={<DatePickerNavBar />} captionElement={<DatePickerCaption />} />

Do not feel disturbed by the typescript notation.

Body:
Sadly, the current month it is not exposed to navbarElement:

http://react-day-picker.js.org/api/DayPicker#navbarElement

It has previousMonth tough :)

A month prop will be added in the next release: https://github.com/gpbl/react-day-picker/pull/552

navbarElement={
  (month) => <DatePickerNavBar currentMonth={month} />
}


问:
Given an array, how to generate all combinations of subset size k?
So given input = [1, 2, 3] and k=2 this would return:

```<code>1 2
1 3
2 1
2 3
3 1
3 2
</code>```

This is the closest to what I am looking for, but not quite: http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/

function subsetsOfSize(a, used, startIndex, currentSize, k) {
  if (currentSize === k) {
    for (var i = 0; i < a.length; i++) {
      if (used[i])
        console.log(a[i]);
    }
    console.log('-');
    return;
  }

  if (startIndex === a.length)
    return;

  used[startIndex] = true;
  subsetsOfSize(a, used, startIndex+1, currentSize+1, k);

  used[startIndex] = false;
  subsetsOfSize(a, used, startIndex+1, currentSize, k);
}

var input = [1,2,3];
subsetsOfSize(input, Array(input.length).fill(false), 0, 0, 2);```

^ Missing results such as 2 1, 3 1, 3 2, etc.

Secondly, I am not sure if I am naming this problem correctly because solutions to "all combinations of subset of size k" do not give the expected answer.

答:
I'm a simple person:

make an array M with size k

fill M with zeroes

loop this:

M[0] += 1

loop through M: *if (M[i] >= size of N) then set M[i]=0 and increase M[i+1] += 1

if M has only different numbers then you've find yourself the indices of a
subset of n

loop ends when the last element of M reaches size of n - minus one a.k.a. when the * condition would cause an error

Body:
So given input = [1, 2, 3] and k=2 this would return:

1 2
1 3
2 1
2 3
3 1
3 2

This is the closest to what I am looking for, but not quite: http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/

function subsetsOfSize(a, used, startIndex, currentSize, k) {
  if (currentSize === k) {
    for (var i = 0; i < a.length; i++) {
      if (used[i])
        console.log(a[i]);
    }
    console.log('-');
    return;
  }

  if (startIndex === a.length)
    return;

  used[startIndex] = true;
  subsetsOfSize(a, used, startIndex+1, currentSize+1, k);

  used[startIndex] = false;
  subsetsOfSize(a, used, startIndex+1, currentSize, k);
}

var input = [1,2,3];
subsetsOfSize(input, Array(input.length).fill(false), 0, 0, 2);

^ Missing results such as 2 1, 3 1, 3 2, etc.

Secondly, I am not sure if I am naming this problem correctly because solutions to "all combinations of subset of size k" do not give the expected answer.


问:
Excel VBA Macro to add a blank row when the value in column A is 1
I wanted to add a row in excel vba when ever the value in column A is 1, here is the code I wrote, but this returns a "subscript out of range error". What am I doing wrong? </p>

```<code>Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
        Col = "A"
        StartRow = 1
        LastRow = 20
        Worksheets("Sheet1").Activate
            For R = StartRow To LastRow
                If Cells(R, Col) = 1 Then
                Cells(R, Col).EntireRow.Insert Shift:=xlDown
                End If
            Next R

Application.ScreenUpdating = True

End Sub
</code>```

答:
Code below tested and works.</p>

```<code>With Worksheets("Sheet1")

    Dim cntr as Long
    For cntr = 20 to 5 Step - 1
          If .Cells(cntr, 1) = 1 Then .cells(cntr,1).EntireRow.Insert Shift:=xlDown
    Next

End With
</code>```

Body:
I wanted to add a row in excel vba when ever the value in column A is 1, here is the code I wrote, but this returns a "subscript out of range error". What am I doing wrong?

Sub InsertRow()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Application.ScreenUpdating = False
        Col = "A"
        StartRow = 1
        LastRow = 20
        Worksheets("Sheet1").Activate
            For R = StartRow To LastRow
                If Cells(R, Col) = 1 Then
                Cells(R, Col).EntireRow.Insert Shift:=xlDown
                End If
            Next R

Application.ScreenUpdating = True

End Sub

Body:
Code below tested and works.

With Worksheets("Sheet1")

    Dim cntr as Long
    For cntr = 20 to 5 Step - 1
          If .Cells(cntr, 1) = 1 Then .cells(cntr,1).EntireRow.Insert Shift:=xlDown
    Next

End With


问:
Scale algorithm not exact?
I'm trying to create this very simple algorithm to size, position and transform (scale) a div. For some reason the algorithm doesn't work exactly. If you take a look at the jsfiddle i made, when you click the div, it scales, but the edges go out of the window. If my math isn't really bad, this should not happen with this algorithm. Why is this happening, and what can i do to fix it?

PS: No console log (no errors)
Any help is very much appreciated! :3

For some reason, i have to put some code in to upload jsfiddle's, so here is the algorithm, the rest is on the jsfiddle. :3

```<code>var me = $("#me");
var zoom = $("#me.zoom");
var win = $(window);

me.css({
    "top": win.height() / 2 - me.height() / 2 + "px",
    "left": win.width() / 2 - me.width() / 2 + "px"
});

me.on("click", function() {
    me.toggleClass("zoom");
    if(me.hasClass("zoom")) {
        me.css({
            "transform": "scale(" + win.width() / me.width() + ")",
            "-webkit-transform": "scale(" + win.width() / me.width() + ")"
        });
    } else {
        me.css({
            "transform": "scale(1)",
            "-webkit-transform": "scale(1)"
        });
    }
});
</code>```

DEMO

答:
As mentioned by @Cory in the comment the 1% padding is what's going outside the window. You might want to use outerHeight() and outerWidth() instead as shown on this update on the Fiddle:

https://jsfiddle.net/k8vkL343/3/

Title: Scale algorithm not exact?

Body:
I'm trying to create this very simple algorithm to size, position and transform (scale) a div. For some reason the algorithm doesn't work exactly. If you take a look at the jsfiddle i made, when you click the div, it scales, but the edges go out of the window. If my math isn't really bad, this should not happen with this algorithm. Why is this happening, and what can i do to fix it?

PS: No console log (no errors)
Any help is very much appreciated! :3

For some reason, i have to put some code in to upload jsfiddle's, so here is the algorithm, the rest is on the jsfiddle. :3

var me = $("#me");
var zoom = $("#me.zoom");
var win = $(window);

me.css({
    "top": win.height() / 2 - me.height() / 2 + "px",
    "left": win.width() / 2 - me.width() / 2 + "px"
});

me.on("click", function() {
    me.toggleClass("zoom");
    if(me.hasClass("zoom")) {
        me.css({
            "transform": "scale(" + win.width() / me.width() + ")",
            "-webkit-transform": "scale(" + win.width() / me.width() + ")"
        });
    } else {
        me.css({
            "transform": "scale(1)",
            "-webkit-transform": "scale(1)"
        });
    }
});

DEMO


问:
Why is Meteor session variables getting cleared on page refresh
I just noticed in my meteor app that the session variables are getting cleared on page refresh. So

How is meteor saving user login details ?

Are they not saved in session ?

How can this issue be managed ?

答:
This is an old question, but since I found myself needing the same thing, here's how I did it. I 'extended' the session to actually store it on the localstorage when setting a value, and loading up the localstorage into the session when the page loads.</p>

```<code>// improving the session package to persist it to the localstorage
Session._set = Session.set;
Session.set = function(key,value) {
    Session._set(key,value);
    localStorage.setItem(key,JSON.stringify(value));
};

// helper function
function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

// loading the localstorate on load
for (var i = 0; i < localStorage.length; i++) {
    var key = localStorage.key(i);
    var value = localStorage.getItem(key);
    Session._set(key,isJSON(value) ? JSON.parse(value) : value);
}
</code>```

Body:
This is an old question, but since I found myself needing the same thing, here's how I did it. I 'extended' the session to actually store it on the localstorage when setting a value, and loading up the localstorage into the session when the page loads.

// improving the session package to persist it to the localstorage
Session._set = Session.set;
Session.set = function(key,value) {
    Session._set(key,value);
    localStorage.setItem(key,JSON.stringify(value));
};

// helper function
function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

// loading the localstorate on load
for (var i = 0; i < localStorage.length; i++) {
    var key = localStorage.key(i);
    var value = localStorage.getItem(key);
    Session._set(key,isJSON(value) ? JSON.parse(value) : value);
}


问:
Catching errors in Angular HttpClient
I have a data service that looks like this:

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
        constructor(
        private httpClient: HttpClient) {
    }
    get(url, params): Promise<Object> {

        return this.sendRequest(this.baseUrl + url, 'get', null, params)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    post(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'post', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    patch(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'patch', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    sendRequest(url, type, body, params = null): Observable<any> {
        return this.httpClient[type](url, { params: params }, body)
    }
}
```

If I get an HTTP error (i.e. 404), I get a nasty console message:
ERROR Error: Uncaught (in promise): [object Object] from core.es5.js
How do I handle it in my case?

答:
Fairly straightforward (in compared to how it was done with the previous API).

Source from (copy and pasted) the Angular official guide

```<code> http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );
</code>```

Title: Catching errors in Angular HttpClient

Body:
I have a data service that looks like this:

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
        constructor(
        private httpClient: HttpClient) {
    }
    get(url, params): Promise<Object> {

        return this.sendRequest(this.baseUrl + url, 'get', null, params)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    post(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'post', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    patch(url, body): Promise<Object> {
        return this.sendRequest(this.baseUrl + url, 'patch', body)
            .map((res) => {
                return res as Object
            })
            .toPromise();
    }
    sendRequest(url, type, body, params = null): Observable<any> {
        return this.httpClient[type](url, { params: params }, body)
    }
}

If I get an HTTP error (i.e. 404), I get a nasty console message:
ERROR Error: Uncaught (in promise): [object Object] from core.es5.js
How do I handle it in my case?

Body:
Fairly straightforward (in compared to how it was done with the previous API).

Source from (copy and pasted) the Angular official guide

 http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');
    }
  );


问:
Missing logic for  creation
I currently take baby steps in JS development and coded the following link adder:

const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')

button.addEventListener('click', function(){
 let input = document.getElementById('text').value

 let createA = document.createElement('a')
 createA.setAttribute('href', input)
 let linkDescr = document.createTextNode(input)
 createA.appendChild(linkDescr)

 listdiv.appendChild(createA)
})```

The order of instruction is this:

Get the value of the text box

Create

Set 's link description

Set href

add 's description to

And then add all of  to the pre-existing Div..

So far so good. But, why is it that when we set href, it gets automatically added to , but we have to take an extra step to add the link's description? Isn't let linkDescr = document.createTextNode(input) supposed to add the description automatically as well? My theory is that the commands are different in that we directly set an attribute of  for one, but create a variable on the other; and something need's to be done first with this variable. Variables don't just do anything by themselves. Please educate me on my logic. Also feel free to propose code changes/suggestions/flaws.
Thank you

答:
There are often multiple ways to do things.

For example, the href can be added like this:

```<code>createA.href = input;
</code>```

So then the description can also be added as a property.

```<code>createA.textContent = input;
</code>```

The API simply gives us the choice. Appending a text node may make more sense in some cases, like when you're relocating an existing node.

In your case, you're creating a new text node. This is an object that is independent of any other part of the DOM tree, so it doesn't do anything until you insert it in the position where you want it, like inside the new a element.

Title: Missing logic for <a> creation

Body:
I currently take baby steps in JS development and coded the following link adder:

const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')

button.addEventListener('click', function(){
 let input = document.getElementById('text').value

 let createA = document.createElement('a')
 createA.setAttribute('href', input)
 let linkDescr = document.createTextNode(input)
 createA.appendChild(linkDescr)

 listdiv.appendChild(createA)
})

The order of instruction is this:

Get the value of the text box

Create

Set 's link description

Set href

add 's description to

And then add all of  to the pre-existing Div..

So far so good. But, why is it that when we set href, it gets automatically added to , but we have to take an extra step to add the link's description? Isn't let linkDescr = document.createTextNode(input) supposed to add the description automatically as well? My theory is that the commands are different in that we directly set an attribute of  for one, but create a variable on the other; and something need's to be done first with this variable. Variables don't just do anything by themselves. Please educate me on my logic. Also feel free to propose code changes/suggestions/flaws.
Thank you

Body:
There are often multiple ways to do things.

For example, the href can be added like this:

createA.href = input;

So then the description can also be added as a property.

createA.textContent = input;

The API simply gives us the choice. Appending a text node may make more sense in some cases, like when you're relocating an existing node.

In your case, you're creating a new text node. This is an object that is independent of any other part of the DOM tree, so it doesn't do anything until you insert it in the position where you want it, like inside the new a element.


问:
Configure Visual Studio to use UNIX line endings
We would like to use Visual Studio 2005 to work on a local copy of an SVN repository. This local copy has been checked out by Mac OS X (and updates and commits will only be made under Mac OS X, so no problem there), and as a consequence the line endings are UNIX-style.

We fear that Visual Studio will introduce Windows-style line endings. Is it possible to force Visual Studio to use UNIX line endings?

答:
Here are some options available for Visual Studio Community 2017

"File > Advanced Save Options" has been removed by microsoft due to "uncommon use".  Whatever that means. https://developercommunity.visualstudio.com/content/problem/8290/file-advanced-save-options-option-is-missed.html
You can add it back by going to "Tools>Customize", then "Commands" tab, select the drop down next to  "Menu Bar" select "File" then "Add Command">File>Advanced Save Options..".  You can then reorder it in the file menu by using "move down".

I don't know if you will have to then set the advanced save options for each and every file, but it might prevent the issue I was having where my Visual Studio kept adding CL RF line endings into my files that were uniformly LF.

But I took it one step further and I added an extension called "Line Endings Unifier" by going to  "Tools>Extensions and Updates>Online" and then searching for "line endings" in the search bar to the right.  I will use this to automatically force all of my scripts to save with uniform line endings of my choice, but you can do more with it.
https://marketplace.visualstudio.com/items?itemName=JakubBielawa.LineEndingsUnifier

strip'em is another solution that does something similar to Line Endings Unifier.  http://www.grebulon.com/software/stripem.php

I am not sure how they differ or the advantages/disadvantages of either.  I'm mainly using Line Endings Unifier just because it was in the Visual Studio Marketplace.  I think I've used all of these methods in the past, but my memory is fuzzy.


问:
question number reordering
I have a list of question in my javascript file. Each question has a question number and question description and options. A question can be added anywhere in the list of questions. So if a question is added into the top of all questions, then i need to change the question numbers of all the below ones. How can achieve this. Can i use javascript for this?</p>

答:
You could do something like this using ordered lists (ol) and jQuery:</p>

```<code><html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type ="text/javascript">
$(function(){

  var n = 2;

  $('button').delegate('click', function(){
    $(this).parents('li').after('<li><p><span>Question'+n+'</span><button>Create new question</button></p></li>');
    n += 1;
  })

})
</script>
</head>
<body>
  <ol>
    <li>
      <p><span>Question 1</span><button>Create new question</button></p>
    </li>
  </ol>
</body>
</html>
</code>```

Title: question number reordering

Body:
You could do something like this using ordered lists (ol) and jQuery:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type ="text/javascript">
$(function(){

  var n = 2;

  $('button').delegate('click', function(){
    $(this).parents('li').after('<li><p><span>Question'+n+'</span><button>Create new question</button></p></li>');
    n += 1;
  })

})
</script>
</head>
<body>
  <ol>
    <li>
      <p><span>Question 1</span><button>Create new question</button></p>
    </li>
  </ol>
</body>
</html>


问:
How do you convert a string to a variable with Ruby?
I am trying to add a link to a blog_post using in this case blog.link

If for example myblog.link = new_contact_path, it would be  "new_contact_path".
In my view I am trying to create a link using
<%= @blogs.each do |blog| %>
    <%= link_to blog.title, blog.link  %>
 <%end %>

I tried using #{blog.link} but that does not work.
I ended up trying something else. I will post it in the answer.

答:
What I did instead was made a helper method.

```<code>def blog_action_link(link)
    case link
    when "person"
      new_person_path
    when "place"
      places_path
    else
    new_contact_path
    end
  end
</code>```

Then I used the helper in my view instead.

Body:
What I did instead was made a helper method.

def blog_action_link(link)
    case link
    when "person"
      new_person_path
    when "place"
      places_path
    else
    new_contact_path
    end
  end

Then I used the helper in my view instead.


问:
Generating HTML report in gulp using lighthouse
I am using gulp for a project and I added lighthouse to the gulp tasks like this:

```<code>gulp.task("lighthouse", function(){
    return launchChromeAndRunLighthouse('http://localhost:3800', flags, perfConfig).then(results => {
      console.log(results);
    });
});
</code>```

And this is my launchChromeAndRunLighthouse() function

```<code>function launchChromeAndRunLighthouse(url, flags = {}, config = null) {
  return chromeLauncher.launch().then(chrome => {
    flags.port = chrome.port;
    return lighthouse(url, flags, config).then(results =>
      chrome.kill().then(() => results));
  });
}
</code>```

It gives me the json output in command line. I can post my json here and get the report.

Is there any way I can generate the HTML report using gulp ?

You are welcome to start a bounty if you think this question will be helpful for future readers.

答:
The answer from @EMC is fine, but it requires multiple steps to generate the HTML from that point. However, you can use it like this (written in TypeScript, should be very similar in JavaScript):

```<code>const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));
</code>```

Then call it:

```<code>await write(results, 'html', 'report.html');
</code>```

UPDATE

There have been some changes to the lighthouse repo. I now enable programmatic HTML reports as follows:

```<code>const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));
const reportGenerator = await import(root('./node_modules/lighthouse/lighthouse-core/report/report-generator'));

// ...lighthouse setup

const raw = await lighthouse(url, flags, config);
await write(reportGenerator.generateReportHtml(raw.lhr), 'html', root('report.html'));
</code>```

I know it's hacky, but it solves the problem :).

Body:
I am using gulp for a project and I added lighthouse to the gulp tasks like this:

gulp.task("lighthouse", function(){
    return launchChromeAndRunLighthouse('http://localhost:3800', flags, perfConfig).then(results => {
      console.log(results);
    });
});

And this is my launchChromeAndRunLighthouse() function

function launchChromeAndRunLighthouse(url, flags = {}, config = null) {
  return chromeLauncher.launch().then(chrome => {
    flags.port = chrome.port;
    return lighthouse(url, flags, config).then(results =>
      chrome.kill().then(() => results));
  });
}

It gives me the json output in command line. I can post my json here and get the report.

Is there any way I can generate the HTML report using gulp ?

You are welcome to start a bounty if you think this question will be helpful for future readers.

Body:
The answer from @EMC is fine, but it requires multiple steps to generate the HTML from that point. However, you can use it like this (written in TypeScript, should be very similar in JavaScript):

const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));

Then call it:

await write(results, 'html', 'report.html');

UPDATE

There have been some changes to the lighthouse repo. I now enable programmatic HTML reports as follows:

const { write } = await import(root('./node_modules/lighthouse/lighthouse-cli/printer'));
const reportGenerator = await import(root('./node_modules/lighthouse/lighthouse-core/report/report-generator'));

// ...lighthouse setup

const raw = await lighthouse(url, flags, config);
await write(reportGenerator.generateReportHtml(raw.lhr), 'html', root('report.html'));

I know it's hacky, but it solves the problem :).


问:
Send a constant from server to client in meteorjs
Scenario: You want to put the build id in the footer of a meteor app. The client will need a reference to process.env.BUILD_ID from the server.

Common answer: Save it in a collection. On meteor start, save the current build id to a collection and load that on the client.

Problem with the common answer: What if you have multiple containers running? Say for instance you're using kube to update the version. You have version abc running, and then kube starts pushing up def. In the process of starting each def container, it sets the current version in the db to def. Yet the abc containers are still running. If you hit one of those containers, it will report def as the build id. Even though thats wrong. Additionally, what if the kube update fails, and you decide to cancel the push to the new version and keep the old containers running. Until the next container restart, youll be serving the abc content but telling the user its version def.

What would be the proper way to store a constant and match it on the client without lying about its true value?

答:
Meteor methods are the way to get data from the server (as opposed to the using publications to get from the database).  I recommend using ValidatedMethod for extra modularity and nicer validation.

Define the following method in your project and make sure it is imported to the server on server startup:

```<code>import { Meteor } from 'meteor/meteor';
import { ValidatedMethod } from 'meteor/mdg:validated-method';

const getAppVersion = new ValidatedMethod({
  name: 'getAppVersion',
  validate: null,
  run({}) {
    return process.env.BUILD_ID;
  },
});

export default getAppVersion;
</code>```

Then in the frontend code:

```<code>import getAppVersion from '/imports/api/methods/getAppVersion.js';

getAppVersion.call({}, (err, res) => {
  if (res) setFooterVersion(res);
});
</code>```

Body:
Meteor methods are the way to get data from the server (as opposed to the using publications to get from the database).  I recommend using ValidatedMethod for extra modularity and nicer validation.

Define the following method in your project and make sure it is imported to the server on server startup:

import { Meteor } from 'meteor/meteor';
import { ValidatedMethod } from 'meteor/mdg:validated-method';

const getAppVersion = new ValidatedMethod({
  name: 'getAppVersion',
  validate: null,
  run({}) {
    return process.env.BUILD_ID;
  },
});

export default getAppVersion;

Then in the frontend code:

import getAppVersion from '/imports/api/methods/getAppVersion.js';

getAppVersion.call({}, (err, res) => {
  if (res) setFooterVersion(res);
});


问:
PHP/Javascript - Changing button image and making database calls onClick()?
I have a button on a page. The button is an image sprite, and it choose ADD in green. I want the user to be able to click this button, and then do a few things:

1) That button makes a call to add an item to my MySQL database, without reloading the page. (I think this needs AJAX.)

2) The button background image sprite changes such that it now says REMOVE in red.

I don't understand how to do this. I'd greatly appreciate a basic walk through on how to do it.

答:
It will be easier to make the "AJAX" call if you use a JavaScript framework, such as jQuery.

You'll tell jQuery to issue a POST request (with data attached) to a PHP script on the server. The PHP script you write will add the item to the database. When the request is complete, jQuery will run a "callback" for you. In your callback, you can change the styling of the button.

Please see jQuery.post

That's the general overview and should get you started. Please comment on this answer if you'd like more details or examples on a particular part of the process.