问:
How should I pass my s3 credentials to Python lambda function on AWS?
I'd like to write a file to S3 from my lambda function written in Python.  But I’m struggling to pass my S3 ID and Key.

The following works on my local machine after I set my local Python environment variables AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to point to the local files I created with the AWS CLI.

```<code>session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'))
</code>```

And the following works on Lambda where I hand code my ID and Key (using *** here):

```<code>AWS_ACCESS_KEY_ID = '***'
AWS_SECRET_ACCESS_KEY = '***'
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
</code>```

But I understand this is insecure after reading best practices from Amazon. So I try:

```<code>AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
</code>```

But I get an error: “The AWS Access Key Id you provided does not exist in our records.” I also tried to define these variables in the Lambda console, but I then I get: "Lambda was unable to configure your environment variables because the environment variables you have provided contains reserved keys."

I am a little surprised I need to pass an ID or Key at all since I believe my account for authoring the Lambda function also has permission to write to the S3 account (the key and secret I hand code are from IAM for this same account). I got the same sense from reading the following post:
AWS Lambda function write to S3

答:
You never need to use AWS access keys when you are using one AWS resource within another. Just allow the Lambda function to access the S3 bucket and any actions that you want to take (e.g. PutObject). If you make sure the Lambda function receives the role with the policy to allow for that kind of access, the SDK takes all authentication out of your hands. </p>

<p>If you do need to use any secrets keys in Lambda, e.g. of 3rd party systems or an AWS RDS database (non-Aurora), you may want to have a look at AWS KMS. This works nicely together with Lambda. But again: using S3 in Lambda should be handled with the right role/policy in IAM. </p>

Body:
I'd like to write a file to S3 from my lambda function written in Python.  But I’m struggling to pass my S3 ID and Key.

The following works on my local machine after I set my local Python environment variables AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to point to the local files I created with the AWS CLI.

session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'))

And the following works on Lambda where I hand code my ID and Key (using *** here):

AWS_ACCESS_KEY_ID = '***'
AWS_SECRET_ACCESS_KEY = '***'
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

But I understand this is insecure after reading best practices from Amazon. So I try:

AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

But I get an error: “The AWS Access Key Id you provided does not exist in our records.” I also tried to define these variables in the Lambda console, but I then I get: "Lambda was unable to configure your environment variables because the environment variables you have provided contains reserved keys."

I am a little surprised I need to pass an ID or Key at all since I believe my account for authoring the Lambda function also has permission to write to the S3 account (the key and secret I hand code are from IAM for this same account). I got the same sense from reading the following post:
AWS Lambda function write to S3

Body:
You never need to use AWS access keys when you are using one AWS resource within another. Just allow the Lambda function to access the S3 bucket and any actions that you want to take (e.g. PutObject). If you make sure the Lambda function receives the role with the policy to allow for that kind of access, the SDK takes all authentication out of your hands.

If you do need to use any secrets keys in Lambda, e.g. of 3rd party systems or an AWS RDS database (non-Aurora), you may want to have a look at AWS KMS. This works nicely together with Lambda. But again: using S3 in Lambda should be handled with the right role/policy in IAM.


来源: stackexchange

问:
2 classes in 2 header files
I am trying to compile a program that has 2 .h and 3.cpp . I keep getting the same error message: "error: ‘Patrons’ does not name a type   Patrons match;"

when I put the whole code in one single .cpp file, I have no errors and it compiles, but for my assignment I need to do it in separate files.

I think I wrote the code right so I dont know why I get the error message.

```<code>// class patrons.h

using namespace std;

class Patrons //named it patrons because this is where i have a list of all    the patrons
{

    int patronscnt;
    public:
    std::list<string>::iterator PL;
    std::list<string> patslist;
    string name;
    void patronslist();
    void addpatron();
    void removepatron();
    void editpatron();

};
</code>```

-

```<code>// class patron.h

using namespace std;

class Patron //class decleration. Named it patron because it has the information of one patron
{
    string x;
    string input;//class members
    Patrons match;
    public:

    void ID();
    void email();
    void phone();
    void address();
    void borrowstatus();
    void finestatus();
    void check(string);
    //update
 };
</code>```

答:
You could include patrons.h in patron.h.

You accomplish this by adding the following to the top of the patron.h file:

```<code>#include "patrons.h"
</code>```

However in my opinion, it is generally better to store a pointer to an object instead of the entire object. If you were to switch the match variable in patron.h to be a Patrons pointer:

```<code>Patrons *match;
</code>```

Then instead of including patrons.h, you could forward declare the Patrons class, by adding the following to the top of the patron.h file:

```<code>class Patrons;
</code>```

Then if needed you could include patrons.h in your patron.cpp file. Forward declaring will help you from running into circular dependencies.

ContentLicense: CC BY-SA 3.0

Title: 2 classes in 2 header files

Body:
I am trying to compile a program that has 2 .h and 3.cpp . I keep getting the same error message: "error: ‘Patrons’ does not name a type   Patrons match;"

when I put the whole code in one single .cpp file, I have no errors and it compiles, but for my assignment I need to do it in separate files.

I think I wrote the code right so I dont know why I get the error message.

// class patrons.h

using namespace std;

class Patrons //named it patrons because this is where i have a list of all    the patrons
{

    int patronscnt;
    public:
    std::list<string>::iterator PL;
    std::list<string> patslist;
    string name;
    void patronslist();
    void addpatron();
    void removepatron();
    void editpatron();

};

-

// class patron.h

using namespace std;

class Patron //class decleration. Named it patron because it has the information of one patron
{
    string x;
    string input;//class members
    Patrons match;
    public:

    void ID();
    void email();
    void phone();
    void address();
    void borrowstatus();
    void finestatus();
    void check(string);
    //update
 };

Body:
You could include patrons.h in patron.h.

You accomplish this by adding the following to the top of the patron.h file:

#include "patrons.h"

However in my opinion, it is generally better to store a pointer to an object instead of the entire object. If you were to switch the match variable in patron.h to be a Patrons pointer:

Patrons *match;

Then instead of including patrons.h, you could forward declare the Patrons class, by adding the following to the top of the patron.h file:

class Patrons;

Then if needed you could include patrons.h in your patron.cpp file. Forward declaring will help you from running into circular dependencies.


问:
scikit-learn RandomForestClassifier, stopped working, advice on how to debug
I am doing a grid search on a RandomForestClassifier and my code has been working until I changed the features and suddenly the code generates the following error (at line classifier.fit)

I did not change any code, but reduced the feature dimensions from 16 to 8. I am totally confused as to what I should look into. What does this error mean?

Error:

```<code>multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 344, in __call__
return self.func(*args, **kwargs)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
return [func(*args, **kwargs) for func, args, kwargs in self.items]
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in <listcomp>
return [func(*args, **kwargs) for func, args, kwargs in self.items]
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/ensemble/forest.py", line 120, in _parallel_build_trees
tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/tree/tree.py", line 739, in fit
X_idx_sorted=X_idx_sorted)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/tree/tree.py", line 246, in fit
raise ValueError("max_features must be in (0, n_features]")
ValueError: max_features must be in (0, n_features]
</code>```

Code:

```<code>    classifier = RandomForestClassifier(n_estimators=20, n_jobs=-1)
    rfc_tuning_params = {"max_depth": [3, 5, None],
                         "max_features": [1, 3, 5, 7, 10],
                         "min_samples_split": [2, 5, 10],
                         "min_samples_leaf": [1, 3, 10],
                         "bootstrap": [True, False],
                         "criterion": ["gini", "entropy"]}
    classifier = GridSearchCV(classifier, param_grid=rfc_tuning_params, cv=nfold,
                              n_jobs=cpus)
    model_file = os.path.join(os.path.dirname(__file__), "random-forest_classifier-%s.m" % task)
    classifier.fit(X_train, y_train) #line that causes the error
    nfold_predictions=cross_val_predict(classifier.best_estimator_, X_train, y_train, cv=nfold)
</code>```

答:
In your rfc_tuning_params, you have "max_features": [1, 3, 5, 7, 10]. That includes 10, which is bigger than the number of features (8). Hence you get the error

```<code>ValueError: max_features must be in (0, n_features]
</code>```

So you need to remove the 10 from "max_features".

Body:
I am doing a grid search on a RandomForestClassifier and my code has been working until I changed the features and suddenly the code generates the following error (at line classifier.fit)

I did not change any code, but reduced the feature dimensions from 16 to 8. I am totally confused as to what I should look into. What does this error mean?

Error:

multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py", line 344, in __call__
return self.func(*args, **kwargs)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in __call__
return [func(*args, **kwargs) for func, args, kwargs in self.items]
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py", line 131, in <listcomp>
return [func(*args, **kwargs) for func, args, kwargs in self.items]
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/ensemble/forest.py", line 120, in _parallel_build_trees
tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/tree/tree.py", line 739, in fit
X_idx_sorted=X_idx_sorted)
File "/home/zqz/Programs/anaconda3/lib/python3.5/site-packages/sklearn/tree/tree.py", line 246, in fit
raise ValueError("max_features must be in (0, n_features]")
ValueError: max_features must be in (0, n_features]

Code:

    classifier = RandomForestClassifier(n_estimators=20, n_jobs=-1)
    rfc_tuning_params = {"max_depth": [3, 5, None],
                         "max_features": [1, 3, 5, 7, 10],
                         "min_samples_split": [2, 5, 10],
                         "min_samples_leaf": [1, 3, 10],
                         "bootstrap": [True, False],
                         "criterion": ["gini", "entropy"]}
    classifier = GridSearchCV(classifier, param_grid=rfc_tuning_params, cv=nfold,
                              n_jobs=cpus)
    model_file = os.path.join(os.path.dirname(__file__), "random-forest_classifier-%s.m" % task)
    classifier.fit(X_train, y_train) #line that causes the error
    nfold_predictions=cross_val_predict(classifier.best_estimator_, X_train, y_train, cv=nfold)

Body:
In your rfc_tuning_params, you have "max_features": [1, 3, 5, 7, 10]. That includes 10, which is bigger than the number of features (8). Hence you get the error

ValueError: max_features must be in (0, n_features]

So you need to remove the 10 from "max_features".


问:
How can I check for a specific class using javascript?
So I need to be able to check if a specified id has a specific class, but I'm not completely sure on how to do that.

Here is my code. You can see my attempt at checking a id for a specific class in the homeTransition function.

function homeTransition()
    {
        if(document.getElementById("aboutContent").hasClass("animated fadeInUp")){
            document.getElementById("aboutContent").className = " animated slideOutDown";
        } else if(document.getElementById("projectsContent").hasClass("animated fadeInUp")){
            document.getElementById("projectsContent").className = " animated slideOutDown";
            } else if(document.getElementById("contactContent").hasClass("animated fadeInUp")){
                document.getElementById("contactContent").className = " animated slideOutDown";
            }
                    document.getElementById("astronaut").className = " animated fadeIn";
    }

function aboutTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("aboutContent").className = " animated fadeInUp";

        document.getElementById("projectsContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function projectsTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("projectsContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function contactTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("contactContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("projectsContent").className = " animated fadeOutLeft";
    }

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #2b2b41;
  z-index: -1;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #42424b;
  z-index: -1;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #353440;
  z-index: -1;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(45, 51, 54, 0.9);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #0dffec;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

Title

 home

 about

 projects

 contact

```

答:
Use vanilla Javascript

```<code>document.querySelector('#aboutContent.myclass');
</code>```

This reads: Select the element with the id (id selector #) aboutContent, and that has the class (class selector .) myClass.

Read up on

CSS selectors

querySelector

I'd also like to note that you seem to be mixing vanilla javascript and jQuery. Maybe you should read up on selecting elements with jQuery.

Body:
So I need to be able to check if a specified id has a specific class, but I'm not completely sure on how to do that.

Here is my code. You can see my attempt at checking a id for a specific class in the homeTransition function.

function homeTransition()
    {
        if(document.getElementById("aboutContent").hasClass("animated fadeInUp")){
            document.getElementById("aboutContent").className = " animated slideOutDown";
        } else if(document.getElementById("projectsContent").hasClass("animated fadeInUp")){
            document.getElementById("projectsContent").className = " animated slideOutDown";
            } else if(document.getElementById("contactContent").hasClass("animated fadeInUp")){
                document.getElementById("contactContent").className = " animated slideOutDown";
            }
                    document.getElementById("astronaut").className = " animated fadeIn";
    }

function aboutTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("aboutContent").className = " animated fadeInUp";

        document.getElementById("projectsContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function projectsTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("projectsContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function contactTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("contactContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("projectsContent").className = " animated fadeOutLeft";
    }

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #2b2b41;
  z-index: -1;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #42424b;
  z-index: -1;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #353440;
  z-index: -1;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(45, 51, 54, 0.9);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #0dffec;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

Title

 home

 about

 projects

 contact

Body:
Use vanilla Javascript

document.querySelector('#aboutContent.myclass');

This reads: Select the element with the id (id selector #) aboutContent, and that has the class (class selector .) myClass.

Read up on

CSS selectors

querySelector

I'd also like to note that you seem to be mixing vanilla javascript and jQuery. Maybe you should read up on selecting elements with jQuery.


问:
Different key type in a map
for a particular requirement I want to have a map with keys in different type. Similar to boost:any. (I have an old  gcc version)

```<code>map<any_type,string> aMap;

//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";
</code>```

is this something possible with the use boost ?

thank in advance

答:
If you're willing to use boost::variant:

Live On Coliru

```<code>#include <boost/variant.hpp>
#include <iostream>
#include <map>

using Key = boost::variant<int, std::string>;
using Map = std::map<Key, std::string>;

int main()
{
    Map m;

    m[1] = "aaa";
    m["myKey"] = "bbb";
}
</code>```

Key ordering/equation is automatically there. Note though that "1" and 1 are different keys in this approach.

Title: Different key type in a map

Body:
for a particular requirement I want to have a map with keys in different type. Similar to boost:any. (I have an old  gcc version)

map<any_type,string> aMap;

//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";

is this something possible with the use boost ?

thank in advance

Body:
If you're willing to use boost::variant:

Live On Coliru

#include <boost/variant.hpp>
#include <iostream>
#include <map>

using Key = boost::variant<int, std::string>;
using Map = std::map<Key, std::string>;

int main()
{
    Map m;

    m[1] = "aaa";
    m["myKey"] = "bbb";
}

Key ordering/equation is automatically there. Note though that "1" and 1 are different keys in this approach.


问:
Python constrained non-linear optimization
What's the recommended package for constrained non-linear optimization in python ?

The specific problem I'm trying to solve is this:

I have an unknown X (Nx1), I have M (Nx1) u vectors and M (NxN) s matrices.

```<code>max [5th percentile of (ui_T*X), i in 1 to M]
st
0<=X<=1 and
[95th percentile of (X_T*si*X), i in 1 to M]<= constant
</code>```

When I started out the problem I only had one point estimate for u and s and I was able to solve the problem above with cvxpy.

I realized that instead of one estimate for u and s, I had the entire distribution of values so I wanted to change my objective function so that I could use the entire distribution. The problem description above is my attempt to include that information in a meaningful way.

cvxpy cannot be used to solve this, I've tried scipy.optimize.anneal, but I can't seem to set bounds on the unknown values. I've looked at pulp too but it doesnt allow nonlinear constraints.

答:
While the SLSQP algorithm in scipy.optimize.minimize is good, it has a bunch of limitations.  The first of which is it's a QP solver, so it works will for equations that fit well into a quadratic programming paradigm. But what happens if you have functional constraints?  Also, scipy.optimize.minimize is not a global optimizer, so you often need to start very close to the final results.

There is a constrained nonlinear optimization package (called mystic) that has been around for nearly as long as scipy.optimize itself -- I'd suggest it as the go-to for handling any general constrained nonlinear optimization.

For example, your problem, if I understand your pseudo-code, looks something like this:

```<code>import numpy as np

M = 10
N = 3
Q = 10
C = 10

# let's be lazy, and generate s and u randomly...
s = np.random.randint(-Q,Q, size=(M,N,N))
u = np.random.randint(-Q,Q, size=(M,N))

def percentile(p, x):
    x = np.sort(x)
    p = 0.01 * p * len(x)
    if int(p) != p:
        return x[int(np.floor(p))]
    p = int(p)
    return x[p:p+2].mean()

def objective(x, p=5): # inverted objective, to find the max
    return -1*percentile(p, [np.dot(np.atleast_2d(u[i]), x)[0] for i in range(0,M-1)])

def constraint(x, p=95, v=C): # 95%(xTsx) - v <= 0
    x = np.atleast_2d(x)
    return percentile(p, [np.dot(np.dot(x,s[i]),x.T)[0,0] for i in range(0,M-1)]) - v

bounds = [(0,1) for i in range(0,N)]
</code>```

So, to handle your problem in mystic, you just need to specify the bounds and the constraints.

```<code>from mystic.penalty import quadratic_inequality
@quadratic_inequality(constraint, k=1e4)
def penalty(x):
  return 0.0

from mystic.solvers import diffev2
from mystic.monitors import VerboseMonitor
mon = VerboseMonitor(10)

result = diffev2(objective, x0=bounds, penalty=penalty, npop=10, gtol=200, \
                 disp=False, full_output=True, itermon=mon, maxiter=M*N*100)

print result[0]
print result[1]
</code>```

The result looks something like this:

```<code>Generation 0 has Chi-Squared: -0.434718
Generation 10 has Chi-Squared: -1.733787
Generation 20 has Chi-Squared: -1.859787
Generation 30 has Chi-Squared: -1.860533
Generation 40 has Chi-Squared: -1.860533
Generation 50 has Chi-Squared: -1.860533
Generation 60 has Chi-Squared: -1.860533
Generation 70 has Chi-Squared: -1.860533
Generation 80 has Chi-Squared: -1.860533
Generation 90 has Chi-Squared: -1.860533
Generation 100 has Chi-Squared: -1.860533
Generation 110 has Chi-Squared: -1.860533
Generation 120 has Chi-Squared: -1.860533
Generation 130 has Chi-Squared: -1.860533
Generation 140 has Chi-Squared: -1.860533
Generation 150 has Chi-Squared: -1.860533
Generation 160 has Chi-Squared: -1.860533
Generation 170 has Chi-Squared: -1.860533
Generation 180 has Chi-Squared: -1.860533
Generation 190 has Chi-Squared: -1.860533
Generation 200 has Chi-Squared: -1.860533
Generation 210 has Chi-Squared: -1.860533
STOP("ChangeOverGeneration with {'tolerance': 0.005, 'generations': 200}")
[-0.17207128  0.73183465 -0.28218955]
-1.86053344078
</code>```

mystic is very flexible, and can handle any type of constraints (e.g. equalities, inequalities) including symbolic and functional constraints.
I specified the constraints as "penalties" above, which is the traditional way, in that they apply a penalty to the objective when the constraint is violated.
mystic also provides nonlinear kernel transformations, which constrain solution space by reducing the space of valid solutions (i.e. by a spatial mapping or kernel transformation).

As an example, here's mystic solving a problem that breaks a lot of QP solvers, since the constraints are not in the form of a constraints matrix.  It's optimizing the design of a pressure vessel.

```<code>"Pressure Vessel Design"

def objective(x):
    x0,x1,x2,x3 = x
    return 0.6224*x0*x2*x3 + 1.7781*x1*x2**2 + 3.1661*x0**2*x3 + 19.84*x0**2*x2

bounds = [(0,1e6)]*4
# with penalty='penalty' applied, solution is:
xs = [0.72759093, 0.35964857, 37.69901188, 240.0]
ys = 5804.3762083

from mystic.symbolic import generate_constraint, generate_solvers, simplify
from mystic.symbolic import generate_penalty, generate_conditions

equations = """
-x0 + 0.0193*x2 <= 0.0
-x1 + 0.00954*x2 <= 0.0
-pi*x2**2*x3 - (4/3.)*pi*x2**3 + 1296000.0 <= 0.0
x3 - 240.0 <= 0.0
"""
cf = generate_constraint(generate_solvers(simplify(equations)))
pf = generate_penalty(generate_conditions(equations), k=1e12)

if __name__ == '__main__':

    from mystic.solvers import diffev2
    from mystic.math import almostEqual
    from mystic.monitors import VerboseMonitor
    mon = VerboseMonitor(10)

    result = diffev2(objective, x0=bounds, bounds=bounds, constraints=cf, penalty=pf, \
                     npop=40, gtol=50, disp=False, full_output=True, itermon=mon)

    assert almostEqual(result[0], xs, rel=1e-2)
    assert almostEqual(result[1], ys, rel=1e-2)
</code>```

Find this, and roughly 100 examples like it, here: https://github.com/uqfoundation/mystic.

I'm the author, so I am slightly biased.  However, the bias is very slight. mystic is both mature and well-supported, and is unparalleled in capacity to solve hard constrained nonlinear optimization problems.

Body:
What's the recommended package for constrained non-linear optimization in python ?

The specific problem I'm trying to solve is this:

I have an unknown X (Nx1), I have M (Nx1) u vectors and M (NxN) s matrices.

max [5th percentile of (ui_T*X), i in 1 to M]
st
0<=X<=1 and
[95th percentile of (X_T*si*X), i in 1 to M]<= constant

When I started out the problem I only had one point estimate for u and s and I was able to solve the problem above with cvxpy.

I realized that instead of one estimate for u and s, I had the entire distribution of values so I wanted to change my objective function so that I could use the entire distribution. The problem description above is my attempt to include that information in a meaningful way.

cvxpy cannot be used to solve this, I've tried scipy.optimize.anneal, but I can't seem to set bounds on the unknown values. I've looked at pulp too but it doesnt allow nonlinear constraints.

Body:
While the SLSQP algorithm in scipy.optimize.minimize is good, it has a bunch of limitations.  The first of which is it's a QP solver, so it works will for equations that fit well into a quadratic programming paradigm. But what happens if you have functional constraints?  Also, scipy.optimize.minimize is not a global optimizer, so you often need to start very close to the final results.

There is a constrained nonlinear optimization package (called mystic) that has been around for nearly as long as scipy.optimize itself -- I'd suggest it as the go-to for handling any general constrained nonlinear optimization.

For example, your problem, if I understand your pseudo-code, looks something like this:

import numpy as np

M = 10
N = 3
Q = 10
C = 10

# let's be lazy, and generate s and u randomly...
s = np.random.randint(-Q,Q, size=(M,N,N))
u = np.random.randint(-Q,Q, size=(M,N))

def percentile(p, x):
    x = np.sort(x)
    p = 0.01 * p * len(x)
    if int(p) != p:
        return x[int(np.floor(p))]
    p = int(p)
    return x[p:p+2].mean()

def objective(x, p=5): # inverted objective, to find the max
    return -1*percentile(p, [np.dot(np.atleast_2d(u[i]), x)[0] for i in range(0,M-1)])

def constraint(x, p=95, v=C): # 95%(xTsx) - v <= 0
    x = np.atleast_2d(x)
    return percentile(p, [np.dot(np.dot(x,s[i]),x.T)[0,0] for i in range(0,M-1)]) - v

bounds = [(0,1) for i in range(0,N)]

So, to handle your problem in mystic, you just need to specify the bounds and the constraints.

from mystic.penalty import quadratic_inequality
@quadratic_inequality(constraint, k=1e4)
def penalty(x):
  return 0.0

from mystic.solvers import diffev2
from mystic.monitors import VerboseMonitor
mon = VerboseMonitor(10)

result = diffev2(objective, x0=bounds, penalty=penalty, npop=10, gtol=200, \
                 disp=False, full_output=True, itermon=mon, maxiter=M*N*100)

print result[0]
print result[1]

The result looks something like this:

Generation 0 has Chi-Squared: -0.434718
Generation 10 has Chi-Squared: -1.733787
Generation 20 has Chi-Squared: -1.859787
Generation 30 has Chi-Squared: -1.860533
Generation 40 has Chi-Squared: -1.860533
Generation 50 has Chi-Squared: -1.860533
Generation 60 has Chi-Squared: -1.860533
Generation 70 has Chi-Squared: -1.860533
Generation 80 has Chi-Squared: -1.860533
Generation 90 has Chi-Squared: -1.860533
Generation 100 has Chi-Squared: -1.860533
Generation 110 has Chi-Squared: -1.860533
Generation 120 has Chi-Squared: -1.860533
Generation 130 has Chi-Squared: -1.860533
Generation 140 has Chi-Squared: -1.860533
Generation 150 has Chi-Squared: -1.860533
Generation 160 has Chi-Squared: -1.860533
Generation 170 has Chi-Squared: -1.860533
Generation 180 has Chi-Squared: -1.860533
Generation 190 has Chi-Squared: -1.860533
Generation 200 has Chi-Squared: -1.860533
Generation 210 has Chi-Squared: -1.860533
STOP("ChangeOverGeneration with {'tolerance': 0.005, 'generations': 200}")
[-0.17207128  0.73183465 -0.28218955]
-1.86053344078

mystic is very flexible, and can handle any type of constraints (e.g. equalities, inequalities) including symbolic and functional constraints.
I specified the constraints as "penalties" above, which is the traditional way, in that they apply a penalty to the objective when the constraint is violated.
mystic also provides nonlinear kernel transformations, which constrain solution space by reducing the space of valid solutions (i.e. by a spatial mapping or kernel transformation).

As an example, here's mystic solving a problem that breaks a lot of QP solvers, since the constraints are not in the form of a constraints matrix.  It's optimizing the design of a pressure vessel.

"Pressure Vessel Design"

def objective(x):
    x0,x1,x2,x3 = x
    return 0.6224*x0*x2*x3 + 1.7781*x1*x2**2 + 3.1661*x0**2*x3 + 19.84*x0**2*x2

bounds = [(0,1e6)]*4
# with penalty='penalty' applied, solution is:
xs = [0.72759093, 0.35964857, 37.69901188, 240.0]
ys = 5804.3762083

from mystic.symbolic import generate_constraint, generate_solvers, simplify
from mystic.symbolic import generate_penalty, generate_conditions

equations = """
-x0 + 0.0193*x2 <= 0.0
-x1 + 0.00954*x2 <= 0.0
-pi*x2**2*x3 - (4/3.)*pi*x2**3 + 1296000.0 <= 0.0
x3 - 240.0 <= 0.0
"""
cf = generate_constraint(generate_solvers(simplify(equations)))
pf = generate_penalty(generate_conditions(equations), k=1e12)

if __name__ == '__main__':

    from mystic.solvers import diffev2
    from mystic.math import almostEqual
    from mystic.monitors import VerboseMonitor
    mon = VerboseMonitor(10)

    result = diffev2(objective, x0=bounds, bounds=bounds, constraints=cf, penalty=pf, \
                     npop=40, gtol=50, disp=False, full_output=True, itermon=mon)

    assert almostEqual(result[0], xs, rel=1e-2)
    assert almostEqual(result[1], ys, rel=1e-2)

Find this, and roughly 100 examples like it, here: https://github.com/uqfoundation/mystic.

I'm the author, so I am slightly biased.  However, the bias is very slight. mystic is both mature and well-supported, and is unparalleled in capacity to solve hard constrained nonlinear optimization problems.


问:
Spree-blogging-spree missing required :bucket option
I am working on a spree store and have Amazon s3 working just fine on the main app. I added the spree-blogging-spree gem by just following the read me instructions but I am now getting a missing required :bucket option error when I try to edit post or add an image. This is only for blog related edits and images everything else is still working fine. </p>

<p>I know this is referring to s3 but I am not sure why it is showing up now. Is there a migration I missed or some kind of config file I need to add? </p>

```<code>Showing /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-blogging-spree-81da8dd081a5/app/views/spree/admin/blog_entries/_form.html.erb where line #85 raised:

missing required :bucket option
Extracted source (around line #242):
240
241
242
243
244
245

        @bucket = @options[:bucket] || s3_credentials[:bucket]
        @bucket = @bucket.call(self) if @bucket.respond_to?(:call)
        @bucket or raise ArgumentError, "missing required :bucket option"
      end

      def s3_interface

Trace of template inclusion: /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-blogging-spree-81da8dd081a5/app/views/spree/admin/blog_entries/edit.html.erb

Rails.root: /home/ubuntu/workspace/mumbles_spree
</code>```

答:
I figured it out I had to add my s3 credentials to the blog_entry_image.rb:

app/models/spree/blog_entry_image.rb

```<code>class Spree::BlogEntryImage < Spree::Image
  has_attached_file :attachment,
     :styles => {:mini => '48x48#', :normal => '200x200>', :large => '600x600>'},
     :default_style => :large,
     :url => "/assets/blog_entry_images/:id/:style/:basename.:extension",
     :path => ":rails_root/public/assets/blog_entry_images/:id/:style/:basename.:extension" ,
      storage: :s3,
                  s3_credentials: {access_key_id: 'xxx',
                  secret_access_key:  'xxx'},
                  bucket: 'xxx'
end
</code>```

Body:
I am working on a spree store and have Amazon s3 working just fine on the main app. I added the spree-blogging-spree gem by just following the read me instructions but I am now getting a missing required :bucket option error when I try to edit post or add an image. This is only for blog related edits and images everything else is still working fine.

I know this is referring to s3 but I am not sure why it is showing up now. Is there a migration I missed or some kind of config file I need to add?

Showing /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-blogging-spree-81da8dd081a5/app/views/spree/admin/blog_entries/_form.html.erb where line #85 raised:

missing required :bucket option
Extracted source (around line #242):
240
241
242
243
244
245

        @bucket = @options[:bucket] || s3_credentials[:bucket]
        @bucket = @bucket.call(self) if @bucket.respond_to?(:call)
        @bucket or raise ArgumentError, "missing required :bucket option"
      end

      def s3_interface

Trace of template inclusion: /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/spree-blogging-spree-81da8dd081a5/app/views/spree/admin/blog_entries/edit.html.erb

Rails.root: /home/ubuntu/workspace/mumbles_spree

Body:
I figured it out I had to add my s3 credentials to the blog_entry_image.rb:

app/models/spree/blog_entry_image.rb

class Spree::BlogEntryImage < Spree::Image
  has_attached_file :attachment,
     :styles => {:mini => '48x48#', :normal => '200x200>', :large => '600x600>'},
     :default_style => :large,
     :url => "/assets/blog_entry_images/:id/:style/:basename.:extension",
     :path => ":rails_root/public/assets/blog_entry_images/:id/:style/:basename.:extension" ,
      storage: :s3,
                  s3_credentials: {access_key_id: 'xxx',
                  secret_access_key:  'xxx'},
                  bucket: 'xxx'
end


问:
Strange character appearing at start of string
I am taking different transistor data from a file. The program stores that in a structure. It then prompts for an input from the user. User enters 5 different values, eg 12 0.03 100 320 65 and then the program takes these values and compares it to the data from the file and sees if any transistors would be suitable for the parameters you have entered.
The program then prompts the user again, and this repeats until the letter q is entered, which ends the program.

The problem I'm having - and I've been trawling the internet for hours trying to find a solution but none of them have worked - is that any input after the first set isn't accepted. So it looks like this.

Please input: Voltage Current Power Frequency Gain

15 0.1 200 100 80

15 0.1 200 100 80

ALL RELEVANT TRANSISTORS

Please input: Voltage Current Power Frequency Gain

20 0.3 100 150 40

?1 2 3 4 5

The question mark is always a strange character. In the past few hours it has been a ? in a diamond, the letter P, and a small square with 0010 in it. Everything I have found on the internet says this should work. What am I missing?

Here's my input function

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
struct input{
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX_IN];

int CHK =1, number=0;

int input_function1()
{
    const char check[3] = {'\0'};
    int i;
    const char inp[30] = {'\0'};

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp); //Prints out the string to see if the input has been correctly accepted
    ungetc(inp, stdin);

    sscanf(inp, "%s", &check);
    if(check[0]!='q' && check[1]!='q' && check[2]!='q')
    {

    sscanf(inp, "%d %f %d %d %d", &inputs[number].volt, &inputs[number].amp,
    &inputs[number].power, &inputs[number].freq, &inputs[number].gain);

    }

}
</code>```

Below is how I am calling the function. check_function is the function which checks the input transistor against the database.

```<code>while(CHK==1)
{
    input_function1();

    check_function();
    ++number;

}
</code>```

答:
You are declaring a const char array like this:

```<code>const char test[30] = {'\0'};
</code>```

and that actually creates a string/array that is not editable and the terminating 0 that should mark the end of a string is the only character in this array. Also this zero is being set at the test[0].

ContentLicense: CC BY-SA 4.0

Body:
I am taking different transistor data from a file. The program stores that in a structure. It then prompts for an input from the user. User enters 5 different values, eg 12 0.03 100 320 65 and then the program takes these values and compares it to the data from the file and sees if any transistors would be suitable for the parameters you have entered.
The program then prompts the user again, and this repeats until the letter q is entered, which ends the program.

The problem I'm having - and I've been trawling the internet for hours trying to find a solution but none of them have worked - is that any input after the first set isn't accepted. So it looks like this.

Please input: Voltage Current Power Frequency Gain

15 0.1 200 100 80

15 0.1 200 100 80

ALL RELEVANT TRANSISTORS

Please input: Voltage Current Power Frequency Gain

20 0.3 100 150 40

?1 2 3 4 5

The question mark is always a strange character. In the past few hours it has been a ? in a diamond, the letter P, and a small square with 0010 in it. Everything I have found on the internet says this should work. What am I missing?

Here's my input function

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
struct input{
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX_IN];

int CHK =1, number=0;

int input_function1()
{
    const char check[3] = {'\0'};
    int i;
    const char inp[30] = {'\0'};

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp); //Prints out the string to see if the input has been correctly accepted
    ungetc(inp, stdin);

    sscanf(inp, "%s", &check);
    if(check[0]!='q' && check[1]!='q' && check[2]!='q')
    {

    sscanf(inp, "%d %f %d %d %d", &inputs[number].volt, &inputs[number].amp,
    &inputs[number].power, &inputs[number].freq, &inputs[number].gain);

    }

}

Below is how I am calling the function. check_function is the function which checks the input transistor against the database.

while(CHK==1)
{
    input_function1();

    check_function();
    ++number;

}

Body:
You are declaring a const char array like this:

const char test[30] = {'\0'};

and that actually creates a string/array that is not editable and the terminating 0 that should mark the end of a string is the only character in this array. Also this zero is being set at the test[0].


问:
Running Multiple Servos With Timer/Counters
I am currently working with a project for school in which I am building a small cart that will scan an area for the most intense source of light and drive towards it. I have programmed an SG90 180 degree servo to scan a 180 degree area, use the info I scanned to create a decision and then turn the cart and drive towards the light. The issue I have run into is that I am using the TIMER/COUNTER1 to create a PWM wave to drive the motors. My issue extends from the fact that I am using FS90R servos to drive the cart which also run on a PWM wave. My timer counter is already running the 180 degree servo and when I go to drive the continuous servos the SG90 turns and while I am scanning one of my wheels turns. This obviously is not how the cart should run. Does anyone have a way to possibly create an interrupt driven PWM wave that does not directly employ the use of the PWM capabilities of the TIMER/COUNTER1 so that I can control all 3 of the servos separately?</p>

答:
There are 6 PWM outputs on the Arduino, two from each timer. If you are using existing libraries to drive the outputs to the servos the libraries might assume the use of timer 1. You would have to dive into the library code to modify the libraries.

Arduino PWM Information

Ensure that you have each servo on a separate PWM output.


问:
HTML/CSS code for creating a Table
I am currently working on this assignment for school. I have two issues I can't find the solution for.

HTML Validation gives me this error - A table row was 5 columns wide and exceeded the column count established by the first row (4).
From line 72, column 5; to line 72, column 9

As you can see on the table there is an extra column at the end that is very small. I am not sure how to eliminate that.

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th id="package-names">Package Name</th>
    <th id="description">Description</th>
    <th id="nights">Nights</th>
    <th id="cost-per-person">Cost per Person</th>
  </tr>
  <tr>
    <td headers="package-names">Weekend Escape</td>
    <td headers="description" class="text">Two breakfasts, a     trail map, a picnic snack</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$450</td>
  </tr>
  <tr>
    <td headers="package-names">Zen Retreat</td>
    <td headers="description" class="text">Four breakfasts, a trail map, a pass for daily yoga</td>
    <td headers="nights">4</td>
    <td headers="cost-per-person">$600</td>
  </tr>
  <tr>
    <td headers="package-names">Kayak Away</td>
    <td headers="description" class="text">Two breakfasts, two hours of kayak rental daily, a trail map</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$500<td>
  </tr>
</table></code>```

答:
The error is in the very last td line:

```<code><td headers="cost-per-person">$500<td>
</code>```

The last tag has to be  a closing tag: 	instead of

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th id="package-names">Package Name</th>
    <th id="description">Description</th>
    <th id="nights">Nights</th>
    <th id="cost-per-person">Cost per Person</th>
  </tr>
  <tr>
    <td headers="package-names">Weekend Escape</td>
    <td headers="description" class="text">Two breakfasts, a     trail map, a picnic snack</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$450</td>
  </tr>
  <tr>
    <td headers="package-names">Zen Retreat</td>
    <td headers="description" class="text">Four breakfasts, a trail map, a pass for daily yoga</td>
    <td headers="nights">4</td>
    <td headers="cost-per-person">$600</td>
  </tr>
  <tr>
    <td headers="package-names">Kayak Away</td>
    <td headers="description" class="text">Two breakfasts, two hours of kayak rental daily, a trail map</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$500</td>
  </tr>
</table></code>```

Title: HTML/CSS code for creating a Table

Body:
I am currently working on this assignment for school. I have two issues I can't find the solution for.

HTML Validation gives me this error - A table row was 5 columns wide and exceeded the column count established by the first row (4).
From line 72, column 5; to line 72, column 9

As you can see on the table there is an extra column at the end that is very small. I am not sure how to eliminate that.

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }

    Package Name
    Description
    Nights
    Cost per Person

    Weekend Escape
    Two breakfasts, a     trail map, a picnic snack
    2
    $450

    Zen Retreat
    Four breakfasts, a trail map, a pass for daily yoga
    4
    $600

    Kayak Away
    Two breakfasts, two hours of kayak rental daily, a trail map
    2
    $500

Body:
The error is in the very last td line:

<td headers="cost-per-person">$500<td>

The last tag has to be  a closing tag: </td>instead of <td>

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }

<table>
  <tr>
    <th id="package-names">Package Name</th>
    <th id="description">Description</th>
    <th id="nights">Nights</th>
    <th id="cost-per-person">Cost per Person</th>
  </tr>
  <tr>
    <td headers="package-names">Weekend Escape</td>
    <td headers="description" class="text">Two breakfasts, a     trail map, a picnic snack</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$450</td>
  </tr>
  <tr>
    <td headers="package-names">Zen Retreat</td>
    <td headers="description" class="text">Four breakfasts, a trail map, a pass for daily yoga</td>
    <td headers="nights">4</td>
    <td headers="cost-per-person">$600</td>
  </tr>
  <tr>
    <td headers="package-names">Kayak Away</td>
    <td headers="description" class="text">Two breakfasts, two hours of kayak rental daily, a trail map</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$500</td>
  </tr>
</table>


问:
add jquery stellar plugin to laravel 5.4 project using mix
I am new using Laravel Mix, I cant' add the jquery library stellar, it show me this error, when I try npm run dev:
This dependency was not found:
* jquery.stellar in ./resources/assets/js/bootstrap.js

But I already installed it using npm install --save jquery.stellar or npm install jquery.stellar

this is my webpack file:
webpack.mix.js:

```<code>const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   ;
</code>```

app.js:

```<code>/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/*Ie10 windows phone fix*/
(function() {
  if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement("style");
    msViewportStyle.appendChild(
      document.createTextNode("@-ms-viewport{width:auto!important}")
    );
    document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  }
})();

/*Android fix*/
$(function () {
  var nua = navigator.userAgent
  var isAndroid = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1 && nua.indexOf('Chrome') === -1)
  if (isAndroid) {
    $('select.form-control').removeClass('form-control').css('width', '100%')
  }
});

/*my code*/
$(document).ready(function () {

    $('.navbar-toggle').click(function () {
        $('.row-offcanvas').toggleClass('active');
    });

    var w = $(window);
    if (w.width() >= 768 ){
        $('body').removeClass('margin-body');
        $('nav[role="navigation"]').removeClass('navbar-fixed-top');
    }else{
        $('body').addClass('margin-body');
        $('nav[role="navigation"]').addClass('navbar-fixed-top');
    }

    $(window).stellar();

});
</code>```

bootstrap.js

```<code>window.$ = window.jQuery = require('jquery');

require('jquery.stellar');

require('bootstrap-less');
</code>```

And in my node_modules directory there is a jquery.stellar directory with 3 files in it: README.md,jquery.stellar.js, package.js

I dont know what is happening, thank you.

答:
Here is how you can add jquery.stellar!

Assuming that you already installed stellar as your dependency
You just have to write this line require( 'jquery.stellar/jquery.stellar' );
or require( 'jquery.stellar/jquery.stellar.js' ); both works fine

Body:
I am new using Laravel Mix, I cant' add the jquery library stellar, it show me this error, when I try npm run dev:
This dependency was not found:
* jquery.stellar in ./resources/assets/js/bootstrap.js

But I already installed it using npm install --save jquery.stellar or npm install jquery.stellar

this is my webpack file:
webpack.mix.js:

const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   ;

app.js:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/*Ie10 windows phone fix*/
(function() {
  if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement("style");
    msViewportStyle.appendChild(
      document.createTextNode("@-ms-viewport{width:auto!important}")
    );
    document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  }
})();

/*Android fix*/
$(function () {
  var nua = navigator.userAgent
  var isAndroid = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1 && nua.indexOf('Chrome') === -1)
  if (isAndroid) {
    $('select.form-control').removeClass('form-control').css('width', '100%')
  }
});

/*my code*/
$(document).ready(function () {

    $('.navbar-toggle').click(function () {
        $('.row-offcanvas').toggleClass('active');
    });

    var w = $(window);
    if (w.width() >= 768 ){
        $('body').removeClass('margin-body');
        $('nav[role="navigation"]').removeClass('navbar-fixed-top');
    }else{
        $('body').addClass('margin-body');
        $('nav[role="navigation"]').addClass('navbar-fixed-top');
    }

    $(window).stellar();

});

bootstrap.js

window.$ = window.jQuery = require('jquery');

require('jquery.stellar');

require('bootstrap-less');

And in my node_modules directory there is a jquery.stellar directory with 3 files in it: README.md,jquery.stellar.js, package.js

I dont know what is happening, thank you.


问:
Coping images (bitmaps) massively in vb.net by clicking a button
I create a project and one of its features is to copy images (or bitmaps) by clicking a button. What I mean is that by clicking once only one small picture will be shown, by clicking an other one time two small pictures will be shown, by clicking 3 times there would be 8 etc. (2^(the times the button is clicked)). Can you help me with the code because I can't express it in vb.net code.

I thank you in advance

答:
I have troubles to understand your question, could you clarify in what way you want the pictures to be shown? And if u want to copy them or just show these pictures in some sort of preview Form?

(sorry to post this As an Answer, but im missing reputation to comment your innitial question)


问:
Looping through files and saving as new file in r
I've been trying to figure out a way to loop through a bunch of "csv" files that contain absorbance data. The file name reads as: Plate"x" 0000000.csv - the "x" is a plate number and the 0's represent a unique code consisting of time and date of observation. The goal is to run through each of the 269 files in my source folder and calculate some values consistently. I have the code done for the calculations. However, I am having trouble getting r looping through all of the files, applying the calculations, and then saving to a new file the output as a csv file in  a new folder as: Plate"x" 000000.csv</p>

```<code> wd = 'C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates'

setwd(wd)

dirs = dir(getwd())

for (i in 1:269){

  #absfiles = list.files(pattern = "*.csv") # list abs files

plate <- read.csv("C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates/absfiles", ".csv", sep="/")

  #for (j in 1:269)

    #u_IDs = as.data.frame(strsplit(absfiles[j], '[.]'))

    #unique_ID = as.character(u_IDs[1])

#plate <- u_IDs

#plate <- fread('C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates/absfiles')
#plate1 <-data.table(plate)
#str(plate)

colnames(plate)[1] <- "Well.ID"
colnames(plate)[3] <- "Absorbance"
#str(plate)

setDT(plate)[, Well.ID:=Well.ID[1L] ,cumsum(Well.ID!='')]
#str(plate)str()

plate[,Well.ID:=as.character(Well.ID)][Well.ID == "BLK", Well.ID := "111BLK"]

plate <- plate[,ID:=substr(Well.ID,4,6)]

plate <- plate[,Group:=ID]
plate <- plate[,Group:=as.factor(Group)]
plate <- plate[Group == "BLK", Group := "0"]
plate <- plate[,Group:=as.character(Group)]
plate <- plate[,Group:=as.numeric(Group)]
plate <- plate[Group > 0.9 & Group < 31.1, Group:= 1]
plate <- plate[Group > 31.1 & Group < 62.1, Group := 2]
plate <- plate[Group > 62.1 & Group < 93.1, Group := 3]
#str(plate$Group)

b1<-plate[Well %in% c("A1"),Absorbance]
b2<-plate[Well %in% c("A5"),Absorbance]
b3<-plate[Well %in% c("A9"),Absorbance]

#group_1<-plate[,abs.c:=Absorbance-b1]
#group_2<-plate[,abs.c:=Absorbance-b2]
#group_3<-plate[,abs.c:=Absorbance-b3]

plate[Group %in% c(1), abs.c:=Absorbance-b1]
plate[Group %in% c(2), abs.c:=Absorbance-b2]
plate[Group %in% c(3), abs.c:=Absorbance-b3]

plate[Group %in% c(1), AWCD:=mean(abs.c)]
plate[Group %in% c(2), AWCD:=mean(abs.c)]
plate[Group %in% c(3), AWCD:=mean(abs.c)]

plate[Group %in% c(1), Odi:=sum(abs.c,c(1))]
plate[Group %in% c(2), Odi:=sum(abs.c,c(2))]
plate[Group %in% c(3), Odi:=sum(abs.c,c(3))]

plate[Group %in% c(1), Pi:=abs.c/Odi]
plate[Group %in% c(2), Pi:=abs.c/Odi]
plate[Group %in% c(3), Pi:=abs.c/Odi]

plate[Group %in% c(1), sumpi:=Pi,c(1)*(log(Pi,c(1)))]
plate[Group %in% c(2), sumpi:=Pi,c(2)*(log(Pi,c(2)))]
plate[Group %in% c(3), sumpi:=Pi,c(3)*(log(Pi,c(3)))]

plate[is.na(plate)] <- 0

plate[Group %in% c(1), H:=sum(sumpi,c(1))]
plate[Group %in% c(2), H:=sum(sumpi,c(2))]
plate[Group %in% c(3), H:=sum(sumpi,c(3))]

H. <- plate[!duplicated(H),]
H. <- H.[!NA]
platechar <-as.character(H.)
#dir.create("./H_Values_Plates")
file=H.(paste("./H_Values_Plates/",".csv",sep="/"))
}
</code>```

答: paste('Plate',i,'000.csv', sep = '') in your loop with i taking values that you need should allow you to loop through. you seem to have a decent grasp on what you're doing in the loop. just use this to get at all the files

Body:
I've been trying to figure out a way to loop through a bunch of "csv" files that contain absorbance data. The file name reads as: Plate"x" 0000000.csv - the "x" is a plate number and the 0's represent a unique code consisting of time and date of observation. The goal is to run through each of the 269 files in my source folder and calculate some values consistently. I have the code done for the calculations. However, I am having trouble getting r looping through all of the files, applying the calculations, and then saving to a new file the output as a csv file in  a new folder as: Plate"x" 000000.csv

 wd = 'C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates'

setwd(wd)

dirs = dir(getwd())

for (i in 1:269){

  #absfiles = list.files(pattern = "*.csv") # list abs files

plate <- read.csv("C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates/absfiles", ".csv", sep="/")

  #for (j in 1:269)

    #u_IDs = as.data.frame(strsplit(absfiles[j], '[.]'))

    #unique_ID = as.character(u_IDs[1])

#plate <- u_IDs

#plate <- fread('C:/Users/anadamsk/Documents/GRAD/DATA/Ecolog Plates/absfiles')
#plate1 <-data.table(plate)
#str(plate)

colnames(plate)[1] <- "Well.ID"
colnames(plate)[3] <- "Absorbance"
#str(plate)

setDT(plate)[, Well.ID:=Well.ID[1L] ,cumsum(Well.ID!='')]
#str(plate)str()

plate[,Well.ID:=as.character(Well.ID)][Well.ID == "BLK", Well.ID := "111BLK"]

plate <- plate[,ID:=substr(Well.ID,4,6)]

plate <- plate[,Group:=ID]
plate <- plate[,Group:=as.factor(Group)]
plate <- plate[Group == "BLK", Group := "0"]
plate <- plate[,Group:=as.character(Group)]
plate <- plate[,Group:=as.numeric(Group)]
plate <- plate[Group > 0.9 & Group < 31.1, Group:= 1]
plate <- plate[Group > 31.1 & Group < 62.1, Group := 2]
plate <- plate[Group > 62.1 & Group < 93.1, Group := 3]
#str(plate$Group)

b1<-plate[Well %in% c("A1"),Absorbance]
b2<-plate[Well %in% c("A5"),Absorbance]
b3<-plate[Well %in% c("A9"),Absorbance]

#group_1<-plate[,abs.c:=Absorbance-b1]
#group_2<-plate[,abs.c:=Absorbance-b2]
#group_3<-plate[,abs.c:=Absorbance-b3]

plate[Group %in% c(1), abs.c:=Absorbance-b1]
plate[Group %in% c(2), abs.c:=Absorbance-b2]
plate[Group %in% c(3), abs.c:=Absorbance-b3]

plate[Group %in% c(1), AWCD:=mean(abs.c)]
plate[Group %in% c(2), AWCD:=mean(abs.c)]
plate[Group %in% c(3), AWCD:=mean(abs.c)]

plate[Group %in% c(1), Odi:=sum(abs.c,c(1))]
plate[Group %in% c(2), Odi:=sum(abs.c,c(2))]
plate[Group %in% c(3), Odi:=sum(abs.c,c(3))]

plate[Group %in% c(1), Pi:=abs.c/Odi]
plate[Group %in% c(2), Pi:=abs.c/Odi]
plate[Group %in% c(3), Pi:=abs.c/Odi]

plate[Group %in% c(1), sumpi:=Pi,c(1)*(log(Pi,c(1)))]
plate[Group %in% c(2), sumpi:=Pi,c(2)*(log(Pi,c(2)))]
plate[Group %in% c(3), sumpi:=Pi,c(3)*(log(Pi,c(3)))]

plate[is.na(plate)] <- 0

plate[Group %in% c(1), H:=sum(sumpi,c(1))]
plate[Group %in% c(2), H:=sum(sumpi,c(2))]
plate[Group %in% c(3), H:=sum(sumpi,c(3))]

H. <- plate[!duplicated(H),]
H. <- H.[!NA]
platechar <-as.character(H.)
#dir.create("./H_Values_Plates")
file=H.(paste("./H_Values_Plates/",".csv",sep="/"))
}


问:
Testing equality between two __m128i variables
If I want to do a bitwise equality test between two __m128i variables, am I required to use an SSE instruction or can I use ==? If not, which SSE instruction should I use?

答:
Consider using an SSE4.1 instruction ptest:

```<code>if(_mm_testc_si128(v0, v1)) {if equal}

else {if not}
</code>```

ptest computes the bitwise AND of 128 bits (representing integer data) in a and mask, and return 1 if the result is zero, otherwise return 0.

Body:
Consider using an SSE4.1 instruction ptest:

if(_mm_testc_si128(v0, v1)) {if equal}

else {if not}

ptest computes the bitwise AND of 128 bits (representing integer data) in a and mask, and return 1 if the result is zero, otherwise return 0.


问:
Pagination on large data sets? – Abort count(*) after a certain time
We use the following pagination technique here:

get count(*) of given filter

get first 25 records of given filter

-> render some pagination links on the page

This works pretty well as long as count(*) is reasonable fast. In our case the data size has grown to a point where a non-indexd query (although most stuff is covered by indices) takes more than a minute. So at this point the user waits for a mostly unimportant number (total records matching filter, number of pages). The first N records are often ready pretty fast.

Therefore I have two questions:

can I limit the count(*) to a certain number

or would it be possible to limit it by time? (no count() known after 20ms)

Or just in general: are there some easy ways to avoid that problem? We would like to keep the system as untouched as possible.

Database: Oracle 10g

Update

There are several scenarios

a) there's an index -> neither count(*) nor the actual select should be a problem

b) there's no index

count(*) is HUGE, and it takes ages to determine it -> rownum would help

count(*) is zero or very low, here a time limit would help. Or I could just dont do a count(*) if the result set is already below the page limit.

答: You could use 'where rownum < x' to limit the number of rows to count. And if you need to show to your user that you has more register, you could use x+1 in count just to see if there is more than x registers.</p>

ContentLicense: CC BY-SA 2.5


问:
JSoup HttpStatusException
I am trying to parse the html of the following URL using JSoup:

```<code>http://brickseek.com/walmart-inventory-checker/
</code>```

When i execute the program I am getting below exception. I am using jsoup-1.10.1.jar

```<code>Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=http://brickseek.com/walmart-inventory-checker/
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:598)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:548)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:235)
    at Third.main(Third.java:22)
</code>```

Below is the program:

```<code>import java.io.IOException;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Third {

    public static void main(String[] args)  throws IOException {

        String uniqueSku ="44656182";
        String zipCode ="75160";

        Response response = Jsoup.connect("http://brickseek.com/walmart-inventory-checker/")
                .data("store_type","3", "sku", uniqueSku , "zip" , String.valueOf(zipCode) , "sort" , "distance")
                .userAgent("Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
                .method(Method.POST)
                .timeout(0)
                .execute();

                String rawHTML = response.body();
                Document parsedDocument = Jsoup.parse(rawHTML);
                Element bodyElement = parsedDocument.body();
                Elements inStockTableElement = bodyElement.getElementsByTag("table");

    }
}
</code>```

Any help would be greatly appreciated.

答:
The server probably has some sort of method to detect whether you are using a bot to scrape the page. Try changing your http header to something like this:

```<code>public class Util {
    public static Connection mask(Connection c) {
        return c.header("Host", "brickseek.com")
                .header("Connection", "keep-alive")
//              .header("Content-Length", ""+c.request().requestBody().length())
                .header("Cache-Control", "max-age=0")
                .header("Origin", "https://brickseek.com/")
                .header("Upgrade-Insecure-Requests", "1")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.48 Safari/537.36")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .referrer("http://brickseek.com/walmart-inventory-checker/")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Accept-Language", "en-US,en;q=0.8");
    }
}
</code>```

This header was copied exactly from the Google Chrome headers - usually, bots are detected by a different order of headers, or by different capitalizations of the headers. By copying Google Chrome exactly, you should be able to bypass it undetected.

Some bot detection algorithms count the number of requests per IP, and starts blocking above a certain threshold - which is why it still works for some people.

Title: JSoup HttpStatusException

Body:
I am trying to parse the html of the following URL using JSoup:

http://brickseek.com/walmart-inventory-checker/

When i execute the program I am getting below exception. I am using jsoup-1.10.1.jar

Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=http://brickseek.com/walmart-inventory-checker/
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:598)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:548)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:235)
    at Third.main(Third.java:22)

Below is the program:

import java.io.IOException;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Third {

    public static void main(String[] args)  throws IOException {

        String uniqueSku ="44656182";
        String zipCode ="75160";

        Response response = Jsoup.connect("http://brickseek.com/walmart-inventory-checker/")
                .data("store_type","3", "sku", uniqueSku , "zip" , String.valueOf(zipCode) , "sort" , "distance")
                .userAgent("Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
                .method(Method.POST)
                .timeout(0)
                .execute();

                String rawHTML = response.body();
                Document parsedDocument = Jsoup.parse(rawHTML);
                Element bodyElement = parsedDocument.body();
                Elements inStockTableElement = bodyElement.getElementsByTag("table");

    }
}

Any help would be greatly appreciated.

Body:
The server probably has some sort of method to detect whether you are using a bot to scrape the page. Try changing your http header to something like this:

public class Util {
    public static Connection mask(Connection c) {
        return c.header("Host", "brickseek.com")
                .header("Connection", "keep-alive")
//              .header("Content-Length", ""+c.request().requestBody().length())
                .header("Cache-Control", "max-age=0")
                .header("Origin", "https://brickseek.com/")
                .header("Upgrade-Insecure-Requests", "1")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.48 Safari/537.36")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .referrer("http://brickseek.com/walmart-inventory-checker/")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Accept-Language", "en-US,en;q=0.8");
    }
}

This header was copied exactly from the Google Chrome headers - usually, bots are detected by a different order of headers, or by different capitalizations of the headers. By copying Google Chrome exactly, you should be able to bypass it undetected.

Some bot detection algorithms count the number of requests per IP, and starts blocking above a certain threshold - which is why it still works for some people.


问:
Not able to apply display property on li element
i am a newbie to CSS,HTML and trying to understand lists.however something confuses me .As you can see below my HTML i am trying to create a drop down navigation bar.what i don't understand is why would display property won't work on a single li element.

  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>
.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden {display:none;}
.home:hover .hidden{display:block;}
.hidden a:hover{background-color: #f1f1f1;}</code>```

Home

  contact us

about

Investor

 what we do

```

答:
Here is the new css you should use:

```<code>.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden{display:none;}
.home:hover + .hidden{display:block;}
li:hover{background-color: #f1f1f1;}
</code>```

Then your html should look like this:

```<code><body>
<ul class="block1">
<li class="home"><a href="#">Home</a></li>

   <li class="hidden" >
  <a  href="#">contact us</a>
    </li>

  <li><a href="#">about</a></li>
  <li><a href="#">Investor</a></li>
  <li> <a href="#">what we do</a></li>
   </ul>

</body>
</code>```

Nothing too wrong with your html, just a mismatch
, and the css you want to look at this post: Using only CSS, show div on hover over

Here is the JSFiddle: Example of OP Code

Body:
i am a newbie to CSS,HTML and trying to understand lists.however something confuses me .As you can see below my HTML i am trying to create a drop down navigation bar.what i don't understand is why would display property won't work on a single li element.

.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden {display:none;}
.home:hover .hidden{display:block;}
.hidden a:hover{background-color: #f1f1f1;}

Home

  contact us

about

Investor

 what we do

Body:
Here is the new css you should use:

.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden{display:none;}
.home:hover + .hidden{display:block;}
li:hover{background-color: #f1f1f1;}

Then your html should look like this:

<body>
<ul class="block1">
<li class="home"><a href="#">Home</a></li>

   <li class="hidden" >
  <a  href="#">contact us</a>
    </li>

  <li><a href="#">about</a></li>
  <li><a href="#">Investor</a></li>
  <li> <a href="#">what we do</a></li>
   </ul>

</body>

Nothing too wrong with your html, just a mismatch <li>, and the css you want to look at this post: Using only CSS, show div on hover over <a>

Here is the JSFiddle: Example of OP Code


问:
Pipe stdout to command which itself needs to read from own stdin
I would like to get the stdout from a process into another process not using stdin, as that one is used for another purpose.

In short I want to accomplish something like that:

```<code>echo  "a" >&4
cat | grep -f /dev/fd/4
</code>```

I got it running using an file as source for file descriptor 4, but that is not what I want:

```<code># Variant 1
cat file | grep -f /dev/fd/4 4<pattern

# Variant 2
exec 4<pattern
cat | grep -f /dev/fd/4
exec 4<&-
</code>```

My best try is that, but I got the following error message:

```<code># Variant 3
cat | (
    echo  "a" >&4
    grep -f /dev/fd/4
) <&4
</code>```

Error message:

```<code>test.sh: line 5: 4: Bad file descriptor
</code>```

What is the best way to accomplish that?

答:
You don't need to use multiple streams to do this:

```<code>$ printf foo > pattern
$ printf '%s\n' foo bar | grep -f pattern
foo
</code>```

If instead of a static file you want to use the output of a command as the input to -f you can use a process substitution:

```<code>$ printf '%s\n' foo bar | grep -f <(echo foo)
foo
</code>```

Body:
I would like to get the stdout from a process into another process not using stdin, as that one is used for another purpose.

In short I want to accomplish something like that:

echo  "a" >&4
cat | grep -f /dev/fd/4

I got it running using an file as source for file descriptor 4, but that is not what I want:

# Variant 1
cat file | grep -f /dev/fd/4 4<pattern

# Variant 2
exec 4<pattern
cat | grep -f /dev/fd/4
exec 4<&-

My best try is that, but I got the following error message:

# Variant 3
cat | (
    echo  "a" >&4
    grep -f /dev/fd/4
) <&4

Error message:

test.sh: line 5: 4: Bad file descriptor

What is the best way to accomplish that?

Body:
You don't need to use multiple streams to do this:

$ printf foo > pattern
$ printf '%s\n' foo bar | grep -f pattern
foo

If instead of a static file you want to use the output of a command as the input to -f you can use a process substitution:

$ printf '%s\n' foo bar | grep -f <(echo foo)
foo


问:
Load data via SQL * Loader in IDENTITY column in Oracle 12c
I need to load data using SQL* Loader into Oracle table with GENERATE ALWAYS AS IDENTITY

```<code>CREATE TABLE tbl_identity
(
  col1 NUMBER(10,0) GENERATED ALWAYS AS IDENTITY(START WITH 7 INCREMENT BY 1)    NOT NULL,
  col2 VARCHAR2(20)
);
</code>```

But when I try to load data in this table, I get an error

```<code>ORA-32795: cannot insert into a generated always identity column
</code>```

Maybe there are any option in SQLLDR which skip IDENTITY for a while?

Or maybe there are any ideas how I can load data into GENERATED ALWAYS IDENTITY column using SQLLDR?

SQLLDR command

```<code>sqlldr userid=user/passw@TNS control=tbl_identity.ctl log=tbl_identity.log rows=1000 readsize=65535 bindsize=65535
</code>```

CTL-file

```<code>OPTIONS(direct=false)
LOAD DATA
INFILE 'tbl_identity.txt'
INTO TABLE tbl_identity
INSERT
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(col1,
 col2)
</code>```

答: Change your DDL from GENERATED ALWAYS to GENERATED BY DEFAULT

Body:
I need to load data using SQL* Loader into Oracle table with GENERATE ALWAYS AS IDENTITY

CREATE TABLE tbl_identity
(
  col1 NUMBER(10,0) GENERATED ALWAYS AS IDENTITY(START WITH 7 INCREMENT BY 1)    NOT NULL,
  col2 VARCHAR2(20)
);

But when I try to load data in this table, I get an error

ORA-32795: cannot insert into a generated always identity column

Maybe there are any option in SQLLDR which skip IDENTITY for a while?

Or maybe there are any ideas how I can load data into GENERATED ALWAYS IDENTITY column using SQLLDR?

SQLLDR command

sqlldr userid=user/passw@TNS control=tbl_identity.ctl log=tbl_identity.log rows=1000 readsize=65535 bindsize=65535

CTL-file

OPTIONS(direct=false)
LOAD DATA
INFILE 'tbl_identity.txt'
INTO TABLE tbl_identity
INSERT
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(col1,
 col2)


问:
Trying to update a dataframe
I have a dataframe (df) which looks like:

```<code>0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0
</code>```

I am trying to update a value (first row, third column) in the dataframe using:

```<code>for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1
</code>```

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

答:
Try to update the row using .loc or .iloc (depend on your needs).
<br> For example, in this case: </p>

```<code>if int(status) == 0:
    df.iloc[index]['3']='1'
</code>```

Title: Trying to update a dataframe

Body:
I have a dataframe (df) which looks like:

0   1                   2                       3
0   BBG.apples.S        BBG.XNGS.bananas.S      0
1   BBG.apples.S        BBG.XNGS.oranges.S      0
2   BBG.apples.S        BBG.XNGS.pairs.S        0
3   BBG.apples.S        BBG.XNGS.mango.S        0
4   BBG.apples.S        BBG.XNYS.mango.S        0
5   BBG.XNGS.bananas.S  BBG.XNGS.oranges.S      0
6   BBG.XNGS.bananas.S  BBG.XNGS.pairs.S        0
7   BBG.XNGS.bananas.S  BBG.XNGS.kiwi.S         0
8   BBG.XNGS.oranges.S  BBG.XNGS.pairs.S        0
9   BBG.XNGS.oranges.S  BBG.XNGS.kiwi.S         0
10  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
11  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
12  BBG.XNGS.peaches.S  BBG.XNGS.strawberrys.S  0
13  BBG.XNGS.peaches.S  BBG.XNGS.kiwi.S         0

I am trying to update a value (first row, third column) in the dataframe using:

for index, row in df.iterrows():

        status = row[3]

        if int(status) == 0:

            df[index]['3'] = 1

but when I print the dataframe out it remains unchanged.

What am I doing wrong?

Body:
Try to update the row using .loc or .iloc (depend on your needs).

 For example, in this case:

if int(status) == 0:
    df.iloc[index]['3']='1'


问:
Rmarkdown no longer working after 1.0.136 R Studio update
I recently updated my R Studio to version 1.0.136 and now have the following error when trying to knit documents:

I've run getOptions("repos") and would seem to be set to the appropriate CRAN mirror:

```<code>                       CRAN
"https://cran.rstudio.com/"
attr(,"RStudio")
[1] TRUE
</code>```

Running devtools::install_github("rstudio/rmarkdown") also does not solve the problem and the same error results.

Any thoughts or more information I can provide?

答:
I had a similar issue when I upgraded to 1.0.136. Specifically, rprojroot1.0 is not available.

In my case, installing the latest version of R (3.3.3) fixed the problem. (You have to point RStudio at the new version, in the "Tools...Global Options..." menu.)

I had been using version 3.1.2 and presumably the latest packages required for knitr needed newer. This discussion suggests as much: https://support.rstudio.com/hc/en-us/community/posts/115000740667-Rmarkdown-not-working-with-RStudio-Version-1-0-136

Body:
I recently updated my R Studio to version 1.0.136 and now have the following error when trying to knit documents:

I've run getOptions("repos") and would seem to be set to the appropriate CRAN mirror:

                       CRAN
"https://cran.rstudio.com/"
attr(,"RStudio")
[1] TRUE

Running devtools::install_github("rstudio/rmarkdown") also does not solve the problem and the same error results.

Any thoughts or more information I can provide?


问:
How to automate login to Google OAuth to access known user account
I am using google firebase oAuth in my app for login
My problem is that everytime i open the app it ask to login .
I want to automate using token service but i dont know how to and what to do.

```<code>private static int RC_SIGN_IN = 0 ;
private static String TAG = "LOGIN_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
Context context = LoginActivity.this;
public FirebaseAuth.AuthStateListener mAuthListener;
private EditText mEmailField,mPasswordField;
TextView register;
private String Email ;
Model_userDetails model_userDetails = new Model_userDetails(); ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();
    register = (TextView) findViewById(R.id.register);

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = firebaseAuth.getCurrentUser();
            if(user!=null) {

               // new HttpCall().checkGoogleEmail(context, Email);

            }

            else
                Log.d("AUTH","User logged out");
        }
    };

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();

    mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();

    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.email_sign_in_button).setOnClickListener(this);
    mEmailField = (EditText) findViewById(R.id.email);
    mPasswordField = (EditText) findViewById(R.id.password);
    register.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(LoginActivity.this,NewUserActivity.class));
        }
    });

}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
protected void onStop() {
    super.onStop();
    if (mAuthListener !=null)
        mAuth.removeAuthStateListener(mAuthListener);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==RC_SIGN_IN)
    {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        if (result.isSuccess())
        {
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
            Email = mAuth.getCurrentUser().getEmail();
            new HttpCall().checkGoogleEmail(context, Email);
        }
        else
            Log.d(TAG,"Google login failed ");

    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
    mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d("AUTH","sign in with credentials: complete "+ task.isSuccessful());
        }
    });
}

private void signIn()
{
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent,RC_SIGN_IN);
}

  private void emailSignIn()

{
    String email = mEmailField.getText().toString();
    String password = mPasswordField.getText().toString();
    if (TextUtils.isEmpty(email)||  TextUtils.isEmpty(password))
    {
        Toast.makeText(LoginActivity.this,"Fields are empty ",Toast.LENGTH_SHORT).show();
    }
    else
    {

        final ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this, "Please wait...", "Proccessing...", true);

        (mAuth.signInWithEmailAndPassword(email,password))
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        progressDialog.dismiss();

                        if (task.isSuccessful()) {
                            Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
                            Intent i = new Intent(LoginActivity.this, AccountActivity.class);
                            i.putExtra("Email", mAuth.getCurrentUser().getEmail());
                            startActivity(i);
                        } else {
                            Log.e("ERROR", task.getException().toString());
                            Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();

                        }
                    }
                });}

}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(TAG," Connection Failed");

}
</code>```

This is my code
please help me with this

答:
i got it myself . We have to call the new activity when checking if the user is login or not.</p>

```<code>mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

        FirebaseUser user = firebaseAuth.getCurrentUser();
        if(user!=null) {

           new HttpCall().checkGoogleEmail(context, Email);

        }

        else
            Log.d("AUTH","User logged out");
    }
};
</code>```

Body:
I am using google firebase oAuth in my app for login
My problem is that everytime i open the app it ask to login .
I want to automate using token service but i dont know how to and what to do.

private static int RC_SIGN_IN = 0 ;
private static String TAG = "LOGIN_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
Context context = LoginActivity.this;
public FirebaseAuth.AuthStateListener mAuthListener;
private EditText mEmailField,mPasswordField;
TextView register;
private String Email ;
Model_userDetails model_userDetails = new Model_userDetails(); ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();
    register = (TextView) findViewById(R.id.register);

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = firebaseAuth.getCurrentUser();
            if(user!=null) {

               // new HttpCall().checkGoogleEmail(context, Email);

            }

            else
                Log.d("AUTH","User logged out");
        }
    };

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();

    mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();

    findViewById(R.id.sign_in_button).setOnClickListener(this);
    findViewById(R.id.email_sign_in_button).setOnClickListener(this);
    mEmailField = (EditText) findViewById(R.id.email);
    mPasswordField = (EditText) findViewById(R.id.password);
    register.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(LoginActivity.this,NewUserActivity.class));
        }
    });

}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
protected void onStop() {
    super.onStop();
    if (mAuthListener !=null)
        mAuth.removeAuthStateListener(mAuthListener);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==RC_SIGN_IN)
    {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        if (result.isSuccess())
        {
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
            Email = mAuth.getCurrentUser().getEmail();
            new HttpCall().checkGoogleEmail(context, Email);
        }
        else
            Log.d(TAG,"Google login failed ");

    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
    mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d("AUTH","sign in with credentials: complete "+ task.isSuccessful());
        }
    });
}

private void signIn()
{
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent,RC_SIGN_IN);
}

  private void emailSignIn()

{
    String email = mEmailField.getText().toString();
    String password = mPasswordField.getText().toString();
    if (TextUtils.isEmpty(email)||  TextUtils.isEmpty(password))
    {
        Toast.makeText(LoginActivity.this,"Fields are empty ",Toast.LENGTH_SHORT).show();
    }
    else
    {

        final ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this, "Please wait...", "Proccessing...", true);

        (mAuth.signInWithEmailAndPassword(email,password))
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        progressDialog.dismiss();

                        if (task.isSuccessful()) {
                            Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
                            Intent i = new Intent(LoginActivity.this, AccountActivity.class);
                            i.putExtra("Email", mAuth.getCurrentUser().getEmail());
                            startActivity(i);
                        } else {
                            Log.e("ERROR", task.getException().toString());
                            Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();

                        }
                    }
                });}

}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(TAG," Connection Failed");

}

This is my code
please help me with this

Body:
i got it myself . We have to call the new activity when checking if the user is login or not.

mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

        FirebaseUser user = firebaseAuth.getCurrentUser();
        if(user!=null) {

           new HttpCall().checkGoogleEmail(context, Email);

        }

        else
            Log.d("AUTH","User logged out");
    }
};