问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
So my question is, what is the convention, when a program detects an
  error. Should it return a positive or a negative return code ?

You do not have the luxury (or responsibility) of making that choice.  From the point of view of C in general, your choices fall into three categories:

The exit status you specify is either 0 or EXIT_SUCCESS (which are not necessarily distinct).  This indicates successful completion.

The exit status you specify is EXIT_FAILURE.  This indicates unsuccessful completion.

The exit status you specify is anything else.

The result signaled to the host environment is implementation-defined in every case, though in the first it is one that communicates success, and in the second it is one that communicates failure.

Now, on Linux and other operating systems implementing POSIX exit() semantics, the implementation-definedness is standardized:

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available from wait() and waitpid();

(IEEE Std 1003.1-2008, 2016 Edition; emphasis added). Those are the traditional UNIX semantics; only the least-significant 8 bits of the exit status you specify matter, so the signedness is lost.  However, the current version of POSIX goes on to say:

the full value shall be available from waitid() and in the siginfo_t passed to a signal handler for SIGCHLD.

Thus, you can communicate a negative number to the parent process if it knows to look for one.  In general, however, it won't do.  In particular, if the parent process is the shell then it won't do.

My professor told me in UNIX/Linux allways to return a negative error code.

That sounds more like an instruction about function return codes for functions other than main(), but I don't see why you think our second guessing about what your professor meant would be more reliable than asking your professor for clarification directly.

But the errno-Codes are all positive integers.

Well, another thing to clarify with your professor would be whether he was giving you specific instructions about how he expects you to write functions for his class (more likely), or whether he was making an assertion about general C or POSIX convention (unlikely, because there are many POSIX functions of which it is not true), or something else.

Note well that C standard library functions do not return errno codes.  When they return a code indicating failure (often, but not always, a negative number), the programmer is obliged to consult the errno variable for a detailed reason -- the function return code generally does not carry that information.  Some functions standardized by POSIX but not C do return errno codes directly; obviously, these do not follow your professor's prescription.

Note also that errno values are for communicating between functions called by the same program, not for communicating with the program's environment.  They are not intended for use as program exit statuses, and in particular, there is no guarantee that their values fit in eight bits (see above).

Also the define-Statement of EXIT_FAILURE in is 1, a positive integer. So should my code look like this:

The value of EXIT_FAILURE is implementation-dependent.  You can therefore glean only implementation-specific insight from it.  As you can see, however, the general-purpose exit status indicating program failure in your implementation is 1.

On Linux and other POSIX(-ish) systems, you achieve best integration with the shell by choosing failure statuses between 1 and 125, as the shell designates special significance to statuses 126-255, and, of course, interprets status 0 as success.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most
  cases they return a negative error code on failure.

Again, no.  Errno codes are not meant for use as program exit codes, and only in rather special circumstances should you try to exit with a negative status.  A common convention is to write an informative error message to stderr (perror() serves exactly this purpose) and then exit with status 1 or (better, IMO) EXIT_FAILURE.

If you want to provide exit codes that describe the nature of the failure then it is up to you to define their values and significance on a per-program basis, remembering that for best compatibility you have only 1 - 125 to work with.

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

Body:
So my question is, what is the convention, when a program detects an
  error. Should it return a positive or a negative return code ?

You do not have the luxury (or responsibility) of making that choice.  From the point of view of C in general, your choices fall into three categories:

The exit status you specify is either 0 or EXIT_SUCCESS (which are not necessarily distinct).  This indicates successful completion.

The exit status you specify is EXIT_FAILURE.  This indicates unsuccessful completion.

The exit status you specify is anything else.

The result signaled to the host environment is implementation-defined in every case, though in the first it is one that communicates success, and in the second it is one that communicates failure.

Now, on Linux and other operating systems implementing POSIX exit() semantics, the implementation-definedness is standardized:

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available from wait() and waitpid();

(IEEE Std 1003.1-2008, 2016 Edition; emphasis added). Those are the traditional UNIX semantics; only the least-significant 8 bits of the exit status you specify matter, so the signedness is lost.  However, the current version of POSIX goes on to say:

the full value shall be available from waitid() and in the siginfo_t passed to a signal handler for SIGCHLD.

Thus, you can communicate a negative number to the parent process if it knows to look for one.  In general, however, it won't do.  In particular, if the parent process is the shell then it won't do.

My professor told me in UNIX/Linux allways to return a negative error code.

That sounds more like an instruction about function return codes for functions other than main(), but I don't see why you think our second guessing about what your professor meant would be more reliable than asking your professor for clarification directly.

But the errno-Codes are all positive integers.

Well, another thing to clarify with your professor would be whether he was giving you specific instructions about how he expects you to write functions for his class (more likely), or whether he was making an assertion about general C or POSIX convention (unlikely, because there are many POSIX functions of which it is not true), or something else.

Note well that C standard library functions do not return errno codes.  When they return a code indicating failure (often, but not always, a negative number), the programmer is obliged to consult the errno variable for a detailed reason -- the function return code generally does not carry that information.  Some functions standardized by POSIX but not C do return errno codes directly; obviously, these do not follow your professor's prescription.

Note also that errno values are for communicating between functions called by the same program, not for communicating with the program's environment.  They are not intended for use as program exit statuses, and in particular, there is no guarantee that their values fit in eight bits (see above).

Also the define-Statement of EXIT_FAILURE in is 1, a positive integer. So should my code look like this:

The value of EXIT_FAILURE is implementation-dependent.  You can therefore glean only implementation-specific insight from it.  As you can see, however, the general-purpose exit status indicating program failure in your implementation is 1.

On Linux and other POSIX(-ish) systems, you achieve best integration with the shell by choosing failure statuses between 1 and 125, as the shell designates special significance to statuses 126-255, and, of course, interprets status 0 as success.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most
  cases they return a negative error code on failure.

Again, no.  Errno codes are not meant for use as program exit codes, and only in rather special circumstances should you try to exit with a negative status.  A common convention is to write an informative error message to stderr (perror() serves exactly this purpose) and then exit with status 1 or (better, IMO) EXIT_FAILURE.

If you want to provide exit codes that describe the nature of the failure then it is up to you to define their values and significance on a per-program basis, remembering that for best compatibility you have only 1 - 125 to work with.


来源: stackexchange

问:
django DEBUG=False still runs in debug mode
I'm having issues setting my DEBUG = False on my deployed server (on heroku).

I don't believe I've seen this before, but setting debug to false is not getting rid of debug mode for my project. This means that when there are 500 errors it shows the error, and 404 errors are showing all my urls.

What's strange is that when i log into the server and run get the setting value from django.conf import settings settings.DEBUG it shows as False, which is what I set it to for the production server. TEMPLATE_DEBUG is also set to False.

I don't know I've ever seen this before where DEBUG = False but it's still acting in debug mode. Any ideas?

EDIT:

Thought I'd put this little note too because it's very common for people to be getting 500 or 400 errors when switching debug to False. I am not getting any errors, my project is just acting like it's in DEBUG mode.

```<code># settings/dev.py
from .base import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG

if not DEBUG:
    ALLOWED_HOSTS = ['localhost']

SECRET_KEY = 'localsecret1234123412341234'

# settings/prod.py
from .base import *

import dj_database_url, os

DEBUG = os.environ.get("DEBUG", False)
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = ['mydomain.com']
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

DATABASES = {}
DATABASES['default'] =  dj_database_url.config()
</code>```

答:
As a note for others: I had the same problem; I configured my production website on a VM with gunicorn and nginx, following the tutorial for ubuntu 16.04 from the digital ocean documentation.

I wasn't able to turn off the debug mode, even when restarting the nginx systemd's service: the solution was to restart also the gunicorn service:

# systemctl restart nginx gunicorn
```

ContentLicense: CC BY-SA 3.0

Body:
I'm having issues setting my DEBUG = False on my deployed server (on heroku).

I don't believe I've seen this before, but setting debug to false is not getting rid of debug mode for my project. This means that when there are 500 errors it shows the error, and 404 errors are showing all my urls.

What's strange is that when i log into the server and run get the setting value from django.conf import settings settings.DEBUG it shows as False, which is what I set it to for the production server. TEMPLATE_DEBUG is also set to False.

I don't know I've ever seen this before where DEBUG = False but it's still acting in debug mode. Any ideas?

EDIT:

Thought I'd put this little note too because it's very common for people to be getting 500 or 400 errors when switching debug to False. I am not getting any errors, my project is just acting like it's in DEBUG mode.

# settings/dev.py
from .base import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG

if not DEBUG:
    ALLOWED_HOSTS = ['localhost']

SECRET_KEY = 'localsecret1234123412341234'

# settings/prod.py
from .base import *

import dj_database_url, os

DEBUG = os.environ.get("DEBUG", False)
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = ['mydomain.com']
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

DATABASES = {}
DATABASES['default'] =  dj_database_url.config()


问:
How to implement Lexical Analysis in Javascript
Hey folks, thanks for reading

I am currently attempting to do a Google-style calculator. You input a string, it determines if it can be calculated and returns the result.

I began slowly with the basics : + - / * and parenthesis handling.

I am willing to improve the calculator over time, and having learned a bit about lexical analysis a while ago, I built a list of tokens and associated regular expression patterns.

This kind of work is easily applicable with languages such as Lex and Yacc, except I am developping a Javascript-only application.

I tried to transcript the idea into Javascript but I can't figure out how to handle everything in a clean and beautiful way, especially nested parenthesis.

Analysis

Let's define what a calculator query is:

```<code>// NON TERMINAL EXPRESSIONS //
query     -> statement
query     -> ε // means end of query

statement -> statement operator statement
statement -> ( statement )
statement -> prefix statement
statement -> number

number    -> integer
number    -> float

// TERMINAL EXPRESSIONS //
operator  -> [+*/%^-]

prefix    -> -

integer   -> [0-9]+

float     -> [0-9]+[.,][0-9]+
</code>```

Javascript

Lexical Analysis consists in verifying there is nothing that doesn't look like one of the terminal expressions : operator, prefixes, integer and float. Which can be shortened to one regular expression:

(I added spaces to make it more readable)

```<code>var calcPat =
/^ (\s*
    ( ([+/*%^-]) | ([0-9]+) | ([0-9]+[.,][0-9]+) | (\() | (\)) )
)+ \s* $/;
</code>```

If this test passes, query is lexically correct and needs to be grammar-checked to determine if it can be calculated. This is the tricky part

I am not going to paste code because it is not clean nor easily understandable, but I am going to explain the process I followed and why I'm stuck:

I created a method called isStatement(string) that's supposed to call itself recursively. The main idea is to split the string into 'potential' statements and check if they really are statements and form one altogether.

Process is the following:

-If the first two tokens are a number followed by an operator:

-Then,

-- If the remaining is just one token and it is a number:

--- Then this is a statement.

--- Else, check if the remaining tokens form a statement (recursive call)

-Else, If the first token is a parenthesis

-Then, Find matching closing parenthesis and check if what's inside is a statement (recursion)

-- Also check if there is something after closing parenthesis and if it forms a statement when associated with the parenthesis structure.

What's the problem ?

My problem is that I cannot find matching parenthesis when there is nested structures. How can I do that ? Also, as you can see, this is not a particurlarly generic and clean grammar-checking algorithm. Do you have any idea to improve this pattern ?

Thank you so much for having taken the time to read everything.
Gael

(PS: As you probably noticed, I am not a native english speaker ! Sorry for mistakes and all !)

答:
You've got the right idea about what lexical analysis is, but you seem to have gotten confused about the distinction between the token grammar and the language grammar.  Those are two different things.

The token grammar is the set of patterns (usually regular expressions) that describe the tokens for the language to be parsed. The regular expressions are expressions over a character set.

The language grammar (or target grammar, I suppose) is the grammar for the language you want to parse. This grammar is expressed in terms of tokens.

You cannot write a regular expression to parse algebraic notation. You just can't.  You can write a grammar for it, but it's not a regular grammar. What you want to do is recognize separate tokens, which in your case could be done with a regular expression somewhat like what you've got.  The trick is that you're not really applying that expression to the overall sentence to be parsed. Instead, you want to match a token at the current point in the sentence.

Now, because you've got Javascript regular expressions to work with, you could come up with a regular expression designed to match a string of tokens. The trick with that will be coming up with a way to identify which token was matched out of the list of possibilities. The Javascript regex engine can give you back arrays of groups, so maybe you could build something on top of that.

edit — I'm trying to work out how you could put together a (somewhat) general-purpose tokenizer builder, starting from a list of separate regular expressions (one for each token).  It's possibly not very complicated, and it'd be pretty fun to have around.

ContentLicense: CC BY-SA 2.5

Body:
Hey folks, thanks for reading

I am currently attempting to do a Google-style calculator. You input a string, it determines if it can be calculated and returns the result.

I began slowly with the basics : + - / * and parenthesis handling.

I am willing to improve the calculator over time, and having learned a bit about lexical analysis a while ago, I built a list of tokens and associated regular expression patterns.

This kind of work is easily applicable with languages such as Lex and Yacc, except I am developping a Javascript-only application.

I tried to transcript the idea into Javascript but I can't figure out how to handle everything in a clean and beautiful way, especially nested parenthesis.

Analysis

Let's define what a calculator query is:

// NON TERMINAL EXPRESSIONS //
query     -> statement
query     -> ε // means end of query

statement -> statement operator statement
statement -> ( statement )
statement -> prefix statement
statement -> number

number    -> integer
number    -> float

// TERMINAL EXPRESSIONS //
operator  -> [+*/%^-]

prefix    -> -

integer   -> [0-9]+

float     -> [0-9]+[.,][0-9]+

Javascript

Lexical Analysis consists in verifying there is nothing that doesn't look like one of the terminal expressions : operator, prefixes, integer and float. Which can be shortened to one regular expression:

(I added spaces to make it more readable)

var calcPat =
/^ (\s*
    ( ([+/*%^-]) | ([0-9]+) | ([0-9]+[.,][0-9]+) | (\() | (\)) )
)+ \s* $/;

If this test passes, query is lexically correct and needs to be grammar-checked to determine if it can be calculated. This is the tricky part

I am not going to paste code because it is not clean nor easily understandable, but I am going to explain the process I followed and why I'm stuck:

I created a method called isStatement(string) that's supposed to call itself recursively. The main idea is to split the string into 'potential' statements and check if they really are statements and form one altogether.

Process is the following:

-If the first two tokens are a number followed by an operator:

-Then,

-- If the remaining is just one token and it is a number:

--- Then this is a statement.

--- Else, check if the remaining tokens form a statement (recursive call)

-Else, If the first token is a parenthesis

-Then, Find matching closing parenthesis and check if what's inside is a statement (recursion)

-- Also check if there is something after closing parenthesis and if it forms a statement when associated with the parenthesis structure.

What's the problem ?

My problem is that I cannot find matching parenthesis when there is nested structures. How can I do that ? Also, as you can see, this is not a particurlarly generic and clean grammar-checking algorithm. Do you have any idea to improve this pattern ?

Thank you so much for having taken the time to read everything.
Gael

(PS: As you probably noticed, I am not a native english speaker ! Sorry for mistakes and all !)


问:
Input Layout toggle hintText color change
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

```<code>  <style name="labelcolor" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">#868686</item>
    <item name="android:textSize">16sp</item>
    <item name="android:paddingTop">5sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">#0ea3ff</item>
    <item name="colorControlNormal">#0ea3ffr</item>
    <item name="colorControlActivated">#0ea3ff</item>
</style>
</code>```

please help me how can i solve this issues.

答:
```<code><style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
                <!--EditText hint color-->
                <item name="android:textColorHint">@color/default_app_white</item>             <!-- TextInputLayout text color-->
                <item name="colorControlActivated">@color/default_app_green</item>
                <!-- EditText line color when EditText on-focus-->
                <item name="colorControlHighlight">@color/default_app_green</item>
                <!-- EditText line color when EditText  in un-focus-->
                <item name="colorControlNormal">@color/default_app_white</item>
            </style>
 <!-- In your style.xml file -->
</code>```

<p>try this one but it affects your whole application </p>

Body:
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

please help me how can i solve this issues.

Body:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
                <!--EditText hint color-->
                <item name="android:textColorHint">@color/default_app_white</item>             <!-- TextInputLayout text color-->
                <item name="colorControlActivated">@color/default_app_green</item>
                <!-- EditText line color when EditText on-focus-->
                <item name="colorControlHighlight">@color/default_app_green</item>
                <!-- EditText line color when EditText  in un-focus-->
                <item name="colorControlNormal">@color/default_app_white</item>
            </style>
 <!-- In your style.xml file -->

try this one but it affects your whole application


问:
Ruby on Rails using incorrect layout partial
I have a RoR app that has some bits under /admin/ which uses it's own styles and layouts to the root.

I have created a controller and view under /admin/active_vulnerabilities but this is using the layouts for root not the admin layouts and CSS etc

I did originally create the controller and view under root but I have moved it under /admin/ and the routes work fine but it seems to have cached the layouts and CSS for the root and not updating to the admin ones. I have tried to use rails assets:precompile but its still pulling the incorrect bits through.

答:
Call layout :admin from /admin/active_vulnerabilities controller like:

```<code>class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :admin

  ...
end
</code>```

And place your admin layout in app/views/layouts/admin file

Body:
Call layout :admin from /admin/active_vulnerabilities controller like:

class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :admin

  ...
end

And place your admin layout in app/views/layouts/admin file


问:
Getting Authentication failed error on firebase facebook login
I am developing firebase demo app where I added firebase facebook as well as google login, So google working fine but whenever I am trying to login using facebook then it will throw Authentication failed at runtime so I will try all the stackOverflow solutions but It didn't work, So anybody knows how to solve this?

Below is my Login code:-

```<code>public class SplashScreen extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    //constant values
    public static final String USER_NAME="com.gaurav.javascripttutorial.username";
    public static final String USER_IMAGE="com.gaurav.javascripttutorial.userimage";
    public static final String USER_ID="com.gaurav.javascripttutorial.userid";

    int RC_SIGN_IN = 1000;

    //Firebase
    FirebaseAuth mAuth;
    GoogleApiClient mGoogleApiClient;
    CallbackManager mCallbackManager;

    //views
    private SignInButton googleLogin;
    private LoginButton facebookLogin;
    private ProgressDialog dialog;

    //Shared Preference
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.main_splashscreen);
        googleLogin = (SignInButton) findViewById(R.id.googleLogin);
        facebookLogin = (LoginButton) findViewById(R.id.facebookLogin);

        pref = this.getSharedPreferences("user",0);
        editor = pref.edit();

        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading, Please wait....");

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

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

        //Facebook configuration
        mCallbackManager = CallbackManager.Factory.create();

        mAuth = FirebaseAuth.getInstance();

        if (mAuth.getCurrentUser()!= null){
            FirebaseUser user = mAuth.getCurrentUser();
            editor.clear();
            editor.putString(USER_NAME,user.getDisplayName());
            editor.putString(USER_ID, user.getUid());
            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
            editor.commit();
            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        googleLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                googleSignIn();
            }
        });
        facebookLogin.setReadPermissions("email","public_profile");
        facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Toast.makeText(SplashScreen.this, "Facebook login cancel.", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(SplashScreen.this, "Something went wrong! Please try again", Toast.LENGTH_LONG).show();
            }
        });
    }

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

    private void handleFacebookAccessToken(AccessToken token){
        final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(SplashScreen.this, "Authentication failed.", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account){
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        }else {
                            Toast.makeText(SplashScreen.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN){
            if (resultCode == RESULT_OK) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                dialog.show();
                if (result.isSuccess()) {
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);

                } else {
                    Log.d("Status", String.valueOf(result.getStatus().getStatusCode()));
                    Toast.makeText(this, "SignIn failed", Toast.LENGTH_SHORT).show();
                }
            }else {
                Toast.makeText(this, "Result Code error", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_LONG).show();

    }
}
</code>```

答:
Assuming you have everything configured correctly (otherwise, read the docs), this is working fine for me (Kotlin code, sorry. If you need Java, just make the translation):

My Activity extends AppCompatActivity:

```<code>class ActivityLogin : AppCompatActivity() {

    private val callbackManager: CallbackManager = CallbackManager.Factory.create()
    private val mAuth: FirebaseAuth = FirebaseAuth.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_splashscreen)

        loginButton.setReadPermissions("email", "public_profile")
        loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(result: LoginResult) {
                handleFacebookAccessToken(result.accessToken)
            }

            override fun onCancel() {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication canceled.", Toast.LENGTH_SHORT).show()
            }

            override fun onError(error: FacebookException?) {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication failed.", Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleFacebookAccessToken(token: AccessToken) {
        val credential = FacebookAuthProvider.getCredential(token.token)
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        val mainIntent = Intent(this@ActivityLogin, ActivityFeed::class.java)
                        startActivity(mainIntent)
                        finish()
                    } else {
                        Toast.makeText(this@ActivityLogin, "Firebase Authentication failed.", Toast.LENGTH_SHORT).show()
                    }
                }
    }
}
</code>```

As you can see, there is no need to call

```<code>FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
FacebookSdk.sdkInitialize(getApplicationContext());
</code>```

during your activity's onCreate().

Body:
I am developing firebase demo app where I added firebase facebook as well as google login, So google working fine but whenever I am trying to login using facebook then it will throw Authentication failed at runtime so I will try all the stackOverflow solutions but It didn't work, So anybody knows how to solve this?

Below is my Login code:-

public class SplashScreen extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    //constant values
    public static final String USER_NAME="com.gaurav.javascripttutorial.username";
    public static final String USER_IMAGE="com.gaurav.javascripttutorial.userimage";
    public static final String USER_ID="com.gaurav.javascripttutorial.userid";

    int RC_SIGN_IN = 1000;

    //Firebase
    FirebaseAuth mAuth;
    GoogleApiClient mGoogleApiClient;
    CallbackManager mCallbackManager;

    //views
    private SignInButton googleLogin;
    private LoginButton facebookLogin;
    private ProgressDialog dialog;

    //Shared Preference
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.main_splashscreen);
        googleLogin = (SignInButton) findViewById(R.id.googleLogin);
        facebookLogin = (LoginButton) findViewById(R.id.facebookLogin);

        pref = this.getSharedPreferences("user",0);
        editor = pref.edit();

        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading, Please wait....");

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

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

        //Facebook configuration
        mCallbackManager = CallbackManager.Factory.create();

        mAuth = FirebaseAuth.getInstance();

        if (mAuth.getCurrentUser()!= null){
            FirebaseUser user = mAuth.getCurrentUser();
            editor.clear();
            editor.putString(USER_NAME,user.getDisplayName());
            editor.putString(USER_ID, user.getUid());
            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
            editor.commit();
            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        googleLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                googleSignIn();
            }
        });
        facebookLogin.setReadPermissions("email","public_profile");
        facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Toast.makeText(SplashScreen.this, "Facebook login cancel.", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(SplashScreen.this, "Something went wrong! Please try again", Toast.LENGTH_LONG).show();
            }
        });
    }

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

    private void handleFacebookAccessToken(AccessToken token){
        final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(SplashScreen.this, "Authentication failed.", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account){
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        }else {
                            Toast.makeText(SplashScreen.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN){
            if (resultCode == RESULT_OK) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                dialog.show();
                if (result.isSuccess()) {
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);

                } else {
                    Log.d("Status", String.valueOf(result.getStatus().getStatusCode()));
                    Toast.makeText(this, "SignIn failed", Toast.LENGTH_SHORT).show();
                }
            }else {
                Toast.makeText(this, "Result Code error", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_LONG).show();

    }
}

Body:
Assuming you have everything configured correctly (otherwise, read the docs), this is working fine for me (Kotlin code, sorry. If you need Java, just make the translation):

My Activity extends AppCompatActivity:

class ActivityLogin : AppCompatActivity() {

    private val callbackManager: CallbackManager = CallbackManager.Factory.create()
    private val mAuth: FirebaseAuth = FirebaseAuth.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_splashscreen)

        loginButton.setReadPermissions("email", "public_profile")
        loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(result: LoginResult) {
                handleFacebookAccessToken(result.accessToken)
            }

            override fun onCancel() {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication canceled.", Toast.LENGTH_SHORT).show()
            }

            override fun onError(error: FacebookException?) {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication failed.", Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleFacebookAccessToken(token: AccessToken) {
        val credential = FacebookAuthProvider.getCredential(token.token)
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        val mainIntent = Intent(this@ActivityLogin, ActivityFeed::class.java)
                        startActivity(mainIntent)
                        finish()
                    } else {
                        Toast.makeText(this@ActivityLogin, "Firebase Authentication failed.", Toast.LENGTH_SHORT).show()
                    }
                }
    }
}

As you can see, there is no need to call

FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
FacebookSdk.sdkInitialize(getApplicationContext());

during your activity's onCreate().


问:
How to create dotted rounded ImageView?
I want create dotted rounded ImageView. I think I should use Paint but it does not work.

```<code>private Paint dashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{
            5, 5
    }, 0.0f));
    dashPaint.setStrokeWidth(Easify.dp(1.2f));
}
</code>```

答:
You could set this background resource to your ImageView:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <solid android:color="#ffffff" />
            <stroke
                android:dashGap="10dp"
                android:dashWidth="10dp"
                android:width="1dp"
                android:color="#979797" />
            <padding
                android:bottom="5dp"
                android:left="5dp"
                android:right="5dp"
                android:top="5dp" />
           <corners
            android:bottomRightRadius="6dp"
            android:bottomLeftRadius="6dp"
            android:topLeftRadius="6dp"
            android:topRightRadius="6dp"/>
        </shape>
    </item>
</layer-list>
</code>```

Title: How to create dotted rounded ImageView?

Body:
I want create dotted rounded ImageView. I think I should use Paint but it does not work.

private Paint dashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
    dashPaint.setStyle(Paint.Style.STROKE);
    dashPaint.setColor(Color.WHITE);
    dashPaint.setAlpha(120);
    dashPaint.setPathEffect(new DashPathEffect(new float[]{
            5, 5
    }, 0.0f));
    dashPaint.setStrokeWidth(Easify.dp(1.2f));
}

Body:
You could set this background resource to your ImageView:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <solid android:color="#ffffff" />
            <stroke
                android:dashGap="10dp"
                android:dashWidth="10dp"
                android:width="1dp"
                android:color="#979797" />
            <padding
                android:bottom="5dp"
                android:left="5dp"
                android:right="5dp"
                android:top="5dp" />
           <corners
            android:bottomRightRadius="6dp"
            android:bottomLeftRadius="6dp"
            android:topLeftRadius="6dp"
            android:topRightRadius="6dp"/>
        </shape>
    </item>
</layer-list>


问:
Error 'this_thread': the symbol to the left of a '::' must be a type?
My headers:

```<code>#include <chrono>
#include <thread>
#include <iostream>
#include <string>
#include <fstream>
#include "include\curses.h"
</code>```

My code problem:

```<code>        std::this_thread::sleep_for(std::chrono::milliseconds(500));
</code>```

My error:

error C3083: 'this_thread': the symbol to the left of a '::' must be a type

It just makes no sense to me!? Every header needed is added. Intellisense (I'm on VS2012) detects the references and parameters. It just won't compile.

Other related errors

*error C2039: 'sleep_for' : is not a member of 'std'*

*error C3861: 'sleep_for': identifier not found*

答:
To avoid that someone else has to dig through their code wondering why on earth the compiler yields similar errors:

Make sure that all the headers you include properly close their namespace scopes.

Example:

abc.h

```<code>namespace abc
{
    int foo();
// oops, you forgot to close that scope
</code>```

abc.cpp

```<code>#include "abc.h"
namespace abc
{
  int foo() { /* ... */ } // This now implements ::abc::abc::foo()
}
</code>```

Body:
My headers:

#include <chrono>
#include <thread>
#include <iostream>
#include <string>
#include <fstream>
#include "include\curses.h"

My code problem:

        std::this_thread::sleep_for(std::chrono::milliseconds(500));

My error:

error C3083: 'this_thread': the symbol to the left of a '::' must be a type

It just makes no sense to me!? Every header needed is added. Intellisense (I'm on VS2012) detects the references and parameters. It just won't compile.

Other related errors

*error C2039: 'sleep_for' : is not a member of 'std'*

*error C3861: 'sleep_for': identifier not found*

Body:
To avoid that someone else has to dig through their code wondering why on earth the compiler yields similar errors:

Make sure that all the headers you include properly close their namespace scopes.

Example:

abc.h

namespace abc
{
    int foo();
// oops, you forgot to close that scope

abc.cpp

#include "abc.h"
namespace abc
{
  int foo() { /* ... */ } // This now implements ::abc::abc::foo()
}


问:
Kamon error with configuration 'requires-aspectj'
I'm adding kamonto my standalone akka application and i'm getting this error:

com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'requires-aspectj' error at Kamon.start().

This is the relative content of application.conf.

```<code>{
...
  modules {
    kamon-akka {
      auto-start = no
    }
    kamon-statsd {
      auto-start = no
    }
    kamon-system-metric {
      auto-start = no
      requires-aspectj = no
      extension-id = "kamon.system.SystemMetrics"
    }
  }
}
</code>```

application.conf: 36: requires-aspectj has type STRING rather than OBJECT

However, when I include the asked property

```<code>{
  modules {
    requires-aspectj = no
  ...
  }
}
</code>```

I get this error: application.conf: 36: requires-aspectj has type STRING rather than OBJECT

If i remove Kamon.start() my application starts as usual

This is an extract of the my build.sbt:

```<code>lazy val root = (project in file("."))
  .settings(name := "kamon-akka")
  .settings(Seq(scalaVersion := "2.11.8"))
  .settings(libraryDependencies ++= Seq(
    akka.Http,
    akka.slf4jApi,
    akka.akkaSlf4j,
    kamon.Core,
    kamon.Akka,
    kamon.LogReporter,
    kamon.SystemMetrics,
    aspectj.aspectjtools,
    aspectj.aspectjweaver,
    aspectj.aspectjrt
  ))
  .settings(aspectjSettings: _*)
</code>```

PS:

kamon = 0.6.7

aspectj = 1.8.9

sbt 0.13.13

scala 2.12.3

I'm also using this plugin addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.4")

any ideas?

答:
First, your application.conf looks strange in that it doesn't appear to have a kamon namespace. It should look like the following (take note of the first line):

kamon {
  ...
  modules {
    kamon-akka {
      ...
    }
    kamon-statsd {
      ...
    }
    kamon-system-metrics {
      ...
    }
  }
}
```

<p>Second, since you're using the <code>sbt-aspectj</code> plugin, add the following to your <code>build.sbt</code> (source: http://kamon.io/documentation/get-started/):</p>

<pre class="lang-scala prettyprint-override"><code>import com.typesafe.sbt.SbtAspectj._

// Bring the sbt-aspectj settings into this build
aspectjSettings

// Here we are effectively adding the `-javaagent` JVM startup
// option with the location of the AspectJ Weaver provided by
// the sbt-aspectj plugin.
javaOptions in run <++= AspectjKeys.weaverOptions in Aspectj

// We need to ensure that the JVM is forked for the
// AspectJ Weaver to kick in properly and do it's magic.
fork in run := true
</code>```

Body:
I'm adding kamonto my standalone akka application and i'm getting this error:

com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'requires-aspectj' error at Kamon.start().

This is the relative content of application.conf.

{
...
  modules {
    kamon-akka {
      auto-start = no
    }
    kamon-statsd {
      auto-start = no
    }
    kamon-system-metric {
      auto-start = no
      requires-aspectj = no
      extension-id = "kamon.system.SystemMetrics"
    }
  }
}

application.conf: 36: requires-aspectj has type STRING rather than OBJECT

However, when I include the asked property

{
  modules {
    requires-aspectj = no
  ...
  }
}

I get this error: application.conf: 36: requires-aspectj has type STRING rather than OBJECT

If i remove Kamon.start() my application starts as usual

This is an extract of the my build.sbt:

lazy val root = (project in file("."))
  .settings(name := "kamon-akka")
  .settings(Seq(scalaVersion := "2.11.8"))
  .settings(libraryDependencies ++= Seq(
    akka.Http,
    akka.slf4jApi,
    akka.akkaSlf4j,
    kamon.Core,
    kamon.Akka,
    kamon.LogReporter,
    kamon.SystemMetrics,
    aspectj.aspectjtools,
    aspectj.aspectjweaver,
    aspectj.aspectjrt
  ))
  .settings(aspectjSettings: _*)

PS:

kamon = 0.6.7

aspectj = 1.8.9

sbt 0.13.13

scala 2.12.3

I'm also using this plugin addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.4")

any ideas?

Body:
First, your application.conf looks strange in that it doesn't appear to have a kamon namespace. It should look like the following (take note of the first line):

kamon {
  ...
  modules {
    kamon-akka {
      ...
    }
    kamon-statsd {
      ...
    }
    kamon-system-metrics {
      ...
    }
  }
}

Second, since you're using the sbt-aspectj plugin, add the following to your build.sbt (source: http://kamon.io/documentation/get-started/):

import com.typesafe.sbt.SbtAspectj._

// Bring the sbt-aspectj settings into this build
aspectjSettings

// Here we are effectively adding the `-javaagent` JVM startup
// option with the location of the AspectJ Weaver provided by
// the sbt-aspectj plugin.
javaOptions in run <++= AspectjKeys.weaverOptions in Aspectj

// We need to ensure that the JVM is forked for the
// AspectJ Weaver to kick in properly and do it's magic.
fork in run := true


问:
Phonegap app can not connect to database on mobile
I have been been working on an app in phonegap and make login and register with JavaScript and ajax call. </p>

<p>So I tested it on Google Chrome and it works perfect, connecting on server (mysql) and inserting data etc... So I decide to build app to test it on mobile (android), and it just not responding when I click on register or login button.
Is there some code or file which I need to import ? </p>

答: Check the url you are connecting with in the ajax call, if its a full path</p>

Body:
I have been been working on an app in phonegap and make login and register with JavaScript and ajax call.

So I tested it on Google Chrome and it works perfect, connecting on server (mysql) and inserting data etc... So I decide to build app to test it on mobile (android), and it just not responding when I click on register or login button.
Is there some code or file which I need to import ?


问:
Using BufferedWriter to get input from the user and write it to a file
I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)

```<code>package bufferedreader;
import java.io.*;
import java.util.Scanner;

public class BufferedReader {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
   writeToFile("morescores");
   processFile("morescores");
}

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
    int score = 1;
   while (true) {
   Scanner reader = new Scanner(System.in);
        System.out.print ("Enter a number: ");
       score = reader.nextInt();
        if (score < 0) {
            break;
       } else {
          outputWriter.write(score);
          outputWriter.newLine();
    }
    }
   outputWriter.flush();
   outputWriter.close();
}

public static void processFile2 (String filename) throws IOException {
    java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
    String line;
    while ((line = inputReader.readLine()) != null) {
        System.out.println (line);
    }
    inputReader.close();
}

}
</code>```

UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string.  I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value

答:
If you pass int value to the write method of BufferedWriter class, then it will be consider as character instead of number, therefore with the current code you have written whatever positive number you are providing will get converted to valid char value and then it will be written into the file.
In order to achieve what you are asking for you need to convert your int value to string before writing it to file and to do that you can use any of the below methods :

```<code>String.valueOf(score)
Integer.toString(score)
</code>```

Body:
I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)

package bufferedreader;
import java.io.*;
import java.util.Scanner;

public class BufferedReader {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
   writeToFile("morescores");
   processFile("morescores");
}

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
    int score = 1;
   while (true) {
   Scanner reader = new Scanner(System.in);
        System.out.print ("Enter a number: ");
       score = reader.nextInt();
        if (score < 0) {
            break;
       } else {
          outputWriter.write(score);
          outputWriter.newLine();
    }
    }
   outputWriter.flush();
   outputWriter.close();
}

public static void processFile2 (String filename) throws IOException {
    java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
    String line;
    while ((line = inputReader.readLine()) != null) {
        System.out.println (line);
    }
    inputReader.close();
}

}

UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string.  I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value

Body:
If you pass int value to the write method of BufferedWriter class, then it will be consider as character instead of number, therefore with the current code you have written whatever positive number you are providing will get converted to valid char value and then it will be written into the file.
In order to achieve what you are asking for you need to convert your int value to string before writing it to file and to do that you can use any of the below methods :

String.valueOf(score)
Integer.toString(score)


问:
Will VPC Support for Amazon Elasticsearch Service Domains Configure Using cloudformation
I am configuring AWS Elastic Search Cluster using cloudformation but i am unable to use VPC enable cluster using CFN template so my question is this is possible configuration if yes then can someone provided me link for that.

http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html

答: It is currently not supported; support will come soon according to the docs. </p>


问:
NLP convert bracket notation to dependency tree
Given a bracket notation  of constituent words, is there a way to convert it into its dependency tree?

```<code>[S [NP [Proper-Noun John]][VP [Verb saw][NP [Proper-Noun Mary]][PP [Preposition with][NP [Determiner a][Noun telescope]]]]]
</code>```

into

```<code>nsubj(saw-2, John-1)
root(ROOT-0, saw-2)
dobj(saw-2, Mary-3)
case(telescope-6, with-4)
det(telescope-6, a-5)
nmod(saw-2, telescope-6)
</code>```

答:
There are many language/representation-specific decisions and heuristics involved in this kind of conversion, so you're not going to find any standard language-independent conversion tools. If you're working with PTB-style English trees there are several existing converters:

There's the one developed for the Stanford parser (edu.stanford.nlp.trees.EnglishGrammaticalStructure), which produces the kind of output you have above, described in their FAQ. (See also a related question: Stanford Dependencies Conversion Tool.)

There's also an older very PTB-specific LTH Constituent-to-Dependency Conversion Tool for Penn-style Treebanks, which produces CoNLL 2008-style output.

Your example doesn't look like a standard PTB tree so you might need to adapt an existing converter, in which case the Stanford converter is probably a good starting point.

Body:
Given a bracket notation  of constituent words, is there a way to convert it into its dependency tree?

[S [NP [Proper-Noun John]][VP [Verb saw][NP [Proper-Noun Mary]][PP [Preposition with][NP [Determiner a][Noun telescope]]]]]

into

nsubj(saw-2, John-1)
root(ROOT-0, saw-2)
dobj(saw-2, Mary-3)
case(telescope-6, with-4)
det(telescope-6, a-5)
nmod(saw-2, telescope-6)


问:
Disabling iPhone screenshot feature
I'm working on an enterprise iPhone application for a client, the issue at hand is customer information will show up on the phone. My client is worried that the information could be caught using the iphone screen capture feature (home + power button), then emailed or synced from the phone. Is there any way to disable the screen capture feature? Can this be done programatically or is is possible through a configuration profile?</p>

答: if your customer could retain the ownership of a handset, they can restrict Screen Capture feature using iPhone Configuration Utility. Make sure you don't give these phones to any one outside of this organization, otherwise you are in violation of your Enterprise legal agreement with Apple.

Title: Disabling iPhone screenshot feature


问:
Python commands in the Command prompt
I try to enter some commands directly in the cmd. The commands work from the IDE PyCharm, but when i try to enter them directly it doesn't work. What do i have to do? I tried to change the direction of the cmd (using cd).
Im using windows. I try to do some pip commands but i acctualy have a bigger problem. I am using the spectral toolbox from python. in the File matplotlib there comes the error No module named 'matplotlib._path'.</p>

答:
If you are using Linux then you can try as follows from your command prompt:

just for the example, i imported os module of python and got the OS
  information with os.uname() command ..

```<code>bash-4.1$ python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.uname()
    ('Linux', 'noi-karn', '2.6.32-431.11.2.el6.x86_64', '#1 SMP Tue Mar 25 19:59:55 UTC 2014', 'x86_64')
    >>> quit()
bash-4.1$
</code>```

Title: Python commands in the Command prompt

Body:
If you are using Linux then you can try as follows from your command prompt:

just for the example, i imported os module of python and got the OS
  information with os.uname() command ..

bash-4.1$ python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.uname()
    ('Linux', 'noi-karn', '2.6.32-431.11.2.el6.x86_64', '#1 SMP Tue Mar 25 19:59:55 UTC 2014', 'x86_64')
    >>> quit()
bash-4.1$


问:
Does kryo serialization work on non serializable class and class have non serializable attributes?
I'm trying to use Kryo library to convert any given object to byteArray and store in a data store or queue for later use. But is it possible to serialize any given object or only object implementing serializable interface can be converted.</p>

答:
It is possible to serialize/deserialize a bean with Kryo also if it doesn't implement java.io.Serialiable and/or if its attributes don't implement Serializable (I run the example with Kryo 2.10; there is the limitation that no argument constructors had to be explicitly defined here because non default constructors were present):

```<code>import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class KryoSerializerExample {

    public static void main(String[] args) {
        KryoHelper kryoHelper = new KryoHelper();
        ClassNotImplementingSerializable obj1 = new ClassNotImplementingSerializable(123, 456, "789");
        ClassNotImplementingSerializable obj2 = (ClassNotImplementingSerializable) kryoHelper.fromBytes(kryoHelper.toBytes(obj1));
        if (obj1.equals(obj2)) {
            System.out.println("the object and its clone are equal as expected");
        } else {
            System.out.println("the object and its clone are not equal, something went wrong");
        }
    }

    public static class KryoHelper {

        Kryo kryo;

        public KryoHelper() {
            super();
            kryo=new Kryo();
        }

        public byte[] toBytes(Object obj){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try (Output output = new Output(baos)) {
                kryo.writeClassAndObject(output, obj);
            }

            byte[] bytes = baos.toByteArray();
            return bytes;
        }

        public Object fromBytes(byte[] bytes){
            Object retrievedObject;
            try (Input input = new Input( new ByteArrayInputStream(bytes))){
                retrievedObject = kryo.readClassAndObject(input);
            }

            return retrievedObject;
        }

    }

    public static class ClassNotImplementingSerializable {
        private int a;
        private ClassNotImplementingSerializable2 b;

        /**
         * no-arg constructor is necessary
         */
        public ClassNotImplementingSerializable() {
        }
        public ClassNotImplementingSerializable(int a, int b, String c) {
            this.a = a;
            this.b = new ClassNotImplementingSerializable2(b,c);
        }
        public int getA() {
            return a;
        }
        public void setA(int a) {
            this.a = a;
        }
        public ClassNotImplementingSerializable2 getB() {
            return b;
        }
        public void setB(ClassNotImplementingSerializable2 b) {
            this.b = b;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + a;
            result = prime * result + ((b == null) ? 0 : b.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ClassNotImplementingSerializable other = (ClassNotImplementingSerializable) obj;
            if (a != other.a)
                return false;
            if (b == null) {
                if (other.b != null)
                    return false;
            } else if (!b.equals(other.b))
                return false;
            return true;
        }

    }

    public static class ClassNotImplementingSerializable2 {
        private int a;
        private String b;

        /**
         * no-arg constructor is necessary
         */
        public ClassNotImplementingSerializable2() {
        }
        public ClassNotImplementingSerializable2(int a, String b) {
            this.a = a;
            this.b = b;
        }
        public int getA() {
            return a;
        }
        public void setA(int a) {
            this.a = a;
        }
        public String getB() {
            return b;
        }
        public void setB(String b) {
            this.b = b;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + a;
            result = prime * result + ((b == null) ? 0 : b.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ClassNotImplementingSerializable2 other = (ClassNotImplementingSerializable2) obj;
            if (a != other.a)
                return false;
            if (b == null) {
                if (other.b != null)
                    return false;
            } else if (!b.equals(other.b))
                return false;
            return true;
        }
    }
}
</code>```

There can be problems with some specific field types, such as java.sql.Timestamp for example (there is a way around this one though), and of course java.lang.Thread and the likes.

Body:
It is possible to serialize/deserialize a bean with Kryo also if it doesn't implement java.io.Serialiable and/or if its attributes don't implement Serializable (I run the example with Kryo 2.10; there is the limitation that no argument constructors had to be explicitly defined here because non default constructors were present):

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class KryoSerializerExample {

    public static void main(String[] args) {
        KryoHelper kryoHelper = new KryoHelper();
        ClassNotImplementingSerializable obj1 = new ClassNotImplementingSerializable(123, 456, "789");
        ClassNotImplementingSerializable obj2 = (ClassNotImplementingSerializable) kryoHelper.fromBytes(kryoHelper.toBytes(obj1));
        if (obj1.equals(obj2)) {
            System.out.println("the object and its clone are equal as expected");
        } else {
            System.out.println("the object and its clone are not equal, something went wrong");
        }
    }

    public static class KryoHelper {

        Kryo kryo;

        public KryoHelper() {
            super();
            kryo=new Kryo();
        }

        public byte[] toBytes(Object obj){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try (Output output = new Output(baos)) {
                kryo.writeClassAndObject(output, obj);
            }

            byte[] bytes = baos.toByteArray();
            return bytes;
        }

        public Object fromBytes(byte[] bytes){
            Object retrievedObject;
            try (Input input = new Input( new ByteArrayInputStream(bytes))){
                retrievedObject = kryo.readClassAndObject(input);
            }

            return retrievedObject;
        }

    }

    public static class ClassNotImplementingSerializable {
        private int a;
        private ClassNotImplementingSerializable2 b;

        /**
         * no-arg constructor is necessary
         */
        public ClassNotImplementingSerializable() {
        }
        public ClassNotImplementingSerializable(int a, int b, String c) {
            this.a = a;
            this.b = new ClassNotImplementingSerializable2(b,c);
        }
        public int getA() {
            return a;
        }
        public void setA(int a) {
            this.a = a;
        }
        public ClassNotImplementingSerializable2 getB() {
            return b;
        }
        public void setB(ClassNotImplementingSerializable2 b) {
            this.b = b;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + a;
            result = prime * result + ((b == null) ? 0 : b.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ClassNotImplementingSerializable other = (ClassNotImplementingSerializable) obj;
            if (a != other.a)
                return false;
            if (b == null) {
                if (other.b != null)
                    return false;
            } else if (!b.equals(other.b))
                return false;
            return true;
        }

    }

    public static class ClassNotImplementingSerializable2 {
        private int a;
        private String b;

        /**
         * no-arg constructor is necessary
         */
        public ClassNotImplementingSerializable2() {
        }
        public ClassNotImplementingSerializable2(int a, String b) {
            this.a = a;
            this.b = b;
        }
        public int getA() {
            return a;
        }
        public void setA(int a) {
            this.a = a;
        }
        public String getB() {
            return b;
        }
        public void setB(String b) {
            this.b = b;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + a;
            result = prime * result + ((b == null) ? 0 : b.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ClassNotImplementingSerializable2 other = (ClassNotImplementingSerializable2) obj;
            if (a != other.a)
                return false;
            if (b == null) {
                if (other.b != null)
                    return false;
            } else if (!b.equals(other.b))
                return false;
            return true;
        }
    }
}

There can be problems with some specific field types, such as java.sql.Timestamp for example (there is a way around this one though), and of course java.lang.Thread and the likes.


问:
In Identity Server 4, I have a User's identity but 0 Claims
I have an identity server, a JavaScript client, and an API. All have been configured so that Authentication and Authorization are working as expected. I am now attempting to load the current user by id (the sub claim) in my API. The problem is that the User.Claims enumeration is empty in all of my controllers.

I have decoded the bearer token I am sending with each request and have confirmed I have a sub claim. Is there some additional configuration needed in my API to receive these claims?

Decoded JWT

```<code>{
  "nbf": 1510436170,
  "exp": 1510439770,
  "iss": "https://localhost:44300",
  "aud": [
    "https://localhost:44300/resources",
    "mycustom.api"
  ],
  "client_id": "mycustom.web",
  "sub": "c92cc2bc-d063-49d6-a36e-f6340796df15",
  "auth_time": 1510435257,
  "idp": "local",
  "scope": [
    "openid",
    "profile",
    "mycustom.api"
  ],
  "amr": [
    "pwd"
  ]
}
</code>```

API Configuration

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<BrewSwapDbContext>()
        .AddDefaultTokenProviders();

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300";
            options.ApiName = "mycustom.api";
        });

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(builder =>
        builder.AllowAnyHeader()
        .AllowAnyMethod()
        .AllowAnyOrigin());

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc();
}
</code>```

Client Configuration

On the SPA client I am using angular-auth-oidc-client. Again, I am able to inspect the bearer token in each request and can see the sub claim I need. See the decoded JWT above.

```<code>let oidcConfig = new OpenIDImplicitFlowConfiguration()
oidcConfig.stsServer = "https://localhost:44300";
oidcConfig.redirect_url = "https://localhost:44302";
oidcConfig.client_id = 'mycustom.web';
oidcConfig.response_type = 'id_token token';
oidcConfig.scope = 'openid profile mycustom.api';
oidcConfig.post_logout_redirect_uri = "https://localhost:44302";
oidcConfig.start_checksession = false;
oidcConfig.silent_renew = true;
oidcConfig.silent_renew_offset_in_seconds = 0;
oidcConfig.startup_route = '/home';
oidcConfig.auto_userinfo = true;
oidcConfig.log_console_warning_active = true;
oidcConfig.log_console_debug_active = true;
oidcConfig.max_id_token_iat_offset_allowed_in_seconds = 10;
oidcConfig.storage = localStorage;
</code>```

API Controller

```<code>public class ExampleController : Controller
{
    private readonly MyDbContext _context;

    public ExampleController(MyDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IEnumerable<Example> GetExamples()
    {
        var test = User.Claims;
        return _context.Examples;
    }
}
</code>```

You can see below that an identity was found...

but it has 0 claims.

答:
API Setup correction:

This is the correct code for your ConfigureServices method.

The AddIdentity is not needed since the information is provided by the claims that come from the IdentityServer4.

```<code>public void ConfigureServices(IServiceCollection services)
{
     services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300";
            options.ApiName = "mycustom.api";
        });

    services.AddMvc();
}
</code>```

Body:
I have an identity server, a JavaScript client, and an API. All have been configured so that Authentication and Authorization are working as expected. I am now attempting to load the current user by id (the sub claim) in my API. The problem is that the User.Claims enumeration is empty in all of my controllers.

I have decoded the bearer token I am sending with each request and have confirmed I have a sub claim. Is there some additional configuration needed in my API to receive these claims?

Decoded JWT

{
  "nbf": 1510436170,
  "exp": 1510439770,
  "iss": "https://localhost:44300",
  "aud": [
    "https://localhost:44300/resources",
    "mycustom.api"
  ],
  "client_id": "mycustom.web",
  "sub": "c92cc2bc-d063-49d6-a36e-f6340796df15",
  "auth_time": 1510435257,
  "idp": "local",
  "scope": [
    "openid",
    "profile",
    "mycustom.api"
  ],
  "amr": [
    "pwd"
  ]
}

API Configuration

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<BrewSwapDbContext>()
        .AddDefaultTokenProviders();

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300";
            options.ApiName = "mycustom.api";
        });

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(builder =>
        builder.AllowAnyHeader()
        .AllowAnyMethod()
        .AllowAnyOrigin());

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc();
}

Client Configuration

On the SPA client I am using angular-auth-oidc-client. Again, I am able to inspect the bearer token in each request and can see the sub claim I need. See the decoded JWT above.

let oidcConfig = new OpenIDImplicitFlowConfiguration()
oidcConfig.stsServer = "https://localhost:44300";
oidcConfig.redirect_url = "https://localhost:44302";
oidcConfig.client_id = 'mycustom.web';
oidcConfig.response_type = 'id_token token';
oidcConfig.scope = 'openid profile mycustom.api';
oidcConfig.post_logout_redirect_uri = "https://localhost:44302";
oidcConfig.start_checksession = false;
oidcConfig.silent_renew = true;
oidcConfig.silent_renew_offset_in_seconds = 0;
oidcConfig.startup_route = '/home';
oidcConfig.auto_userinfo = true;
oidcConfig.log_console_warning_active = true;
oidcConfig.log_console_debug_active = true;
oidcConfig.max_id_token_iat_offset_allowed_in_seconds = 10;
oidcConfig.storage = localStorage;

API Controller

public class ExampleController : Controller
{
    private readonly MyDbContext _context;

    public ExampleController(MyDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IEnumerable<Example> GetExamples()
    {
        var test = User.Claims;
        return _context.Examples;
    }
}

You can see below that an identity was found...

but it has 0 claims.

Body:
API Setup correction:

This is the correct code for your ConfigureServices method.

The AddIdentity is not needed since the information is provided by the claims that come from the IdentityServer4.

public void ConfigureServices(IServiceCollection services)
{
     services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300";
            options.ApiName = "mycustom.api";
        });

    services.AddMvc();
}


问:
replace values in pandas based on other two column
I have problem with replacement values in a column conditional other two columns.

For example we have three columns. A, B, and C
Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".

When in columns A and B are True in column C we have value "Payroll".
I want to change values in column C where both column A and B are True.

I tried following code: but gives me this error "'NoneType' object has no attribute 'where'":

```<code>data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))
</code>```

but gives me this error "'NoneType' object has no attribute 'where'":

What can be done to this problem?

答:
I think you need all for check if all Trues per rows and then assign output by filtered DataFrame by boolean mask:

```<code>data1 = pd.DataFrame({
    'C': ['Payroll','Other','Payroll','Social'],
    'A': [True, True, True, False],
    'B':[False, True, True, False]
})
print (data1)
       A      B        C
0   True  False  Payroll
1   True   True    Other
2   True   True  Payroll
3  False  False   Social

m = data1[['A', 'B']].all(axis=1)
#same output as
#m = data1['A'] & data1['B']
print (m)
0    False
1     True
2     True
3    False
dtype: bool

print (data1[m])
      A     B        C
1  True  True    Other
2  True  True  Payroll
</code>```

```<code>data1[m] = data1[m].replace({'C' : { 'Payroll':'Social'}})
print (data1)
       A      B        C
0   True  False  Payroll
1   True   True    Other
2   True   True   Social
3  False  False   Social
</code>```

Body:
I have problem with replacement values in a column conditional other two columns.

For example we have three columns. A, B, and C
Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".

When in columns A and B are True in column C we have value "Payroll".
I want to change values in column C where both column A and B are True.

I tried following code: but gives me this error "'NoneType' object has no attribute 'where'":

data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))

but gives me this error "'NoneType' object has no attribute 'where'":

What can be done to this problem?

Body:
I think you need all for check if all Trues per rows and then assign output by filtered DataFrame by boolean mask:

data1 = pd.DataFrame({
    'C': ['Payroll','Other','Payroll','Social'],
    'A': [True, True, True, False],
    'B':[False, True, True, False]
})
print (data1)
       A      B        C
0   True  False  Payroll
1   True   True    Other
2   True   True  Payroll
3  False  False   Social

m = data1[['A', 'B']].all(axis=1)
#same output as
#m = data1['A'] & data1['B']
print (m)
0    False
1     True
2     True
3    False
dtype: bool

print (data1[m])
      A     B        C
1  True  True    Other
2  True  True  Payroll

data1[m] = data1[m].replace({'C' : { 'Payroll':'Social'}})
print (data1)
       A      B        C
0   True  False  Payroll
1   True   True    Other
2   True   True   Social
3  False  False   Social


问:
What is the difference between Face Detection and Face Tracking in iOS perspective
May be this sounds like a stupid one, but i really curious to know that, what is the difference between "Face Detection and Face Tracking" in iOS perspective? And in what case or which kind of situation should i use the two of them.</p>

答:
The Face Detection is done by the Apple Framework CoreImage Framework. Available since iOS 5+, (besides the Vision Framework).

You can use the https://developer.apple.com/documentation/coreimage/cidetector

CIDetector to detect faces.

Face detection will return face landmarks such as eyes, lips, nose. This frames can be used to modify the faces with image processing.

You can also use the faces found, and use it with a third party Face Recognitions API's to recognize faces (Microsoft face API) .

Face Tracking
Can be used to track the real time location of face features, and possible apply filters to it (snapchat, etc).


问:
jquery.form & jquery.validate: No POST data submitted in IE
When users submit my from in IE8, with or without compatibility mode, the form does the AJAX call, but no POST data is sent. Below is my jQuery.validate and jQuery.form code:

```<code>var v = jQuery("#enterfrm").validate({
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                target: "#result",
                success: function() {
                    $("#enterfrm").hide();
                }
            });
        },
        debug: true,
        rules: {
            reportto: {
                required: true
            },
            jobtitle: {
                required: true
            },
            dept: {
                required: true
            },
            paystatus: {
                required: true
            },
            reason: {
                required: true
            },
            prefstartdate: {
                required: true
            },
            sthour: {
                required: true
            },
            edhour: {
                required: true
            },
            jbdescex: {
                required: true
            },
            positionchg: {
                required: true
            },
            minexp: {
                required: true
            },
            adrecreq: {
                required: true
            },
            comsug: {
                required: false
            },
            org: {
                required: true
            },
            origemail: {
                required: true
            },
            // //
            replacing: {
                required: function(element) {
                    return $("#reason").val() == "Replacement";
                }
            },
            replacetitle: {
                required: function(element) {
                    return $("#reason").val() == "Replacement";
                }
            },
            justify: {
                required: function(element) {
                    return $("#reason").val() == "New Position";
                }
            },
            length: {
                required: function(element) {
                    return $("#paystatus").val() == "Temporary - In House" || $("#paystatus").val() == "Temporary - Outside";
                }
            },
            purpose: {
                required: function(element) {
                    return $("#jbdescex").val() == "No" || $("#positionchg").val() == "Yes";
                }
            },
            duties: {
                required: function(element) {
                    return $("#jbdescex").val() == "No" || $("#positionchg").val() == "Yes";
                }
            },
            sthour: {
                required: true,
                minlength: 4,
                maxlength: 8
                //notEqTime: true
            },
            edhour: {
                required: true,
                minlength: 4,
                maxlength: 8 //,
                //notEqTime: true
            }
        }
    });
</code>```

And here is what FireBug Lite captures:

```<code>ResponseHeaders
Date Mon, 17 Jan 2011 13:56:25 GMT
Server Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.12 with Suhosin-Patch mod_perl/2.0.2 Perl/v5.8.8
X-Powered-By PHP/5.2.4-2ubuntu5.12
Keep-Alive timeout=15, max=100
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/html

RequestHeaders
Content-Type application/x-www-form-urlencoded
X-Requested-With XMLHttpRequest
Accept */*
</code>```

There is nothing under the POST tab. This all works fine in Firefox, Chrome, and IE with Chrome Frame. Am I missing something as far as the problem is concerned?

EDIT
I have tried this with a GET request as well now and that does not work either.

答:
looks like jQuery.Form uses $.param(a) to serialize the form, I've only had success getting IE to create proper POST Data with $.param(a, true) See here. http://api.jquery.com/jQuery.param/

You can use traditional serialization globally by doing $.ajaxSettings.traditional = true;

Body:
When users submit my from in IE8, with or without compatibility mode, the form does the AJAX call, but no POST data is sent. Below is my jQuery.validate and jQuery.form code:

var v = jQuery("#enterfrm").validate({
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                target: "#result",
                success: function() {
                    $("#enterfrm").hide();
                }
            });
        },
        debug: true,
        rules: {
            reportto: {
                required: true
            },
            jobtitle: {
                required: true
            },
            dept: {
                required: true
            },
            paystatus: {
                required: true
            },
            reason: {
                required: true
            },
            prefstartdate: {
                required: true
            },
            sthour: {
                required: true
            },
            edhour: {
                required: true
            },
            jbdescex: {
                required: true
            },
            positionchg: {
                required: true
            },
            minexp: {
                required: true
            },
            adrecreq: {
                required: true
            },
            comsug: {
                required: false
            },
            org: {
                required: true
            },
            origemail: {
                required: true
            },
            // //
            replacing: {
                required: function(element) {
                    return $("#reason").val() == "Replacement";
                }
            },
            replacetitle: {
                required: function(element) {
                    return $("#reason").val() == "Replacement";
                }
            },
            justify: {
                required: function(element) {
                    return $("#reason").val() == "New Position";
                }
            },
            length: {
                required: function(element) {
                    return $("#paystatus").val() == "Temporary - In House" || $("#paystatus").val() == "Temporary - Outside";
                }
            },
            purpose: {
                required: function(element) {
                    return $("#jbdescex").val() == "No" || $("#positionchg").val() == "Yes";
                }
            },
            duties: {
                required: function(element) {
                    return $("#jbdescex").val() == "No" || $("#positionchg").val() == "Yes";
                }
            },
            sthour: {
                required: true,
                minlength: 4,
                maxlength: 8
                //notEqTime: true
            },
            edhour: {
                required: true,
                minlength: 4,
                maxlength: 8 //,
                //notEqTime: true
            }
        }
    });

And here is what FireBug Lite captures:

ResponseHeaders
Date Mon, 17 Jan 2011 13:56:25 GMT
Server Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.12 with Suhosin-Patch mod_perl/2.0.2 Perl/v5.8.8
X-Powered-By PHP/5.2.4-2ubuntu5.12
Keep-Alive timeout=15, max=100
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/html

RequestHeaders
Content-Type application/x-www-form-urlencoded
X-Requested-With XMLHttpRequest
Accept */*

There is nothing under the POST tab. This all works fine in Firefox, Chrome, and IE with Chrome Frame. Am I missing something as far as the problem is concerned?

EDIT
I have tried this with a GET request as well now and that does not work either.