问:
How are the outputs of precision_recall_fscore_support in sklearn ordered?
I am doing a multi-class classification problem with the target labels of 0, 1, and 2 (dtype=int). I built my model and want to evaluate how good it is using precision, recall, and f-score. Here's what I did:

```<code>precision,recall,fscore,support = precision_recall_fscore_support(y_train,y_train_pred)
print('recall:  {0}'.format(recall))
</code>```

And here's my output:

```<code>recall:  [ 0.99991709  0.56711409  0.12327412]
</code>```

I'm almost certain that the ordering is 0, 1, 2 from left to right. But I don't know for sure. Would someone please (1) confirm the ordering for me and (2) tell me how I can check the ordering? There must be some parameters where my label ordering is stored? What if my labels were "dog","bird","fish"? Would it have been alphabetical?

答:
precision,recall,fscore,support = precision_recall_fscore_support(y_train,y_train_pred,labels=[0,1,2])

Gives you 0, 1, 2 from left to right. Just like

precision,recall,fscore,support = precision_recall_fscore_support(y_train,y_train_pred,labels=['dog','bird','fish'])

Gives you 'dog','bird','fish' from left to right.

Body:
I am doing a multi-class classification problem with the target labels of 0, 1, and 2 (dtype=int). I built my model and want to evaluate how good it is using precision, recall, and f-score. Here's what I did:

precision,recall,fscore,support = precision_recall_fscore_support(y_train,y_train_pred)
print('recall:  {0}'.format(recall))

And here's my output:

recall:  [ 0.99991709  0.56711409  0.12327412]

I'm almost certain that the ordering is 0, 1, 2 from left to right. But I don't know for sure. Would someone please (1) confirm the ordering for me and (2) tell me how I can check the ordering? There must be some parameters where my label ordering is stored? What if my labels were "dog","bird","fish"? Would it have been alphabetical?


来源: stackexchange

问:
Retrieve the minimum value of a column from the max value of another column
I have a hive table t1 that looks like this:

```
ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12
```

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

```
ID    Score1    score2
1     5         12
2     3         14
3     6         10
```

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

答:
Try:  </p>

```<code>SELECT Z.ID, Z.SCORE1, MIN(SCORE2) AS SCORE2
FROM
(SELECT A.ID, A.SCORE FROM
YOUR_TABLE A
INNER JOIN
(SELECT ID, MAX(SCORE1) FROM YOUR_TABLE GROUP BY ID) B
ON A.ID = B.ID AND A.SCORE1 = B.SCORE1
GROUP BY A.ID, A.SCORE
HAVING COUNT(*)>1
) Z
INNER JOIN YOUR_TABLE C
ON Z.ID = C.ID AND Z.SCORE1 = C.SCORE1
GROUP BY Z.ID, Z.SCORE1;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a hive table t1 that looks like this:

ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

ID    Score1    score2
1     5         12
2     3         14
3     6         10

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

Body:
Try:

SELECT Z.ID, Z.SCORE1, MIN(SCORE2) AS SCORE2
FROM
(SELECT A.ID, A.SCORE FROM
YOUR_TABLE A
INNER JOIN
(SELECT ID, MAX(SCORE1) FROM YOUR_TABLE GROUP BY ID) B
ON A.ID = B.ID AND A.SCORE1 = B.SCORE1
GROUP BY A.ID, A.SCORE
HAVING COUNT(*)>1
) Z
INNER JOIN YOUR_TABLE C
ON Z.ID = C.ID AND Z.SCORE1 = C.SCORE1
GROUP BY Z.ID, Z.SCORE1;


问:
How can I stop elements overlapping using JavaScript and the Raphael JavaScript library
I’m generating multiple, random sized, circular elements using the Raphael JavaScript library but because it’s random a lot of the circular elements being generate overlap or cover each other. What I wanted to know, is there any way with JavaScript to tell if one element is in already in particular position so to avoid the overlapping?  Essentially, I want to create random elements on a canvas, of a random size that don’t overlap or cover each other.

There's a couple of test files I created here to give you an idea of what I'm doing. The first one generates random objects and the second link sets them to a grid to stop the overlapping.

http://files.nicklowman.co.uk/movies/raphael_test_01/

http://files.nicklowman.co.uk/movies/raphael_test_03/

答:
Your examples aren't working for me, so I cannot visualize your exact scenario.

Before you "drop" an element on the canvas, you could query the positions of your other elements and do some calculations to check if the new element will overlap.

A very simple example of this concept using circle elements might look like this:

```<code>function overlap(circ1, circ2) {
    var attrs = ["cx", "cy", "r"];
    var c1 = circ1.attr(attrs);
    var c2 = circ2.attr(attrs);
    var dist = Math.sqrt(Math.pow(c1.cx - c2.cx ,2) + Math.pow(c1.cy - c2.cy, 2));
    return (dist < (c1.r + c2.r));
}
var next_drop = paper.circle(x, y, r);
for (var i in circles) {
    if (overlap(next_drop, circles[i])) {
        // do something
    }
}
</code>```

Of course calculating just where you're going to place a circle after you've determined it overlaps with others is a little more complicated.

ContentLicense: CC BY-SA 2.5

Body:
Your examples aren't working for me, so I cannot visualize your exact scenario.

Before you "drop" an element on the canvas, you could query the positions of your other elements and do some calculations to check if the new element will overlap.

A very simple example of this concept using circle elements might look like this:

function overlap(circ1, circ2) {
    var attrs = ["cx", "cy", "r"];
    var c1 = circ1.attr(attrs);
    var c2 = circ2.attr(attrs);
    var dist = Math.sqrt(Math.pow(c1.cx - c2.cx ,2) + Math.pow(c1.cy - c2.cy, 2));
    return (dist < (c1.r + c2.r));
}
var next_drop = paper.circle(x, y, r);
for (var i in circles) {
    if (overlap(next_drop, circles[i])) {
        // do something
    }
}

Of course calculating just where you're going to place a circle after you've determined it overlaps with others is a little more complicated.


问:
maxIndex of an MVector
Data.Vector includes a function maxIndex with type maxIndex :: (Ord a) => Vector a -> Int that returns the index of the maximum value in that Vector. I'm working with mutable Vectors, however, and MVector doesn't have maxIndex defined for it.

What's the best way of getting the data I want out of the MVector I have? My code currently is:

```<code>import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

type MaxIndex = Int

step :: forall s. MV.MVector s Int -> MaxIndex -> ST s ()
step vec i = do
    n <- MV.unsafeRead vec i
    MV.write vec i 0
    let l      = MV.length vec
        (k, x) = n `divMod` l
    mapM_ (\j -> MV.modify vec (+k) j) [0..l-1]  -- side note, this is just
                                                 -- fmap (+k) vec, but MVector is not
                                                 -- a functor. Is there a better way?
    mapM_ (\j -> MV.modify vec (+1) (j `mod` l)) [i+1..i+x]
</code>```

where i is the index I'm looking to derive inside step. I'm doing this because the actions here need to eventually be wrapped inside an until and repeated until a predicate is satisfied, and freezing and thawing every cycle sounds ludicrously expensive.

答:
I see lots of talk about unsafe freezing which seems suspect since you plan to mutate this memory later, thus violating the assurance you are implicitly giving when calling unsafeFreeze.

My suggestion is to just write an imperative-style maxIndex function.  The below is typed but not tested:

```<code>import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

maxIndex :: (Ord a, MV.Unbox a) => MV.MVector s a -> ST s (Maybe Int)
maxIndex mv | len == 0  = pure Nothing
            | otherwise = Just <$> go 0 0
 where
 len = MV.length mv
 go n i | i >=len   = pure n
        | otherwise = do
     nVal <- MV.unsafeRead mv n
     iVal <- MV.unsafeRead mv i
     if nVal < iVal then go i (i+1)
                    else go n (i+1)
</code>```

Title: maxIndex of an MVector

Body:
Data.Vector includes a function maxIndex with type maxIndex :: (Ord a) => Vector a -> Int that returns the index of the maximum value in that Vector. I'm working with mutable Vectors, however, and MVector doesn't have maxIndex defined for it.

What's the best way of getting the data I want out of the MVector I have? My code currently is:

import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

type MaxIndex = Int

step :: forall s. MV.MVector s Int -> MaxIndex -> ST s ()
step vec i = do
    n <- MV.unsafeRead vec i
    MV.write vec i 0
    let l      = MV.length vec
        (k, x) = n `divMod` l
    mapM_ (\j -> MV.modify vec (+k) j) [0..l-1]  -- side note, this is just
                                                 -- fmap (+k) vec, but MVector is not
                                                 -- a functor. Is there a better way?
    mapM_ (\j -> MV.modify vec (+1) (j `mod` l)) [i+1..i+x]

where i is the index I'm looking to derive inside step. I'm doing this because the actions here need to eventually be wrapped inside an until and repeated until a predicate is satisfied, and freezing and thawing every cycle sounds ludicrously expensive.

Body:
I see lots of talk about unsafe freezing which seems suspect since you plan to mutate this memory later, thus violating the assurance you are implicitly giving when calling unsafeFreeze.

My suggestion is to just write an imperative-style maxIndex function.  The below is typed but not tested:

import qualified Data.Vector.Unboxed.Mutable as MV
import           Control.Monad.ST
import           Control.Monad               (mapM_)

maxIndex :: (Ord a, MV.Unbox a) => MV.MVector s a -> ST s (Maybe Int)
maxIndex mv | len == 0  = pure Nothing
            | otherwise = Just <$> go 0 0
 where
 len = MV.length mv
 go n i | i >=len   = pure n
        | otherwise = do
     nVal <- MV.unsafeRead mv n
     iVal <- MV.unsafeRead mv i
     if nVal < iVal then go i (i+1)
                    else go n (i+1)


问:
Error 400 from twilio rest API while testing with Postman
I was trying to check post method of twilio rest API in postman.Despite of sending the body part raw JSON format it was showing some error 400 code as response. But whenever I was attaching those body details in postman as form format it was working fine. So I am not able to understand why it was not taking that JSON format, if JSON format also working then how should I write that body part for twilio rest API .</p>

答:
Twilio developer evangelist here.

When you make a request with a body, such as a POST request, you need to send the body as form encoded parameters, that is as application/x-www-form-urlencoded.

The Twilio API does not accept JSON bodies.


问:
BeautifulSoup doesn't find all spans or children
I am trying to access the sequence on this webpage:

https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta

The sequence is stored under the div class="seq gbff". Each line is stored under

```<code><span class='ff_line' id='gi_344258949_1"> *line 1 of sequence* </span>
</code>```

When I try to search for the spans containing the sequence, beautiful soup returns None. Same problem when I try to look at the children or content of the div above the spans.

Here is the code:

```<code>import requests
import re
from bs4 import BeautifulSoup
# Create a variable with the url
url = 'https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta'

# Use requests to get the contents
r = requests.get(url)

# Get the text of the contents
html_content = r.text

# Convert the html content into a beautiful soup object
soup = BeautifulSoup(html_content, 'html.parser')

div = soup.find_all('div', attrs={'class', 'seq gbff'})
for each in div.children:
    print(each)
soup.find_all('span', aatrs={'class', 'ff_line'})
</code>```

Neither method works and I'd greatly appreciate any help :D

答:
This page uses JavaScript to load data

With DevTools in Chrome/Firefox I found this url and there are all

https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?id=344258949&db=protein&report=fasta&extrafeat=0&fmt_mask=0&retmode=html&withmarkup=on&tool=portal&log$=seqview&maxdownloadsize=1000000

Now hard part. You have to find this url in HTML because different pages will use different arguments in url. Or you have to compare few urls and find schema so you could generate this url manually.

EDIT: if in url you change retmode=html to retmode=xml then you get it as XML. If you use retmode=text then you get it as text without HTML tags. retmode=json doesn't works.

Body:
I am trying to access the sequence on this webpage:

https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta

The sequence is stored under the div class="seq gbff". Each line is stored under

 *line 1 of sequence*

When I try to search for the spans containing the sequence, beautiful soup returns None. Same problem when I try to look at the children or content of the div above the spans.

Here is the code:

import requests
import re
from bs4 import BeautifulSoup
# Create a variable with the url
url = 'https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta'

# Use requests to get the contents
r = requests.get(url)

# Get the text of the contents
html_content = r.text

# Convert the html content into a beautiful soup object
soup = BeautifulSoup(html_content, 'html.parser')

div = soup.find_all('div', attrs={'class', 'seq gbff'})
for each in div.children:
    print(each)
soup.find_all('span', aatrs={'class', 'ff_line'})

Neither method works and I'd greatly appreciate any help :D

Body:
This page uses JavaScript to load data

With DevTools in Chrome/Firefox I found this url and there are all <span>

https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?id=344258949&db=protein&report=fasta&extrafeat=0&fmt_mask=0&retmode=html&withmarkup=on&tool=portal&log$=seqview&maxdownloadsize=1000000

Now hard part. You have to find this url in HTML because different pages will use different arguments in url. Or you have to compare few urls and find schema so you could generate this url manually.

EDIT: if in url you change retmode=html to retmode=xml then you get it as XML. If you use retmode=text then you get it as text without HTML tags. retmode=json doesn't works.


问:
How to find number of multiple line block comments using grep?
I'm trying to find number of block comments that span across multiple lines in /usr/include/stdio.h

I managed to do it using 2 grep commands:

```<code>egrep '/\*' /usr/include/stdio.h | egrep -cv '\*/'
</code>```

Can this be done in a more elegant way, using only one regex expression?

答:
The easiest way is with negative lookahead, if PCRE is supported in your version of grep (e.g. GNU grep).

```<code>grep -P '/\*(?!.*\*/)' filename
</code>```

Doing negative lookahead in general is difficult with just extended RE. The following comes close, but doesn't work if the single-line comment ends with **/.

```<code>grep -E '/\*[^*]*((\*($|[^/]))?[^*]*)*$'
</code>```

DEMO

Body:
I'm trying to find number of block comments that span across multiple lines in /usr/include/stdio.h

I managed to do it using 2 grep commands:

egrep '/\*' /usr/include/stdio.h | egrep -cv '\*/'

Can this be done in a more elegant way, using only one regex expression?

Body:
The easiest way is with negative lookahead, if PCRE is supported in your version of grep (e.g. GNU grep).

grep -P '/\*(?!.*\*/)' filename

Doing negative lookahead in general is difficult with just extended RE. The following comes close, but doesn't work if the single-line comment ends with **/.

grep -E '/\*[^*]*((\*($|[^/]))?[^*]*)*$'

DEMO


问:
How to get a full node path with LINQ to SQL?
I have a basic hierarchy defined in an SQL table:

```<code>Id    ParentId  Name
----------------------
1     Null      Root
2     1         Node1
3     2         Node2
</code>```

Is there a good LINQ-ish way to get the full path of a node? For example, i want to pass the Id of Node2 and get the full path like Root/Node1/Node2.

Thank you in advance :)

答:
I can't think of a way to do this in a single query for an arbitrary length path.  I'd probably resort to using a loop, building the path as you go, until you reach a node with no parent.</p>

```<code> var node = db.Nodes.Where( n => n.Name == "Node2" ).SingleOrDefault();
 string path = string.Empty;
 while (node != null)
 {
     path = string.Format( "/{0}{1}", node.Name, path );
     node = db.Nodes.Where( n => n.ParentId == node.Id ).SingleOrDefault();
 }
</code>```

OwnerDisplayName: ciscocert

Body:
I have a basic hierarchy defined in an SQL table:

Id    ParentId  Name
----------------------
1     Null      Root
2     1         Node1
3     2         Node2

Is there a good LINQ-ish way to get the full path of a node? For example, i want to pass the Id of Node2 and get the full path like Root/Node1/Node2.

Thank you in advance :)

Body:
I can't think of a way to do this in a single query for an arbitrary length path.  I'd probably resort to using a loop, building the path as you go, until you reach a node with no parent.

 var node = db.Nodes.Where( n => n.Name == "Node2" ).SingleOrDefault();
 string path = string.Empty;
 while (node != null)
 {
     path = string.Format( "/{0}{1}", node.Name, path );
     node = db.Nodes.Where( n => n.ParentId == node.Id ).SingleOrDefault();
 }

OwnerDisplayName: tvanfosson


问:
Using php's swiftmailer with gmail
I'm writing a simple script in which a gmail account is used to send an email to itself.

I altered the script from SwiftMailer's reference, but I'm not getting any results. What's wrong?

Edit: after further debugging I've found that the statement

```<code>$result = $mailer->send($message);
</code>```

causes the code to fail (the echo below it doesn't print).

Why is this? Just cause the message isn't sent the program crashes? :/

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<?php
    require_once '/var/www/swift/lib/swift_required.php';
    echo 'Mail sent <br />';

/*  //create the transport
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587);
      ->setUsername('softrain.evaluaciones@gmail.com')
      ->setPassword('softrain1234')
    ;
*/

    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587)
      ->setUsername('softrain.evaluaciones@gmail.com')
      ->setPassword('password')
    ;

    echo 'line 40 <br />';
    $mailer = Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance('Wonderful Subject')
      ->setFrom(array('softrain.evaluaciones@gmail.com' => 'Evaluaciones'))
      ->setTo(array('softrain.evaluaciones@gmail.com'=> 'A name'))
      ->setBody('Test Message Body')
    ;
    echo 'line 52 <br />';

    $result = $mailer->send($message);
    echo $result;
    echo 'line 58 <br />';

?>
</body>
</html>
</code>```

The test form:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <title>Test Mail Script</title>
    </head>
    <body>
        <form action="scriptmail.php" method="post">
            <input type="submit"/>
            </table>
        </form>
  </body>
</html>
</code>```

答:
I also came here after hours of research. I finally found the true answer. I wanted to send email FROM google mail servers and not from my host with smtp authentication.

You can trace an email with its full headers inside of gmail, follow this guide.

https://support.google.com/mail/answer/29436?hl=en

@fullybaked had the right answer for authenticating your email via smtp but you would still be sending via your host.

```<code>$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername($this->username)
->setPassword($this->password);

$this->mailer = Swift_Mailer::newInstance($transporter);
</code>```

@ducin was correct with the different ports and encryption types.

```<code>$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
</code>```

OR more modern and more secure, use;

```<code>$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
</code>```

If you want to send directly from a gmail server you need to set the authorization mode. Plain is default.

```<code>$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
->setAuthMode('login')
->setUsername('username@gmail.com')
->setPassword('password');

$mailer = Swift_Mailer::newInstance($transporter);
</code>```

@gene is also correct, you do have to authenticate your app, so follow his instruction.

Further to prevent your email from landing in the spam folder, you will also have to add dns text records with DKIM (domain keys)

https://support.google.com/a/answer/174124?hl=en

SPF records

https://support.google.com/a/answer/33786?hl=en

and DMARC

https://support.google.com/a/answer/2466580?hl=en

Title: Using php's swiftmailer with gmail

Body:
I'm writing a simple script in which a gmail account is used to send an email to itself.

I altered the script from SwiftMailer's reference, but I'm not getting any results. What's wrong?

Edit: after further debugging I've found that the statement

$result = $mailer->send($message);

causes the code to fail (the echo below it doesn't print).

Why is this? Just cause the message isn't sent the program crashes? :/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<?php
    require_once '/var/www/swift/lib/swift_required.php';
    echo 'Mail sent
';

/*  //create the transport
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587);
      ->setUsername('softrain.evaluaciones@gmail.com')
      ->setPassword('softrain1234')
    ;
*/

    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587)
      ->setUsername('softrain.evaluaciones@gmail.com')
      ->setPassword('password')
    ;

    echo 'line 40
';
    $mailer = Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance('Wonderful Subject')
      ->setFrom(array('softrain.evaluaciones@gmail.com' => 'Evaluaciones'))
      ->setTo(array('softrain.evaluaciones@gmail.com'=> 'A name'))
      ->setBody('Test Message Body')
    ;
    echo 'line 52
';

    $result = $mailer->send($message);
    echo $result;
    echo 'line 58
';

?>

The test form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <title>Test Mail Script</title>

        <form action="scriptmail.php" method="post">
            <input type="submit"/>

        </form>

Body:
I also came here after hours of research. I finally found the true answer. I wanted to send email FROM google mail servers and not from my host with smtp authentication.

You can trace an email with its full headers inside of gmail, follow this guide.

https://support.google.com/mail/answer/29436?hl=en

@fullybaked had the right answer for authenticating your email via smtp but you would still be sending via your host.

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername($this->username)
->setPassword($this->password);

$this->mailer = Swift_Mailer::newInstance($transporter);

@ducin was correct with the different ports and encryption types.

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')

OR more modern and more secure, use;

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')

If you want to send directly from a gmail server you need to set the authorization mode. Plain is default.

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
->setAuthMode('login')
->setUsername('username@gmail.com')
->setPassword('password');

$mailer = Swift_Mailer::newInstance($transporter);

@gene is also correct, you do have to authenticate your app, so follow his instruction.

Further to prevent your email from landing in the spam folder, you will also have to add dns text records with DKIM (domain keys)

https://support.google.com/a/answer/174124?hl=en

SPF records

https://support.google.com/a/answer/33786?hl=en

and DMARC

https://support.google.com/a/answer/2466580?hl=en


问:
Swift 4 - Xcode 9 beta 4 - NSKernAttributeName vs NSAttributedStringKey
iOS Deployment Target: iOS 9.3,
Base SDK: Latest iOS (iOS 11.0),
Xcode 9 Beta 4,
Swift 4

The following code builds and runs in Swift 3, Xcode 8:

```<code>    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSKernAttributeName] as? CGFloat ?? 0
</code>```

However, the Swift 4 migrator converts it to this:

```<code>    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSAttributedStringKey.kern] as? CGFloat ?? 0
</code>```

Xcode 9 now complains:

```<code>Cannot subscript a value of type '[String : Any]' with an index of type 'NSAttributedStringKey'
</code>```

According to the inspector, 'NSAttributedStringKey' is only available in iOS 11. (Keep in mind that I am targeting iOS 9).

If I replace 'NSAttributedStringKey.kern' with 'NSKernAttributeName', the error remains.

Command-clicking on 'NSKernAttributeName' tells me that its availability is iOS 6. However, the inspector also claims its type is 'NSAttributedStringKey', which is only available in iOS 11. I do not know if this is merely an artefact of the API presentation, or a stuff-up, or something I'm missing.

Question: how can I use NSKernAttributeName (or its modernised version) with backward compatibility to iOS 9, with Swift 4?

Thank you for any help.

答:
Swift 4

If you don't want to ignore the warning and cast regardless, you can copy them into a new dictionary cleanly.

```<code>var attributes: [NSAttributedStringKey: Any] = [:]
textField.defaultTextAttributes.forEach{
    attributes[NSAttributedStringKey(rawValue: $0.key)] = $0.value
}
</code>```

Body:
iOS Deployment Target: iOS 9.3,
Base SDK: Latest iOS (iOS 11.0),
Xcode 9 Beta 4,
Swift 4

The following code builds and runs in Swift 3, Xcode 8:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSKernAttributeName] as? CGFloat ?? 0

However, the Swift 4 migrator converts it to this:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSAttributedStringKey.kern] as? CGFloat ?? 0

Xcode 9 now complains:

Cannot subscript a value of type '[String : Any]' with an index of type 'NSAttributedStringKey'

According to the inspector, 'NSAttributedStringKey' is only available in iOS 11. (Keep in mind that I am targeting iOS 9).

If I replace 'NSAttributedStringKey.kern' with 'NSKernAttributeName', the error remains.

Command-clicking on 'NSKernAttributeName' tells me that its availability is iOS 6. However, the inspector also claims its type is 'NSAttributedStringKey', which is only available in iOS 11. I do not know if this is merely an artefact of the API presentation, or a stuff-up, or something I'm missing.

Question: how can I use NSKernAttributeName (or its modernised version) with backward compatibility to iOS 9, with Swift 4?

Thank you for any help.

Body:
Swift 4

If you don't want to ignore the warning and cast regardless, you can copy them into a new dictionary cleanly.

var attributes: [NSAttributedStringKey: Any] = [:]
textField.defaultTextAttributes.forEach{
    attributes[NSAttributedStringKey(rawValue: $0.key)] = $0.value
}


问:
Lot of repetition in React component
I have a rather large React component that manages the display of a detail for a job on my site.

There are a few things that I would like to do smarter

The component has a few options for opening Dialogs. For each dialog I have a separate Open and Close function. For example  handleImageGridShow and handleImageGridClose. Is there any way to be more concise around this?

I have many presentational components (e.g. ViewJobDetails) that shows details about the job. My issue is that I have to pass them down into each Component as a prop and I'm passing the same props over and over again

As I'm loading my data from firebase I often have to do similar checks to see if the data exists before I render the component (e.g.this.state.selectedImageGrid && <ImageGridDialog />). Is there any more clever way of going about this?

import React, { Component } from 'react';

```<code>import { withStyles } from 'material-ui/styles';
import ViewJobAttachment from "../../components/jobs/viewJobAttachment";
import ViewJobDetails from "../../components/jobs/viewJob/viewJobDetails";
import ViewJobActions from "../../components/jobs/viewJob/viewJobActions";
import ViewCompanyDetails from "../../components/jobs/viewJob/viewCompanyDetails";
import ViewClientsDetails from "../../components/jobs/viewJob/viewClientsDetails";
import ViewProductsDetails from "../../components/jobs/viewJob/viewProductsDetails";
import ViewAttachmentDetails from "../../components/jobs/viewJob/viewAttachmentDetails";
import ViewEventLogDetails from "../../components/jobs/viewJob/viewEventLogDetails";
import ViewSummaryDetails from "../../components/jobs/viewJob/viewSummary";
import {FirebaseList} from "../../utils/firebase/firebaseList";
import SimpleSnackbar from "../../components/shared/snackbar";
import {calculateTotalPerProduct} from "../../utils/jobsService";
import BasicDialog from "../../components/shared/dialog";
import ImageGrid from "../../components/shared/imageGrid";
import Spinner from "../../components/shared/spinner";
import ViewPinnedImageDialog from "../../components/jobs/viewEntry/viewPinnedImage";
import {
  Redirect
} from 'react-router-dom';

const styles = theme => ({
  wrapper: {
    marginBottom: theme.spacing.unit*2
  },
  rightElement: {
    float: 'right'
  }
});

const ImageGridDialog = (props) => {
  return (
    <BasicDialog open={!!props.selectedImageGrid}
                 handleRequestClose={props.handleRequestClose}
                 fullScreen={props.fullScreen}
                 title={props.title}
    >
      <ImageGrid selectedUploads={props.selectedImageGrid}
                     handleClickOpen={props.handleClickOpen}/>
    </BasicDialog>
  )
};

class ViewJob extends Component {
  constructor() {
    super();

    this.state = {
      currentJob: null,
      entries: [],
      promiseResolved: false,
      attachmentDialogOpen: false,
      openAttachment: null,
      selectedImageGrid: false,
      selectedPinnedImage: false,
      showSnackbar: false,
      snackbarMsg: '',
      markedImageLoaded: false,
      loading: true,
      redirect: false
    };

    this.firebase = new FirebaseList('jobs');

    this.handleJobStatusChange = this.handleJobStatusChange.bind(this);
    this.handleImageGridShow = this.handleImageGridShow.bind(this);
    this.handleImageGridClose = this.handleImageGridClose.bind(this);
    this.handlePinnedImageClose = this.handlePinnedImageClose.bind(this);
    this.handlePinnedImageShow = this.handlePinnedImageShow.bind(this);
    this.handleMarkedImageLoaded = this.handleMarkedImageLoaded.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
    this.pushLiveToClient = this.pushLiveToClient.bind(this);
  }

  componentDidMount() {
    this.firebase.db().ref(`jobs/${this.props.id}`).on('value', (snap) => {
      const job = {
        id: snap.key,
        ...snap.val()
      };
      this.setState({
        currentJob: job,
        loading: false
      })
    });

    const previousEntries = this.state.entries;

    this.firebase.db().ref(`entries/${this.props.id}`).on('child_added', snap => {
      previousEntries.push({
        id: snap.key,
        ...snap.val()
      });

      this.setState({
        entries: previousEntries
      })
    });
  }

  handleRemove() {
    this.firebase.remove(this.props.id)
      .then(() => {
        this.setState({redirect: true})
      })
  };

  pushLiveToClient() {
    const updatedJob = {
      ...this.state.currentJob,
      'lastPushedToClient': Date.now()
    };
    this.firebase.update(this.state.currentJob.id, updatedJob)
      .then(() => this.handleSnackbarShow("Job pushed live to client"))
  }

  handleJobStatusChange() {
    const newState = !this.state.currentJob.completed;
    const updatedJob = {
      ...this.state.currentJob,
      'completed': newState
    };
    this.firebase.update(this.state.currentJob.id, updatedJob)
  }

  handleSnackbarShow = (msg) => {
    this.setState({
      showSnackbar: true,
      snackbarMsg: msg
    });
  };

  handleSnackbarClose= (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    this.setState({ showSnackbar: false });
  };

  handleAttachmentDialogClose =() => {
    this.setState({attachmentDialogOpen: false})
  };

  handleClickOpen = (file) => {
    this.setState({
      attachmentDialogOpen: true,
      openAttachment: file
    });
  };

  handleImageGridShow(imageGrid) {
    this.setState({selectedImageGrid: imageGrid})
  }

  handleImageGridClose() {
    this.setState({selectedImageGrid: false})
  }

  handlePinnedImageShow(pinnedImage) {
    this.setState({selectedPinnedImage: pinnedImage})
  }

  handlePinnedImageClose() {
    this.setState({selectedPinnedImage: false})
  }

  handleMarkedImageLoaded() {
    this.setState({markedImageLoaded: true})
  }

  render() {
    const {classes} = this.props;
    let {_, costPerItem} = calculateTotalPerProduct(this.state.entries);
    if (this.state.redirect) {
      return <Redirect to='/jobs' push/>
    } else {
      if (this.state.loading) {
        return <Spinner/>
      } else {
        return (
          <div className={styles.wrapper}>
            {this.state.currentJob &&
            <div>
              <ViewJobActions currentJob={this.state.currentJob}
                              handleJobStatusChange={this.handleJobStatusChange}
                              pushLiveToClient={this.pushLiveToClient}
              />
              <ViewJobDetails currentJob={this.state.currentJob}/>
              <ViewCompanyDetails currentJob={this.state.currentJob}/>
              <ViewClientsDetails currentJob={this.state.currentJob}/>
              <ViewProductsDetails currentJob={this.state.currentJob}/>
              {this.state.currentJob.selectedUploads && this.state.currentJob.selectedUploads.length > 0
                ? <ViewAttachmentDetails currentJob={this.state.currentJob} handleClickOpen={this.handleClickOpen}/>
                : null}
              <ViewEventLogDetails jobId={this.state.currentJob.jobId}
                                   jobKey={this.state.currentJob.id}
                                   entries={this.state.entries}
                                   handlePinnedImageShow={this.handlePinnedImageShow}
                                   handleImageGridShow={this.handleImageGridShow}/>
              <ViewSummaryDetails stats={costPerItem}/>
              <ViewJobAttachment open={this.state.attachmentDialogOpen}
                                 handleRequestClose={this.handleAttachmentDialogClose}
                                 attachment={this.state.openAttachment}
              />
              {this.state.selectedImageGrid &&
              <ImageGridDialog selectedImageGrid={this.state.selectedImageGrid}
                               handleRequestClose={this.handleImageGridClose}
                               handleClickOpen={this.handleClickOpen}
                               title="Pictures for job"
                               fullScreen={false}/>}
              {this.state.selectedPinnedImage &&
              <ViewPinnedImageDialog attachment={this.state.selectedPinnedImage}
                                     open={!!this.state.selectedPinnedImage}
                                     markedImageLoaded={this.state.markedImageLoaded}
                                     handleMarkedImageLoaded={this.handleMarkedImageLoaded}
                                     handleRequestClose={this.handlePinnedImageClose}
                                     otherMarkedEntries={this.state.entries}
              />
              }
              <SimpleSnackbar showSnackbar={this.state.showSnackbar}
                              handleSnackbarClose={this.handleSnackbarClose}
                              snackbarMsg={this.state.snackbarMsg}/>

            </div>}
          </div>
        );
      }
    }
  }
}

export default withStyles(styles)(ViewJob);
</code>```

答:
You can define a regular component method and bind it in handler like this onSomething={this.handler.bind(this, index)} assuming you have some distinguishable thing in the index var

function should look like this

```<code>handler(index) {
  ...
}
</code>```

Title: Lot of repetition in React component

Body:
I have a rather large React component that manages the display of a detail for a job on my site.

There are a few things that I would like to do smarter

The component has a few options for opening Dialogs. For each dialog I have a separate Open and Close function. For example  handleImageGridShow and handleImageGridClose. Is there any way to be more concise around this?

I have many presentational components (e.g. ViewJobDetails) that shows details about the job. My issue is that I have to pass them down into each Component as a prop and I'm passing the same props over and over again

As I'm loading my data from firebase I often have to do similar checks to see if the data exists before I render the component (e.g.this.state.selectedImageGrid && <ImageGridDialog />). Is there any more clever way of going about this?

import React, { Component } from 'react';

import { withStyles } from 'material-ui/styles';
import ViewJobAttachment from "../../components/jobs/viewJobAttachment";
import ViewJobDetails from "../../components/jobs/viewJob/viewJobDetails";
import ViewJobActions from "../../components/jobs/viewJob/viewJobActions";
import ViewCompanyDetails from "../../components/jobs/viewJob/viewCompanyDetails";
import ViewClientsDetails from "../../components/jobs/viewJob/viewClientsDetails";
import ViewProductsDetails from "../../components/jobs/viewJob/viewProductsDetails";
import ViewAttachmentDetails from "../../components/jobs/viewJob/viewAttachmentDetails";
import ViewEventLogDetails from "../../components/jobs/viewJob/viewEventLogDetails";
import ViewSummaryDetails from "../../components/jobs/viewJob/viewSummary";
import {FirebaseList} from "../../utils/firebase/firebaseList";
import SimpleSnackbar from "../../components/shared/snackbar";
import {calculateTotalPerProduct} from "../../utils/jobsService";
import BasicDialog from "../../components/shared/dialog";
import ImageGrid from "../../components/shared/imageGrid";
import Spinner from "../../components/shared/spinner";
import ViewPinnedImageDialog from "../../components/jobs/viewEntry/viewPinnedImage";
import {
  Redirect
} from 'react-router-dom';

const styles = theme => ({
  wrapper: {
    marginBottom: theme.spacing.unit*2
  },
  rightElement: {
    float: 'right'
  }
});

const ImageGridDialog = (props) => {
  return (
    <BasicDialog open={!!props.selectedImageGrid}
                 handleRequestClose={props.handleRequestClose}
                 fullScreen={props.fullScreen}
                 title={props.title}
    >
      <ImageGrid selectedUploads={props.selectedImageGrid}
                     handleClickOpen={props.handleClickOpen}/>
    </BasicDialog>
  )
};

class ViewJob extends Component {
  constructor() {
    super();

    this.state = {
      currentJob: null,
      entries: [],
      promiseResolved: false,
      attachmentDialogOpen: false,
      openAttachment: null,
      selectedImageGrid: false,
      selectedPinnedImage: false,
      showSnackbar: false,
      snackbarMsg: '',
      markedImageLoaded: false,
      loading: true,
      redirect: false
    };

    this.firebase = new FirebaseList('jobs');

    this.handleJobStatusChange = this.handleJobStatusChange.bind(this);
    this.handleImageGridShow = this.handleImageGridShow.bind(this);
    this.handleImageGridClose = this.handleImageGridClose.bind(this);
    this.handlePinnedImageClose = this.handlePinnedImageClose.bind(this);
    this.handlePinnedImageShow = this.handlePinnedImageShow.bind(this);
    this.handleMarkedImageLoaded = this.handleMarkedImageLoaded.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
    this.pushLiveToClient = this.pushLiveToClient.bind(this);
  }

  componentDidMount() {
    this.firebase.db().ref(`jobs/${this.props.id}`).on('value', (snap) => {
      const job = {
        id: snap.key,
        ...snap.val()
      };
      this.setState({
        currentJob: job,
        loading: false
      })
    });

    const previousEntries = this.state.entries;

    this.firebase.db().ref(`entries/${this.props.id}`).on('child_added', snap => {
      previousEntries.push({
        id: snap.key,
        ...snap.val()
      });

      this.setState({
        entries: previousEntries
      })
    });
  }

  handleRemove() {
    this.firebase.remove(this.props.id)
      .then(() => {
        this.setState({redirect: true})
      })
  };

  pushLiveToClient() {
    const updatedJob = {
      ...this.state.currentJob,
      'lastPushedToClient': Date.now()
    };
    this.firebase.update(this.state.currentJob.id, updatedJob)
      .then(() => this.handleSnackbarShow("Job pushed live to client"))
  }

  handleJobStatusChange() {
    const newState = !this.state.currentJob.completed;
    const updatedJob = {
      ...this.state.currentJob,
      'completed': newState
    };
    this.firebase.update(this.state.currentJob.id, updatedJob)
  }

  handleSnackbarShow = (msg) => {
    this.setState({
      showSnackbar: true,
      snackbarMsg: msg
    });
  };

  handleSnackbarClose= (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    this.setState({ showSnackbar: false });
  };

  handleAttachmentDialogClose =() => {
    this.setState({attachmentDialogOpen: false})
  };

  handleClickOpen = (file) => {
    this.setState({
      attachmentDialogOpen: true,
      openAttachment: file
    });
  };

  handleImageGridShow(imageGrid) {
    this.setState({selectedImageGrid: imageGrid})
  }

  handleImageGridClose() {
    this.setState({selectedImageGrid: false})
  }

  handlePinnedImageShow(pinnedImage) {
    this.setState({selectedPinnedImage: pinnedImage})
  }

  handlePinnedImageClose() {
    this.setState({selectedPinnedImage: false})
  }

  handleMarkedImageLoaded() {
    this.setState({markedImageLoaded: true})
  }

  render() {
    const {classes} = this.props;
    let {_, costPerItem} = calculateTotalPerProduct(this.state.entries);
    if (this.state.redirect) {
      return <Redirect to='/jobs' push/>
    } else {
      if (this.state.loading) {
        return <Spinner/>
      } else {
        return (

            {this.state.currentJob &&

              <ViewJobActions currentJob={this.state.currentJob}
                              handleJobStatusChange={this.handleJobStatusChange}
                              pushLiveToClient={this.pushLiveToClient}
              />
              <ViewJobDetails currentJob={this.state.currentJob}/>
              <ViewCompanyDetails currentJob={this.state.currentJob}/>
              <ViewClientsDetails currentJob={this.state.currentJob}/>
              <ViewProductsDetails currentJob={this.state.currentJob}/>
              {this.state.currentJob.selectedUploads && this.state.currentJob.selectedUploads.length > 0
                ? <ViewAttachmentDetails currentJob={this.state.currentJob} handleClickOpen={this.handleClickOpen}/>
                : null}
              <ViewEventLogDetails jobId={this.state.currentJob.jobId}
                                   jobKey={this.state.currentJob.id}
                                   entries={this.state.entries}
                                   handlePinnedImageShow={this.handlePinnedImageShow}
                                   handleImageGridShow={this.handleImageGridShow}/>
              <ViewSummaryDetails stats={costPerItem}/>
              <ViewJobAttachment open={this.state.attachmentDialogOpen}
                                 handleRequestClose={this.handleAttachmentDialogClose}
                                 attachment={this.state.openAttachment}
              />
              {this.state.selectedImageGrid &&
              <ImageGridDialog selectedImageGrid={this.state.selectedImageGrid}
                               handleRequestClose={this.handleImageGridClose}
                               handleClickOpen={this.handleClickOpen}
                               title="Pictures for job"
                               fullScreen={false}/>}
              {this.state.selectedPinnedImage &&
              <ViewPinnedImageDialog attachment={this.state.selectedPinnedImage}
                                     open={!!this.state.selectedPinnedImage}
                                     markedImageLoaded={this.state.markedImageLoaded}
                                     handleMarkedImageLoaded={this.handleMarkedImageLoaded}
                                     handleRequestClose={this.handlePinnedImageClose}
                                     otherMarkedEntries={this.state.entries}
              />
              }
              <SimpleSnackbar showSnackbar={this.state.showSnackbar}
                              handleSnackbarClose={this.handleSnackbarClose}
                              snackbarMsg={this.state.snackbarMsg}/>

}

        );
      }
    }
  }
}

export default withStyles(styles)(ViewJob);

Body:
You can define a regular component method and bind it in handler like this onSomething={this.handler.bind(this, index)} assuming you have some distinguishable thing in the index var

function should look like this

handler(index) {
  ...
}


问:
Error: Cannot find module 'cors'
I keep getting this error message below:
I tried to find other stackoverflow post and articles but couldn't really sovle it.
do any of you guys know what the problem is it?</p>

```<code>`kimeric@pal-nat186-87-17  ~/Desktop/cs390/Assignment9/backEnd  master ✚ ● ?  node server9.js
module.js:472
    throw err;
    ^

Error: Cannot find module 'cors'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/kimeric/Desktop/cs390/Assignment9/backEnd/server9.js:11:12)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)`
</code>```

答:
Run npm install cors --save from the command line in the main project directory to install it and add it to your package.json

It is possible that the cors module was separated from the main express package a long time ago, and the code you are using was written before that. (Or never was a part of it, to begin with)

Title: Error: Cannot find module 'cors'

Body:
I keep getting this error message below:
I tried to find other stackoverflow post and articles but couldn't really sovle it.
do any of you guys know what the problem is it?

`kimeric@pal-nat186-87-17  ~/Desktop/cs390/Assignment9/backEnd  master ✚ ● ?  node server9.js
module.js:472
    throw err;
    ^

Error: Cannot find module 'cors'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/kimeric/Desktop/cs390/Assignment9/backEnd/server9.js:11:12)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)`


问:
Code not checking values in list?
This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have:

```<code>def find_val(val, seq):
    for ele in seq:
        if val == ele:
            return True
    return False

def get_input(possible_vals, day_or_time_string):
    if day_or_time_string == "day":
        answer = input("What day would you like your appointment? ")
    else:
        answer = input("What time would you like your appointment? ")
    answer = answer.strip()
    valid_entry = find_val(answer, possible_vals)
    if valid_entry == True:
        count = 0
        while False:
            second_answer = input("Invalid entry. Please enter a valid day: ")
            count = count + 1
            if count == 3:
                print("This is getting silly - still not a valid entry")
            if second_answer in possible_vals:
                return second_answer
    else:
        return answer

day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)
</code>```

This is the type of output I should be getting:

```<code>What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday
</code>```

However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list:

```<code>What day would you like your appointment? akw
The function returned akw
</code>```

What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?

答:
First

```<code>valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
</code>```

can be simplified to

```<code>if answer in possible_vals:
</code>```

(your find_val function is totally unnecessary)

Then your problem is that

```<code>while False:
    ...
</code>```

simply never executes... Did you mean while True? If so You'll need to somehow break out this (now) infinite loop using a break statement for example.

And finally as A.G. suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise?

Title: Code not checking values in list?

Body:
This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have:

def find_val(val, seq):
    for ele in seq:
        if val == ele:
            return True
    return False

def get_input(possible_vals, day_or_time_string):
    if day_or_time_string == "day":
        answer = input("What day would you like your appointment? ")
    else:
        answer = input("What time would you like your appointment? ")
    answer = answer.strip()
    valid_entry = find_val(answer, possible_vals)
    if valid_entry == True:
        count = 0
        while False:
            second_answer = input("Invalid entry. Please enter a valid day: ")
            count = count + 1
            if count == 3:
                print("This is getting silly - still not a valid entry")
            if second_answer in possible_vals:
                return second_answer
    else:
        return answer

day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)

This is the type of output I should be getting:

What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday

However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list:

What day would you like your appointment? akw
The function returned akw

What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?

Body:
First

valid_entry = find_val(answer, possible_vals)
if valid_entry == True:

can be simplified to

if answer in possible_vals:

(your find_val function is totally unnecessary)

Then your problem is that

while False:
    ...

simply never executes... Did you mean while True? If so You'll need to somehow break out this (now) infinite loop using a break statement for example.

And finally as A.G. suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise?


问:
Angular4 send sms using twilio
Hello guys I am trying to send sms from client side using twilio
 here is what I am trying

```<code>url = 'https://api.twilio.com/2010-04-01/Accounts/AC5b593d9bfeedd9e/Messages.json';
    axios.post(url,{
      "To" : "+9134324738",
      "From" : "+14698",
      "Body" : "Fgrgajshdkajsdhrom axios"
    },{headers: { Authorization: 'Basic sdfsdfsdf=',
    'Content-Type': 'application/x-www-form-url' }
  })
</code>```

but I am getting 400 bad request response

here is what I am getting in response

```<code>{
    "code": 21603,
    "message": "A 'From' phone number is required.",
    "more_info": "https://www.twilio.com/docs/errors/21603",
    "status": 400
}
</code>```

Please suggest some

答:
Twilio developer evangelist here.

We do not recommend that you make requests to the Twilio API directly from your front end JavaScript application. To do so, you would need to store or retrieve your account SID and auth token in the client side somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.

Instead, we recommend you perform the API request on the server side and use your Angular app to make a request to your server to trigger the request.

Title: Angular4 send sms using twilio

Body:
Hello guys I am trying to send sms from client side using twilio
 here is what I am trying

url = 'https://api.twilio.com/2010-04-01/Accounts/AC5b593d9bfeedd9e/Messages.json';
    axios.post(url,{
      "To" : "+9134324738",
      "From" : "+14698",
      "Body" : "Fgrgajshdkajsdhrom axios"
    },{headers: { Authorization: 'Basic sdfsdfsdf=',
    'Content-Type': 'application/x-www-form-url' }
  })

but I am getting 400 bad request response

here is what I am getting in response

{
    "code": 21603,
    "message": "A 'From' phone number is required.",
    "more_info": "https://www.twilio.com/docs/errors/21603",
    "status": 400
}

Please suggest some


问:
How to correctly pass "this" into function?
I struggle passing this into my function as demonstrated below:

```<code>console.log('geolocation is ' + this.isGeolocating);

let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status, self = this) {
    console.log('geolocation is ' + self.isGeolocating);
    if (status === 'OK') {
        if (results[0]) {
            console.log(results[0]);
            self.geolocated = 'success';
        } else {
            // No results found
            self.geolocated = 'error';
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
        self.geolocated = 'error';
    }
});

this.isGeolocating = false;
</code>```

this is properly accessible before and after the function, but how can I pass it through? self in my case is undefined as well.

答:
Try this:</p>

```<code>let myBeautifulThis = this;
let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status) {
  console.log('geolocation is ' + myBeautifulThis.isGeolocating);
});
</code>```

Body:
I struggle passing this into my function as demonstrated below:

console.log('geolocation is ' + this.isGeolocating);

let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status, self = this) {
    console.log('geolocation is ' + self.isGeolocating);
    if (status === 'OK') {
        if (results[0]) {
            console.log(results[0]);
            self.geolocated = 'success';
        } else {
            // No results found
            self.geolocated = 'error';
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
        self.geolocated = 'error';
    }
});

this.isGeolocating = false;

this is properly accessible before and after the function, but how can I pass it through? self in my case is undefined as well.

Body:
Try this:

let myBeautifulThis = this;
let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status) {
  console.log('geolocation is ' + myBeautifulThis.isGeolocating);
});


问:
Cache Hotlinked Image To Minimize Server Load
Before anyone rips me a new one...I HAVE PERMISSION to hotlink images from an external site. It works all good, however I don't like that everytime i refresh the page it pulls the images again. My server is running PHP, is there a way to cache the images once, then display them via some local code. I'm really just looking for a way to speed up the page, and not waste anyones bandwidth. Thanks in advance.</p>

答:
I was looking for an answer to this myself and didn't find anything that fit my needs perfectly. TimThumb came close (you'll have to Google it; I'm a newbie and can thus only post one hyperlink), but it was a little overkill (it has all kinds of image manipulation stuff built-in) and couldn't handle some of the image types I was interested in using (specifically *.ico files). So I wrote my own quick-n-dirty PHP script that should handle any image type and is only concerned with caching the images alone and passing them through without any modifications.

I'm a bit concerned my script may have glaring security flaws or could be more efficient. Also, it's not very smart the way it caches. It never bothers to check later to see if the image has been updated, and it never bothers to clean up its own cache. If anyone has suggestions for improvements to my code, I'm open to feedback.

Here's the script: Warm linker - RefactorMyCode.com


问:
Error when deploying Tizen App - Failed to get a device information
I am having a problem with deploying a Tizen app onto my Samsung smart tv. For some time it was working really good, but since updating tizen studio to 2.0 and the tv-extension to 4.0 it isn't working anymore. I always get a 'Failed to get a device information' error.

[2017.11.22 00:54:29][ERROR] ProfileInfo.java(426) - Failed to get a device information from '10.0.0.40:26101' (model: UJ5500, platform: Tizen, version: unknown, profile: unknown                      `-¶)
  java.lang.Exception: Failed to get a device's profile version
      at org.tizen.common.core.application.ProfileInfo.getProfileInfo(ProfileInfo.java:413)
      at org.tizen.common.util.LaunchUtil.checkProfile(LaunchUtil.java:158)
      at org.tizen.web.zimlaunch.deployer.ZimLaunchDelegate.preLaunchCheck(ZimLaunchDelegate.java:141)
      at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:840)
      at org.eclipse.debug.internal.core.LaunchConfiguration.launch(LaunchConfiguration.java:739)
      at org.eclipse.debug.internal.ui.DebugUIPlugin.buildAndLaunch(DebugUIPlugin.java:1039)
      at org.eclipse.debug.internal.ui.DebugUIPlugin$8.run(DebugUIPlugin.java:1256)
      at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

The required Tizen version is set to 2.3 and my model is a UJ5500 (2015).

On the dev website of samsung they say that this kind of error is only occuring on 2015 models and it can be ignored, but I can't deploy it. I also thought about downgrading tizen studio to 1.3 and the tv-extension to 3.0 as i had before, sadly I can't install the web-app dev of the package manager. For those of you who might think that this is caused by the certificate, I already created a public and partner one with my UDID of my Samsung device. And by the way it is also not working on an emulator (same error).

答: Sebastian, thank you for your help, but I already figured out what was wrong. In the tutorials and guides Samsung pointed to the Samsung certificates, but they are only working for some devices. I always got a PackageManager error in the cli. So I used a Tizen certificate. Then the app installed successfully on the TV.</p>


问:
Is it possible in TFS NOT to trigger a CI build when the content of an active (i.e. NOT cloaked) directory changes?
My scenario is as follows:

Developers check-in SQL changes to directory ClientDB

A dedicated build wakes up, extracts the metadata from the checked-in files, processes it and checks the result in into a sibling directory ClientMetadata

(Developers are not allowed to check-in under ClientMetadata)

The annoying side effect, is that because the dedicated build is a CI build it wakes up twice:

Once for the changes in ClientDB, which makes it update ClientMetadata

Second time, because of its own changes in the ClientMetadata - after all, this directory appears as an Active directory in the Source Settings section of the build:

Ideally, I would like the ClientMetadata directory to be available in the workspace, but I do not want changes there to trigger the build.

Is it possible?

答:
If the 2nd checkin from the build is done with a checkin comment that has the text ***NO_CI*** at the end, the continuous integration trigger will be suppressed.

It's a hack, but it's how gated checkins work OOTB with TFS.

What does ***NO_CI*** stand for?


问:
ES6 exporting/importing in index file
I am currently using ES6 in an React app via webpack/babel.
I am using index files to gather all components of a module and export them. Unfortunately, that looks like this:

```<code>import Comp1_ from './Comp1.jsx';
import Comp2_ from './Comp2.jsx';
import Comp3_ from './Comp3.jsx';

export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;
</code>```

So I can nicely import it from other places like this:

```<code>import { Comp1, Comp2, Comp3 } from './components';
</code>```

Obviously that isn't a very nice solution, so I was wondering, if there was any other way. I don't seem to able to export the imported component directly.

答:
default export

```<code>// Default export (recommended)
export {default} from './module'

// Default export with alias
export {default as d1} from './module'
</code>```

all export

```<code>// In >ES7, it could be
export * from './module'

// In >ES7, with alias
export * as d1 from './module'
</code>```

function name export

```<code>// export by function names
export { funcName1, funcName2, …} from './module'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './module'
</code>```

destructured object export

```<code>// export destructured object
export const { myVar, myFunction } = myObjectWithEverything

// export destructured object, with renaming
export const { v1: myVar, f1: myFunction } = myBigObject
</code>```

with array

```<code>// it works with array as well
export const [ funcName1, funcName2 ] = myBigArray
</code>```

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

ContentLicense: CC BY-SA 4.0

Title: ES6 exporting/importing in index file

Body:
I am currently using ES6 in an React app via webpack/babel.
I am using index files to gather all components of a module and export them. Unfortunately, that looks like this:

import Comp1_ from './Comp1.jsx';
import Comp2_ from './Comp2.jsx';
import Comp3_ from './Comp3.jsx';

export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;

So I can nicely import it from other places like this:

import { Comp1, Comp2, Comp3 } from './components';

Obviously that isn't a very nice solution, so I was wondering, if there was any other way. I don't seem to able to export the imported component directly.

Body:
default export

// Default export (recommended)
export {default} from './module'

// Default export with alias
export {default as d1} from './module'

all export

// In >ES7, it could be
export * from './module'

// In >ES7, with alias
export * as d1 from './module'

function name export

// export by function names
export { funcName1, funcName2, …} from './module'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './module'

destructured object export

// export destructured object
export const { myVar, myFunction } = myObjectWithEverything

// export destructured object, with renaming
export const { v1: myVar, f1: myFunction } = myBigObject

with array

// it works with array as well
export const [ funcName1, funcName2 ] = myBigArray

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export


问:
Complex query combining
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

```<code>+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+
</code>```

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

```<code>+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+
</code>```

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id
</code>```

And also the query:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
</code>```

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

答:
You can try something like

```<code>SELECT t1.user_id,
    t1.consumption_overall as consumption overall,
    t2.consumption_november as consumption november
FROM (
    SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
    FROM fillings
    GROUP BY user_id
) as t1, (
    SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
    FROM fillings
    WHERE 'date'
    BETWEEN '2017-11-01' AND '2017-11-31'
    GROUP BY user_id
) as t2
WHERE t1.user_id = t2.user_id
</code>```

It will take the results of you two queries and put them in the same table.

Title: Complex query combining

Body:
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id

And also the query:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

Body:
You can try something like

SELECT t1.user_id,
    t1.consumption_overall as consumption overall,
    t2.consumption_november as consumption november
FROM (
    SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_overall
    FROM fillings
    GROUP BY user_id
) as t1, (
    SELECT user_id, SUM(kilometers) / SUM(liters) as consumption_november
    FROM fillings
    WHERE 'date'
    BETWEEN '2017-11-01' AND '2017-11-31'
    GROUP BY user_id
) as t2
WHERE t1.user_id = t2.user_id

It will take the results of you two queries and put them in the same table.


问:
Git Push Error "cannot lock ref" "reference already exists"
The full error is:

remote: error: cannot lock ref 'refs/heads/fix/add_overlay': reference already exists

I'm using SourceTree, but that should not matter I don't think. I keep trying to push and I keep getting this error, how can I resolve it?

答:
TL;DR: try removing their branch fix, i.e., their refs/heads/fix, which I suspect is in the way.  (Be sure they don't care if you remove it!)

The error message is very odd.  If the reference refs/heads/fix/add_overlay exists, that's not a problem!  Git should be able to lock it, and if it can't, the reason it can't is not "because it exists".

I suspect that this may be a misleading error message: it may be that the reference refs/heads/fix—not refs/heads/fix/add_overlay—exists, so it's impossible to create a directory refs/heads/fix/ in which to hold the sub-reference refs/heads/fix/add_overlay because the existing reference refs/heads/fix is in the way.

You can tell whether this is the case by examining the set of references that exist (by using git ls-remote, or after a git fetch -p, by looking at your own set of remote-tracking names that are based on their branch names).  And, if it is the case, you should convince them—whoever they are—to rename or remove their branch fix so that you can have them create a directory named fix/ containing branch names like fix/add_overlay.


问:
Firebase maximum projects and apps
How many applications can I create in one project from a single account and how many projects I can create in Firebase for Cloud Messaging?</p>

答:
As of now (8 Dec 2017) I got a maximum of 5 projects

I got this message when I was creating new project and only had my 2 existing projects.

You're 3 projects away from the project limit.

I occasionally create a new Firebase project to test and learn its new features such as Firestore and Cloud Functions and then delete the project. Last month I tried creating a new project to learn Firestore and only had 2 existing projects, I've never got any project-limit message like this before. I think Firebase team just changed the project limit to 5 recently

Update 8 March 2018

My account reached the limit. I tried request another 10 projects to Firebase team and it took 1 business day to approve (sometimes it might take longer). I have to say that Firebase team is not mean. They are willing to help if they can.

I request a project limit increase and say I want another 10 projects because I'm starting my new startup(MVP) and want to keep the cost low at first. After the business generate money I will pay for Paid Services. Besides I told them how easy I can reach the limit as I have to create new projects to test Firebase features, like Firestore and Cloud Messaging before using the features in production. And finally they gave me another 10 projects :)

If you want to start a business with Firebase and have already reached the limit then Firebase team is going to help and give you project limit increase as long as you're not a spammer.

Title: Firebase maximum projects and apps


问:
How to get better at UIKit/Core Animation with no design experience?
I've read through Aaron Hillegass's iPhone Programming: The Big Nerd Ranch Guide and I feel I have a solid understanding on the fundamental design patterns/APIs of UIKit. After searching on both here and on Google, it seems that to take the 'next step,' I should practice by writing apps. But: I have no design experience, and I feel that unless I'm doing some work that involves custom controls or any sort of other custom elements, re-writing apps with the same standard controls isn't helping me get better at iPhone dev. So, here are my options:

1) Learn design

2) Find a designer who has some app ideas (note that this is just in my spare time, and I'm not yet looking to make it my full time job, so finding a designer who would just give me free controls/designs would probably be hard)

3) ???

Anybody have other ideas?

TL;DR: I want to get better at iPhone dev by writing more apps for practice, but I'm not good at visual design.

EDIT: To be clear, I am not trying to make these apps with the intention of releasing for the App Store. I am writing these apps to practice iPhone dev and to get better at it.

答:
I'd personally start looking at what other apps are creating as far as custom controls go.  Trying to reverse engineer, so to speak, what they are doing will give you insight into what some of the lesser known APIs like CALayer can do for you as far effects, animations, etc.  Getting comfortable outside the standard set of controls and APIs will give you the skill set you need so when someone comes to you with a design idea, you can easily translate that into reality.  For the next version of my own app I did just this, really digging into cool things you can do.

This blog does just this.  His posts come at an angle from how to do custom things that both Apple and third party devs do:

iDevRecipes

Also, here's a reference to really get a sense of some of the cool Core Animation APIs.  This guy includes videos demonstrating the effects, as well as Xcode projects:

Subtle Effects With CALayer

Complex Interpolation With CAShapeLayer

3D Objects in Objective-C with CATransformLayer

Combining those with blocks based animations introduced in iOS 4.x can produce some real eye popping and easy to program creations.


问:
C++ error: no match for call to '(std::list<int>) (int&)'
I have a piece of script to count the highest possible sum of list elements while retaining the pattern: higher-lower-higher-lower-higher etc.

```<code>#include <algorithm>
#include <stdio.h>
#include <list>

using namespace std;

int main() {
    int n=0;
    bool g = false;
    int d = 1000000;
    list<int> a(d,0);
    int b;

    for (int x=0; x<n; x++) {  //load the list elements
        scanf("%d", &b);
        a.push_back(b);
    }

    for (int i=0; a(n) == a(n+1); i++) {
        a.remove(n+1);  //this is to remove any (consecutive) duplicates
    }

    if (a(n) > a(n+1)) {
        g = false;
    } else {
        g = true;
    }

while (n+1 < d) {
    if (g) {
        if (!(a(n) < a(n+1))) {
            a.remove(n+1);
            continue;
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    } else {
        if (!(a(n) > a(n+1))) {
            a.remove(n+1);
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    }
}
long long sum = 0 ;
for (int i = 0 ; i < a.count(); i++) {
   sum += a(i);
}

printf("%lld ", sum);

return 0;
}
</code>```

However, at compilation attempt it throws no match for call to '(std::list<int>) (int&)' everywhere where I am trying to compare list elements.

What am I doing wrong?

答:
a(n) means calling the function call operator std::list::operator()(int&) with n as its argument. The error no match for call to '(std::list<int>) (int&)' is because std::list doesn't have a call operator.

A list does not support random access unlike a vector which have operator[] for random access. Using a vector, the random access element n of vector a becomes a[n].

To traverse through a list, you use list iterators. Use std::list::begin to get the iterator to first element. To traverse, use assignment, increment (++) and decrement (--) operators. To access the value of the element, use dereference operator (*).

Body:
I have a piece of script to count the highest possible sum of list elements while retaining the pattern: higher-lower-higher-lower-higher etc.

#include <algorithm>
#include <stdio.h>
#include <list>

using namespace std;

int main() {
    int n=0;
    bool g = false;
    int d = 1000000;
    list<int> a(d,0);
    int b;

    for (int x=0; x<n; x++) {  //load the list elements
        scanf("%d", &b);
        a.push_back(b);
    }

    for (int i=0; a(n) == a(n+1); i++) {
        a.remove(n+1);  //this is to remove any (consecutive) duplicates
    }

    if (a(n) > a(n+1)) {
        g = false;
    } else {
        g = true;
    }

while (n+1 < d) {
    if (g) {
        if (!(a(n)  a(n+1))) {
            a.remove(n+1);
        } else {
            n = n+1;
            g = !g;
            continue;
        }
    }
}
long long sum = 0 ;
for (int i = 0 ; i < a.count(); i++) {
   sum += a(i);
}

printf("%lld ", sum);

return 0;
}

However, at compilation attempt it throws no match for call to '(std::list<int>) (int&)' everywhere where I am trying to compare list elements.

What am I doing wrong?


问:
How to go from Try to Catch in specific condition in Try
I have a specific condition in try want it to be in catch if happened

```<code>string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}
</code>```

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

答:
I think if is all you need.

```<code>if(x==null) {
    //do what you need to do
} else if (x.Value < 3) {
    //do something else
} (...)
</code>```

Body:
I have a specific condition in try want it to be in catch if happened

string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

Body:
I think if is all you need.

if(x==null) {
    //do what you need to do
} else if (x.Value < 3) {
    //do something else
} (...)


问:
Knockout foreach with a where clause
This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..

```<code>Where ItemStatus.Active is 0 in an enum in c# ( backend )

@foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{
  <div class="someclass”>
  <span class="label">Name:</span>
  <span class="value">@employee.Name</span>
  </div>
}
</code>```

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

Thank you

答:
Any JavaScript expression can be used in Knockout bindings.

So you could use the filter function (ES6):

```<code><!-- ko foreach: Employees.filter(employee => employee.Status == 0) -->
...
<!-- /ko -->
</code>```

Or any other method of filtering:

```<code><!-- ko foreach: ko.utils.arrayFilter(Employees.filter, function(employee) { return employee.Status == 0; }) -->
...
<!-- /ko -->
</code>```

Title: Knockout foreach with a where clause

Body:
This sytax is in razor that I am converting to knockoutJS.. any help much appreciated..

Where ItemStatus.Active is 0 in an enum in c# ( backend )

@foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{

  Name:
  @employee.Name

}

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

Thank you

Body:
Any JavaScript expression can be used in Knockout bindings.

So you could use the filter function (ES6):

<!-- ko foreach: Employees.filter(employee => employee.Status == 0) -->
...
<!-- /ko -->

Or any other method of filtering:

<!-- ko foreach: ko.utils.arrayFilter(Employees.filter, function(employee) { return employee.Status == 0; }) -->
...
<!-- /ko -->


问:
How to print all instances of a substring in a string
So, I currently have a file, and I'm trying to have a command that searches through all of the lines in that text that has what I'm looking for.

Here's what I have so far:

```<code>public class finder
{
   public static void main(String args[]) throws FileNotFoundException
   {
       Scanner console = new Scanner (System.in);

       String search = console.nextLine();
       Scanner s = new Scanner(new File("C:\\Users\\xxxxx\\Desktop\\test.txt"));

       while (s.hasNextLine())
       {
         String temp = s.nextLine();
         if (temp.contains(search))
         {
            System.out.println(temp);
         }
       }
   } //Main

} //Finder
</code>```

The text looks like this

```<code>Bob has a cat
Bob has a dog
Chris has a cat
</code>```

If I search "cat", it will print out "Bob has a cat", and "Chris has a cat".
If I search "Bob", it will print out "Bob has a cat", and "Bob has a dog".

So I don't know what to put in the while loop. I know you have to do something with the indexOf string command, but I'm not sure how to implement it.

答:
If you only want to match the whole line just call contains on a given String line to filter the ones you desire:

```<code>import java.util.Arrays;
import java.util.List;

public class TestSearch {
    public static void main(String[] args) {
        String query = "chris";
        List<String> dataList = Arrays.asList("Bob has a cat", "Bob has a dog", "Chris has a cat");
        dataList.stream().filter(str -> str.toLowerCase().contains(query)).forEach(System.out::println);
    }
}
</code>```

which will print:

```<code>Chris has a cat
</code>```

If you want something more elaborate, like getting all the indexes of the matches of your query in a given line, then you should try with Pattern and Matcher (pretty good tutorial here):

```<code>import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {
    public static void main(String[] args) {
        String query = "bob";
        System.out.println("Searching for \"" + query + "\"...");
        Pattern patt = Pattern.compile(query);
        Arrays.asList(
                "Bob has a cat bob",
                "Bob has a dog",
                "Chris has a cat",
            "Cat has a chris that is a bob")
        .forEach(line -> {
            System.out.println("Checking in line = \"" + line + "\"");
            Matcher matcher = patt.matcher(line.toLowerCase());
            while (matcher.find()) {
                System.out.println("found! index = " + matcher.start());
            }
        });
    }
}
</code>```

which will print:

```<code>Searching for "bob"...
Checking in line = "Bob has a cat bob"
found! index = 0
found! index = 14
Checking in line = "Bob has a dog"
found! index = 0
Checking in line = "Chris has a cat"
Checking in line = "Cat has a chris that is a bob"
found! index = 26
</code>```

Plug in your file reading with java.nio and happy coding!

Cheers!

Body:
So, I currently have a file, and I'm trying to have a command that searches through all of the lines in that text that has what I'm looking for.

Here's what I have so far:

public class finder
{
   public static void main(String args[]) throws FileNotFoundException
   {
       Scanner console = new Scanner (System.in);

       String search = console.nextLine();
       Scanner s = new Scanner(new File("C:\\Users\\xxxxx\\Desktop\\test.txt"));

       while (s.hasNextLine())
       {
         String temp = s.nextLine();
         if (temp.contains(search))
         {
            System.out.println(temp);
         }
       }
   } //Main

} //Finder

The text looks like this

Bob has a cat
Bob has a dog
Chris has a cat

If I search "cat", it will print out "Bob has a cat", and "Chris has a cat".
If I search "Bob", it will print out "Bob has a cat", and "Bob has a dog".

So I don't know what to put in the while loop. I know you have to do something with the indexOf string command, but I'm not sure how to implement it.

Body:
If you only want to match the whole line just call contains on a given String line to filter the ones you desire:

import java.util.Arrays;
import java.util.List;

public class TestSearch {
    public static void main(String[] args) {
        String query = "chris";
        List<String> dataList = Arrays.asList("Bob has a cat", "Bob has a dog", "Chris has a cat");
        dataList.stream().filter(str -> str.toLowerCase().contains(query)).forEach(System.out::println);
    }
}

which will print:

Chris has a cat

If you want something more elaborate, like getting all the indexes of the matches of your query in a given line, then you should try with Pattern and Matcher (pretty good tutorial here):

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {
    public static void main(String[] args) {
        String query = "bob";
        System.out.println("Searching for \"" + query + "\"...");
        Pattern patt = Pattern.compile(query);
        Arrays.asList(
                "Bob has a cat bob",
                "Bob has a dog",
                "Chris has a cat",
            "Cat has a chris that is a bob")
        .forEach(line -> {
            System.out.println("Checking in line = \"" + line + "\"");
            Matcher matcher = patt.matcher(line.toLowerCase());
            while (matcher.find()) {
                System.out.println("found! index = " + matcher.start());
            }
        });
    }
}

which will print:

Searching for "bob"...
Checking in line = "Bob has a cat bob"
found! index = 0
found! index = 14
Checking in line = "Bob has a dog"
found! index = 0
Checking in line = "Chris has a cat"
Checking in line = "Cat has a chris that is a bob"
found! index = 26

Plug in your file reading with java.nio and happy coding!

Cheers!


答:
There's typically three approaches. One is to assign this to another variable, conventionally named self or that, before the function; the variable will be captured into the function's closure.

```<code>let that = this;
geocoder.geocode(..., function(...) {
    that.isGeolocating
});
</code>```

Another is to explicitly tell the function what this should be, using bind:

```<code>geocoder.geocode(..., function(...) {
    this.isGeolocating
}.bind(this));
</code>```

The third one is to use a rocket function, which does not reassign this:

```<code>geocoder.geocode(..., (...) => {
    this.isGeolocating
});
</code>```

Title: How to correctly pass "this" into function?

Body:
There's typically three approaches. One is to assign this to another variable, conventionally named self or that, before the function; the variable will be captured into the function's closure.

let that = this;
geocoder.geocode(..., function(...) {
    that.isGeolocating
});

Another is to explicitly tell the function what this should be, using bind:

geocoder.geocode(..., function(...) {
    this.isGeolocating
}.bind(this));

The third one is to use a rocket function, which does not reassign this:

geocoder.geocode(..., (...) => {
    this.isGeolocating
});


答:
You need to either store a reference to this in a variable outside of your function, or use arrow functions.

So either

```<code>let self = this;
geocoder.geocode({'location': geolocation}, function(results, status) {
    // you existing code here
    // use self.isGeolocating
});
</code>```

of just

```<code>geocoder.geocode({'location': geolocation}, (results, status) => {
    // using this in here will use the this of the outer scope.
    // use this.isGeolocating
});
</code>```

Body:
You need to either store a reference to this in a variable outside of your function, or use arrow functions.

So either

let self = this;
geocoder.geocode({'location': geolocation}, function(results, status) {
    // you existing code here
    // use self.isGeolocating
});

of just

geocoder.geocode({'location': geolocation}, (results, status) => {
    // using this in here will use the this of the outer scope.
    // use this.isGeolocating
});