答:
Some programmer dude already spotted, but I want to be a little more explicit:

```<code>char x;
int value;
if (value != x)
</code>```

Both x and value are uninitialized, they could hold any value. If you compare them, it is very unlikely that they will match, but they could by accident even at the first time you enter the loop (leading to immediate exit). It is very unlikely, too, that variable x holds the value of 'x' – in the end, it is undefined behaviour anyway to read uninitialized variables...

Next problem is: You simply use scanf("%d"). This will fail trying to read input, if you type in an 'x' character, because that one cannot be scanned as a number. So you would have to read a string first and then parse it. Both errors fixed together, your code might look like this:

```<code>char buffer[128];
while(1)
{
    if(!fgets(buffer, sizeof(buffer), stdin))
        break; // some error occured
    if(*buffer == 'x') // you can compare directly, you don't need a char x = 'x'; ...
        break;
    int value;
    char c;
    if(sscanf(buffer, "%d %c", &value, &c) == 1)
    {
        // ...
    }
    else
    {
        puts("invalid input");
        fflush(stdout);
    }
}
</code>```

Scanning for an additional character after the number (important: the space character before is needed to skip white space, i. e. the terminating newline character got from fgets) together with checking the return value of sscanf detects invalid input such as 'abc' or '1xyz'.

Additionally, have a look at your popStack function:

```<code>struct Node* var = top;
if (var == top)
</code>```

This will always be true, even it top is NULL: then var is NULL, too, and NULL is equal to itself, of course...

You should rather do it this way:

```<code>if (top)
{
    struct Node* var = top;
    top = top->next;
    free(var);
}
</code>```

Good practice is always checking the return value of malloc. Although it shouldn't ever fail in such a small program like yours, you won't forget it later when writing larger programs if you get used to right from the start...

Together with some code simplification (admitted, cosmetics only, but the if is not necessary...):

```<code>struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
if(temp)
{
    temp->Data = value;
    temp->next = top;
    top = temp;
}
else
{
    // appropriate error handling
}
</code>```

One last recommendation: Your two functions form a functional pair, so prefer reflecting this in their names, too: either "push" and "pop" or "pushStack" and "popStack".

Title: How can i display stack C

Body:
Some programmer dude already spotted, but I want to be a little more explicit:

char x;
int value;
if (value != x)

Both x and value are uninitialized, they could hold any value. If you compare them, it is very unlikely that they will match, but they could by accident even at the first time you enter the loop (leading to immediate exit). It is very unlikely, too, that variable x holds the value of 'x' – in the end, it is undefined behaviour anyway to read uninitialized variables...

Next problem is: You simply use scanf("%d"). This will fail trying to read input, if you type in an 'x' character, because that one cannot be scanned as a number. So you would have to read a string first and then parse it. Both errors fixed together, your code might look like this:

char buffer[128];
while(1)
{
    if(!fgets(buffer, sizeof(buffer), stdin))
        break; // some error occured
    if(*buffer == 'x') // you can compare directly, you don't need a char x = 'x'; ...
        break;
    int value;
    char c;
    if(sscanf(buffer, "%d %c", &value, &c) == 1)
    {
        // ...
    }
    else
    {
        puts("invalid input");
        fflush(stdout);
    }
}

Scanning for an additional character after the number (important: the space character before is needed to skip white space, i. e. the terminating newline character got from fgets) together with checking the return value of sscanf detects invalid input such as 'abc' or '1xyz'.

Additionally, have a look at your popStack function:

struct Node* var = top;
if (var == top)

This will always be true, even it top is NULL: then var is NULL, too, and NULL is equal to itself, of course...

You should rather do it this way:

if (top)
{
    struct Node* var = top;
    top = top->next;
    free(var);
}

Good practice is always checking the return value of malloc. Although it shouldn't ever fail in such a small program like yours, you won't forget it later when writing larger programs if you get used to right from the start...

Together with some code simplification (admitted, cosmetics only, but the if is not necessary...):

struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
if(temp)
{
    temp->Data = value;
    temp->next = top;
    top = temp;
}
else
{
    // appropriate error handling
}

One last recommendation: Your two functions form a functional pair, so prefer reflecting this in their names, too: either "push" and "pop" or "pushStack" and "popStack".


来源: stackexchange

问:
VerifyError in using FingerPrint authorization in lower APIs in android
I want to use FingerPrint authorization in my app. But as I run it in Samsung GT-N8000 with Android 4.1, it has stopped and shows me VerifyError(this device doesn’t support finger print sensor).

```<code>import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.graphics.drawable.TintAwareDrawable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.security.cert.CertificateException;

import banknote.maxsoft.com.banknote.DataBaseClass;
import banknote.maxsoft.com.banknote.MainActivity;
import banknote.maxsoft.com.banknote.R;

public class LogUpInActivity extends Activity {

    // sign in with password
    public View signIn_passwordContent;

    // sign in with finger print
    public  View signIn_fingerPrintContent;
    private KeyguardManager keyguardManager;
    private FingerprintManager fingerprintManager;
    private KeyStore keyStore;
    private KeyGenerator keyGenerator;
    private TextView msg_fingerPrint;
    private Cipher cipher;
    private static final String KEY_NAME = "mohrOmoom";
    private FingerprintManager.CryptoObject cryptoObject;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_container);

               signIn_passwordContent = findViewById(R.id.signIn_password_container);

        signIn_fingerPrintContent = findViewById(R.id.fingerprint_container);
        msg_fingerPrint = (TextView) findViewById(R.id.fingerprint_description);

        // Initializing both Android Keyguard Manager and Fingerprint Manager
        if (Build.VERSION.SDK_INT>=23) {
            keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
            fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
        }

            // Check whether the device has a Fingerprint sensor.
            if ((!fingerprintManager.isHardwareDetected()) && (Build.VERSION.SDK_INT>+23)){
                signIn_fingerPrintContent.setVisibility(View.GONE);
            } else {
                signIn_fingerPrintContent.setVisibility(View.VISIBLE);

                // Checks whether fingerprint permission is set on manifest
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                    msg_fingerPrint.setVisibility(View.VISIBLE);
                    msg_fingerPrint.setText(R.string.fingerPrint_not_avable);
                    msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                } else {
                    // Check whether at least one fingerprint is registered
                    if (!fingerprintManager.hasEnrolledFingerprints()) {
                        msg_fingerPrint.setVisibility(View.VISIBLE);
                        msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                        msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                    } else {
                        // Checks whether lock screen security is enabled or not
                        if (!keyguardManager.isKeyguardSecure()) {
                            msg_fingerPrint.setVisibility(View.VISIBLE);
                            msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                            msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                        } else {
                            generateKey();

                            if (cipherInit()) {
                                cryptoObject = new FingerprintManager.CryptoObject(cipher);
                                FingerprintHandler helper = new FingerprintHandler(this);
                                helper.startAuth(fingerprintManager, cryptoObject);
                            }
                        }
                    }
                }

            }
        }

...

    } // on create

    /*
    sign in with finger print
     */
    @TargetApi(Build.VERSION_CODES.M)
    protected void generateKey() {
        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            //startActivity(new Intent(LogUpInActivity.this,MainActivity.class));
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException("Failed to get KeyGenerator instance", e);
        }

        try {
            keyStore.load(null);
            keyGenerator.init(new
                    KeyGenParameterSpec.Builder(KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT |
                            KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(
                            KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build());
            keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException |
                InvalidAlgorithmParameterException
                | IOException e) {
            throw new RuntimeException(e);
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public boolean cipherInit() {
        try {
            cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("Failed to get Cipher", e);
        }

        try {
            keyStore.load(null);
            SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return true;
        } catch (KeyPermanentlyInvalidatedException e) {
            return false;
        } catch(KeyStoreException | UnrecoverableKeyException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Failed to init Cipher", e);
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        }
        return true;
    }

    public void onFinish(){
        editor_password.putString("password",logIn_password).commit();

    }
</code>```

this is error logs:

```<code>FATAL EXCEPTION: main
              java.lang.VerifyError: PACKAGE NAME/LogUpInActivity
                  at java.lang.Class.newInstanceImpl(Native Method)
                  at java.lang.Class.newInstance(Class.java:1319)
                  at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

and this si Build.grdle:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "banknote.maxsoft.com.banknote"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'junit:junit:4.12'
    compile 'com.getbase:floatingactionbutton:1.10.1'
}
</code>```

How can I solve VerifyError and run my app in lower APIs?
thanks for your helps.

UPDATE:
i use @MuthukrishnanRajendran answer,like this:

```<code>public class LogActivity extends Activity implements FPStatusListener {
// sign up statue
private SharedPreferences StatuSharePreference;
private SharedPreferences.Editor editor_state;
public boolean state_signUp, default_state, state_check;
private LogUpInActivity.Stage mStage;

// sign up with password
private View signUpContent;
private EditText signUp_pasword_editText, signUp_conf_password_editText, signIn_password_editText;
public static SharedPreferences save_password_sharePreference;
public static SharedPreferences.Editor editor_password;
public static String logIn_password = null;

// sign in with password
public View signIn_passwordContent;
public int times_of_signIn=3;

// sign in with finger print
public  View signIn_fingerPrintContent;
private LFingerPrint mLFingerPrint;
private TextView msg_fingerPrint;
private static final String KEY_NAME = "mohrOmoom";

// sign in after unlocking
public boolean sign_in_again;

private Button cancelBTN, stateBTN;
private TextView msg_state_conf;

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_container);

    TextView who = (TextView) findViewById(R.id.who);
    who.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/mehr.ttf"));
    TextView signInPassTitle = (TextView) findViewById(R.id.password_description);
    signInPassTitle.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/nazanin.ttf"));
    TextView signUpPassTitle = (TextView) findViewById(R.id.signUp_title);
    signUpPassTitle.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/nazanin.ttf"));
    StatuSharePreference = getSharedPreferences("signUp", Context.MODE_PRIVATE);
    editor_state = StatuSharePreference.edit();

    signUpContent = findViewById(R.id.signup_content);
    signUp_pasword_editText = (EditText) findViewById(R.id.pass);
    signUp_conf_password_editText = (EditText) findViewById(R.id.conf_pass);
    signIn_password_editText = (EditText) findViewById(R.id.password);
    msg_state_conf = (TextView) findViewById(R.id.notConfiration_msg);
    save_password_sharePreference = getSharedPreferences("password", Context.MODE_PRIVATE);
    editor_password = save_password_sharePreference.edit();

    signIn_passwordContent = findViewById(R.id.signIn_password_container);

    signIn_fingerPrintContent = findViewById(R.id.fingerprint_container);
    msg_fingerPrint = (TextView) findViewById(R.id.fingerprint_description);
    mLFingerPrint = new LFingerPrint(this, this);

    // check if sign up is done or not
    if (!default_state) {
        state_signUp = false;
        default_state = true;
    } else {
        state_signUp = true;
    }

    state_check = StatuSharePreference.getBoolean("signUp", state_signUp);
    if (!state_check) {
        // register user password
        signIn_passwordContent.setVisibility(View.GONE);
        signUpContent.setVisibility(View.VISIBLE);
        mStage = LogUpInActivity.Stage.SIGNUP;
    } else {
        signUpContent.setVisibility(View.GONE);
        signIn_passwordContent.setVisibility(View.VISIBLE);

        // Check whether the device has a Fingerprint sensor.
        if ((!mLFingerPrint.getManager().isFingerPrintAvailable())){
            signIn_fingerPrintContent.setVisibility(View.GONE);
        } else {
            signIn_fingerPrintContent.setVisibility(View.VISIBLE);

            // Checks whether fingerprint permission is set on manifest
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                msg_fingerPrint.setVisibility(View.VISIBLE);
                msg_fingerPrint.setText(R.string.fingerPrint_not_avable);
                msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
            } else {
                // Check whether at least one fingerprint is registered
                if (!mLFingerPrint.getManager().hasFingerprintRegistered()) {
                    msg_fingerPrint.setVisibility(View.VISIBLE);
                    msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                    msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                } else {
                    mLFingerPrint.getManager().startListening();
                }
            }

        }
        mStage = LogUpInActivity.Stage.SIGNIN_PASSWORD;
    }

    cancelBTN = (Button) findViewById(R.id.cancel_button);
    cancelBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    logIn_password = save_password_sharePreference.getString("password", logIn_password);
    stateBTN = (Button) findViewById(R.id.second_dialog_button);
    stateBTN.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(View view) {
            switch (mStage) {
                case SIGNUP: //get user password and register it
                    registerPassword();
                    break;
                /*case  SIGNIN_FINGERPRINT:// open sign in with password
                    signInWithPassword();
                    break;*/
                case SIGNIN_PASSWORD://checking passsword entry
                    verifyPassword();
                    break;
            }
        }
    });

} // on create

/**
 * get user password from Edit text , check its lengh , confirm it
 **/
public void registerPassword() {
    String passString = signUp_pasword_editText.getText().toString();
    String confPassString = signUp_conf_password_editText.getText().toString();

    if ((passString.equals(confPassString)) &&
            (passString.length() == 12) &&
            (confPassString.length() == 12)) {
        logIn_password = passString;
        editor_password.putString("password", logIn_password).commit();
        Toast.makeText(this, logIn_password, Toast.LENGTH_LONG).show();
        msg_state_conf.setVisibility(View.VISIBLE);
        msg_state_conf.setText(R.string.msg_conf);
        msg_state_conf.setTextColor(getResources().getColor(R.color.green_color));

        editor_state.putBoolean("signUp", true).commit();
        //state_signUp = true;

        //mina! ***checking fingerPrint sensor***
        /* + : finger primt authorization
        ** - : sign in with password
         */
        mStage = LogUpInActivity.Stage.SIGNIN_PASSWORD;
        signUpContent.setVisibility(View.GONE);
        signIn_passwordContent.setVisibility(View.VISIBLE);
    } else {
        msg_state_conf.setVisibility(View.VISIBLE);
        msg_state_conf.setText(R.string.msg_not_conf);
        msg_state_conf.setTextColor(getResources().getColor(R.color.red_color));
        //not confirm
        editor_state.putBoolean("signUp", false).commit();

    }
}

/**
 * Checks whether the current entered password is correct, and dismisses the the dialog and
 * let's the activity know about the result.
 */
private void verifyPassword() {
    logIn_password = save_password_sharePreference.getString("signUp", logIn_password);
    Toast.makeText(this, logIn_password, Toast.LENGTH_LONG).show();
    if (signIn_password_editText.getText().toString().equals(logIn_password)) {
        startActivity(new Intent(LogActivity.this, MainActivity.class));
        LogActivity.this.finish();
    } else {
        --times_of_signIn;
        Toast.makeText(this, times_of_signIn + "تعداد ورود باقیمانده:", Toast.LENGTH_LONG).show();
        signIn_password_editText.setText(null);

        if (times_of_signIn == 0) {
            Toast.makeText(this, R.string.restart_app, Toast.LENGTH_LONG).show();
            MainActivity.sqlDB.delete(DataBaseClass.BANK_TABLE_NAME, null, null);
            logIn_password = null;
            editor_password.putString("password", logIn_password).commit();
            state_signUp = false;
            editor_state.putBoolean("signUp", state_signUp).commit();
            signIn_passwordContent.setVisibility(View.GONE);
            signUpContent.setVisibility(View.VISIBLE);
            mStage = LogUpInActivity.Stage.SIGNUP;
        }
    }

}

public void onFinish(){
    editor_password.putString("password",logIn_password).commit();

}

/**
 * Enumeration to indicate which authentication method the user is trying to authenticate with.
 */
public enum Stage {
    SIGNUP,
    SIGNIN_FINGERPRINT,
    SIGNIN_PASSWORD
}

@Override
public void fpAuthSuccess() {
    Intent intent=new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);

}

@Override
public void fpAuthFailed(@Nullable String error) {
    Toast.makeText(this,R.string.fingerPrint_retry,Toast.LENGTH_LONG).show();

}
</code>```

}

but as i run it on Samsung N8000,this error shows me:

```<code>FATAL EXCEPTION: main
              java.lang.RuntimeException: Unable to start activity ComponentInfo{...LogActivity}: java.lang.NullPointerException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NullPointerException
                  at banknote.maxsoft.com.banknote.authorization.LogActivity.onCreate(LogActivity.java:135)
                  at android.app.Activity.performCreate(Activity.java:5188)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

答: Please refer my Sample FingerPrint application, It supports Legacy FingerPrint device, Marshmallow devices and Samsung devices.</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to use FingerPrint authorization in my app. But as I run it in Samsung GT-N8000 with Android 4.1, it has stopped and shows me VerifyError(this device doesn’t support finger print sensor).

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.graphics.drawable.TintAwareDrawable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.security.cert.CertificateException;

import banknote.maxsoft.com.banknote.DataBaseClass;
import banknote.maxsoft.com.banknote.MainActivity;
import banknote.maxsoft.com.banknote.R;

public class LogUpInActivity extends Activity {

    // sign in with password
    public View signIn_passwordContent;

    // sign in with finger print
    public  View signIn_fingerPrintContent;
    private KeyguardManager keyguardManager;
    private FingerprintManager fingerprintManager;
    private KeyStore keyStore;
    private KeyGenerator keyGenerator;
    private TextView msg_fingerPrint;
    private Cipher cipher;
    private static final String KEY_NAME = "mohrOmoom";
    private FingerprintManager.CryptoObject cryptoObject;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_container);

               signIn_passwordContent = findViewById(R.id.signIn_password_container);

        signIn_fingerPrintContent = findViewById(R.id.fingerprint_container);
        msg_fingerPrint = (TextView) findViewById(R.id.fingerprint_description);

        // Initializing both Android Keyguard Manager and Fingerprint Manager
        if (Build.VERSION.SDK_INT>=23) {
            keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
            fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
        }

            // Check whether the device has a Fingerprint sensor.
            if ((!fingerprintManager.isHardwareDetected()) && (Build.VERSION.SDK_INT>+23)){
                signIn_fingerPrintContent.setVisibility(View.GONE);
            } else {
                signIn_fingerPrintContent.setVisibility(View.VISIBLE);

                // Checks whether fingerprint permission is set on manifest
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                    msg_fingerPrint.setVisibility(View.VISIBLE);
                    msg_fingerPrint.setText(R.string.fingerPrint_not_avable);
                    msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                } else {
                    // Check whether at least one fingerprint is registered
                    if (!fingerprintManager.hasEnrolledFingerprints()) {
                        msg_fingerPrint.setVisibility(View.VISIBLE);
                        msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                        msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                    } else {
                        // Checks whether lock screen security is enabled or not
                        if (!keyguardManager.isKeyguardSecure()) {
                            msg_fingerPrint.setVisibility(View.VISIBLE);
                            msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                            msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                        } else {
                            generateKey();

                            if (cipherInit()) {
                                cryptoObject = new FingerprintManager.CryptoObject(cipher);
                                FingerprintHandler helper = new FingerprintHandler(this);
                                helper.startAuth(fingerprintManager, cryptoObject);
                            }
                        }
                    }
                }

            }
        }

...

    } // on create

    /*
    sign in with finger print
     */
    @TargetApi(Build.VERSION_CODES.M)
    protected void generateKey() {
        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            //startActivity(new Intent(LogUpInActivity.this,MainActivity.class));
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException("Failed to get KeyGenerator instance", e);
        }

        try {
            keyStore.load(null);
            keyGenerator.init(new
                    KeyGenParameterSpec.Builder(KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT |
                            KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(
                            KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build());
            keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException |
                InvalidAlgorithmParameterException
                | IOException e) {
            throw new RuntimeException(e);
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public boolean cipherInit() {
        try {
            cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("Failed to get Cipher", e);
        }

        try {
            keyStore.load(null);
            SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return true;
        } catch (KeyPermanentlyInvalidatedException e) {
            return false;
        } catch(KeyStoreException | UnrecoverableKeyException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Failed to init Cipher", e);
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        }
        return true;
    }

    public void onFinish(){
        editor_password.putString("password",logIn_password).commit();

    }

this is error logs:

FATAL EXCEPTION: main
              java.lang.VerifyError: PACKAGE NAME/LogUpInActivity
                  at java.lang.Class.newInstanceImpl(Native Method)
                  at java.lang.Class.newInstance(Class.java:1319)
                  at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)

and this si Build.grdle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "banknote.maxsoft.com.banknote"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'junit:junit:4.12'
    compile 'com.getbase:floatingactionbutton:1.10.1'
}

How can I solve VerifyError and run my app in lower APIs?
thanks for your helps.

UPDATE:
i use @MuthukrishnanRajendran answer,like this:

public class LogActivity extends Activity implements FPStatusListener {
// sign up statue
private SharedPreferences StatuSharePreference;
private SharedPreferences.Editor editor_state;
public boolean state_signUp, default_state, state_check;
private LogUpInActivity.Stage mStage;

// sign up with password
private View signUpContent;
private EditText signUp_pasword_editText, signUp_conf_password_editText, signIn_password_editText;
public static SharedPreferences save_password_sharePreference;
public static SharedPreferences.Editor editor_password;
public static String logIn_password = null;

// sign in with password
public View signIn_passwordContent;
public int times_of_signIn=3;

// sign in with finger print
public  View signIn_fingerPrintContent;
private LFingerPrint mLFingerPrint;
private TextView msg_fingerPrint;
private static final String KEY_NAME = "mohrOmoom";

// sign in after unlocking
public boolean sign_in_again;

private Button cancelBTN, stateBTN;
private TextView msg_state_conf;

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_container);

    TextView who = (TextView) findViewById(R.id.who);
    who.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/mehr.ttf"));
    TextView signInPassTitle = (TextView) findViewById(R.id.password_description);
    signInPassTitle.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/nazanin.ttf"));
    TextView signUpPassTitle = (TextView) findViewById(R.id.signUp_title);
    signUpPassTitle.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/nazanin.ttf"));
    StatuSharePreference = getSharedPreferences("signUp", Context.MODE_PRIVATE);
    editor_state = StatuSharePreference.edit();

    signUpContent = findViewById(R.id.signup_content);
    signUp_pasword_editText = (EditText) findViewById(R.id.pass);
    signUp_conf_password_editText = (EditText) findViewById(R.id.conf_pass);
    signIn_password_editText = (EditText) findViewById(R.id.password);
    msg_state_conf = (TextView) findViewById(R.id.notConfiration_msg);
    save_password_sharePreference = getSharedPreferences("password", Context.MODE_PRIVATE);
    editor_password = save_password_sharePreference.edit();

    signIn_passwordContent = findViewById(R.id.signIn_password_container);

    signIn_fingerPrintContent = findViewById(R.id.fingerprint_container);
    msg_fingerPrint = (TextView) findViewById(R.id.fingerprint_description);
    mLFingerPrint = new LFingerPrint(this, this);

    // check if sign up is done or not
    if (!default_state) {
        state_signUp = false;
        default_state = true;
    } else {
        state_signUp = true;
    }

    state_check = StatuSharePreference.getBoolean("signUp", state_signUp);
    if (!state_check) {
        // register user password
        signIn_passwordContent.setVisibility(View.GONE);
        signUpContent.setVisibility(View.VISIBLE);
        mStage = LogUpInActivity.Stage.SIGNUP;
    } else {
        signUpContent.setVisibility(View.GONE);
        signIn_passwordContent.setVisibility(View.VISIBLE);

        // Check whether the device has a Fingerprint sensor.
        if ((!mLFingerPrint.getManager().isFingerPrintAvailable())){
            signIn_fingerPrintContent.setVisibility(View.GONE);
        } else {
            signIn_fingerPrintContent.setVisibility(View.VISIBLE);

            // Checks whether fingerprint permission is set on manifest
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                msg_fingerPrint.setVisibility(View.VISIBLE);
                msg_fingerPrint.setText(R.string.fingerPrint_not_avable);
                msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
            } else {
                // Check whether at least one fingerprint is registered
                if (!mLFingerPrint.getManager().hasFingerprintRegistered()) {
                    msg_fingerPrint.setVisibility(View.VISIBLE);
                    msg_fingerPrint.setText(R.string.fingerPrint_not_register);
                    msg_fingerPrint.setTextColor(getResources().getColor(R.color.red_color));
                } else {
                    mLFingerPrint.getManager().startListening();
                }
            }

        }
        mStage = LogUpInActivity.Stage.SIGNIN_PASSWORD;
    }

    cancelBTN = (Button) findViewById(R.id.cancel_button);
    cancelBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    logIn_password = save_password_sharePreference.getString("password", logIn_password);
    stateBTN = (Button) findViewById(R.id.second_dialog_button);
    stateBTN.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(View view) {
            switch (mStage) {
                case SIGNUP: //get user password and register it
                    registerPassword();
                    break;
                /*case  SIGNIN_FINGERPRINT:// open sign in with password
                    signInWithPassword();
                    break;*/
                case SIGNIN_PASSWORD://checking passsword entry
                    verifyPassword();
                    break;
            }
        }
    });

} // on create

/**
 * get user password from Edit text , check its lengh , confirm it
 **/
public void registerPassword() {
    String passString = signUp_pasword_editText.getText().toString();
    String confPassString = signUp_conf_password_editText.getText().toString();

    if ((passString.equals(confPassString)) &&
            (passString.length() == 12) &&
            (confPassString.length() == 12)) {
        logIn_password = passString;
        editor_password.putString("password", logIn_password).commit();
        Toast.makeText(this, logIn_password, Toast.LENGTH_LONG).show();
        msg_state_conf.setVisibility(View.VISIBLE);
        msg_state_conf.setText(R.string.msg_conf);
        msg_state_conf.setTextColor(getResources().getColor(R.color.green_color));

        editor_state.putBoolean("signUp", true).commit();
        //state_signUp = true;

        //mina! ***checking fingerPrint sensor***
        /* + : finger primt authorization
        ** - : sign in with password
         */
        mStage = LogUpInActivity.Stage.SIGNIN_PASSWORD;
        signUpContent.setVisibility(View.GONE);
        signIn_passwordContent.setVisibility(View.VISIBLE);
    } else {
        msg_state_conf.setVisibility(View.VISIBLE);
        msg_state_conf.setText(R.string.msg_not_conf);
        msg_state_conf.setTextColor(getResources().getColor(R.color.red_color));
        //not confirm
        editor_state.putBoolean("signUp", false).commit();

    }
}

/**
 * Checks whether the current entered password is correct, and dismisses the the dialog and
 * let's the activity know about the result.
 */
private void verifyPassword() {
    logIn_password = save_password_sharePreference.getString("signUp", logIn_password);
    Toast.makeText(this, logIn_password, Toast.LENGTH_LONG).show();
    if (signIn_password_editText.getText().toString().equals(logIn_password)) {
        startActivity(new Intent(LogActivity.this, MainActivity.class));
        LogActivity.this.finish();
    } else {
        --times_of_signIn;
        Toast.makeText(this, times_of_signIn + "تعداد ورود باقیمانده:", Toast.LENGTH_LONG).show();
        signIn_password_editText.setText(null);

        if (times_of_signIn == 0) {
            Toast.makeText(this, R.string.restart_app, Toast.LENGTH_LONG).show();
            MainActivity.sqlDB.delete(DataBaseClass.BANK_TABLE_NAME, null, null);
            logIn_password = null;
            editor_password.putString("password", logIn_password).commit();
            state_signUp = false;
            editor_state.putBoolean("signUp", state_signUp).commit();
            signIn_passwordContent.setVisibility(View.GONE);
            signUpContent.setVisibility(View.VISIBLE);
            mStage = LogUpInActivity.Stage.SIGNUP;
        }
    }

}

public void onFinish(){
    editor_password.putString("password",logIn_password).commit();

}

/**
 * Enumeration to indicate which authentication method the user is trying to authenticate with.
 */
public enum Stage {
    SIGNUP,
    SIGNIN_FINGERPRINT,
    SIGNIN_PASSWORD
}

@Override
public void fpAuthSuccess() {
    Intent intent=new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);

}

@Override
public void fpAuthFailed(@Nullable String error) {
    Toast.makeText(this,R.string.fingerPrint_retry,Toast.LENGTH_LONG).show();

}

}

but as i run it on Samsung N8000,this error shows me:

FATAL EXCEPTION: main
              java.lang.RuntimeException: Unable to start activity ComponentInfo{...LogActivity}: java.lang.NullPointerException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NullPointerException
                  at banknote.maxsoft.com.banknote.authorization.LogActivity.onCreate(LogActivity.java:135)
                  at android.app.Activity.performCreate(Activity.java:5188)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
                  at android.app.ActivityThread.access$700(ActivityThread.java:140)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:137)
                  at android.app.ActivityThread.main(ActivityThread.java:4921)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:511)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                  at dalvik.system.NativeStart.main(Native Method)


问:
Item count should be 10 but is 0
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?</p>

```<code>private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}
</code>```

答:
You need to make a recursive call use the solution provided in question link provided below

i would recommend use qry.ViewAttributes = "Scope='RecursiveAll'"; to get documents and folders as well
query to get all items in a list including items in the sub folders in sharepoint

ContentLicense: CC BY-SA 2.5

Title: Item count should be 10 but is 0

Body:
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?

private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}


问:
How can i display stack C
How could I display stack when I insert x in to programs.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int Data;
    struct Node* next;
} * top;

void popStack()
{
    struct Node *temp, *var = top;
    if (var == top)
    {
        top = top->next;
        free(var);
    }
    else
        printf("\nStack Empty");
}

void push(int value)
{
    struct Node* temp;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->Data = value;
    if (top == NULL)
    {
        top = temp;
        top->next = NULL;
    }
    else
    {
        temp->next = top;
        top = temp;
    }
}

void display()
{
    struct Node* var = top;
    if (var != NULL)
    {
        printf("\nElements are as:\n");
        while (var != NULL)
        {
            printf("\t%d\n", var->Data);
            var = var->next;
        }
        printf("\n");
    }
    else
        printf("\nStack is Empty");
}

int main(int argc, char* argv[])
{
    printf(" Wellcome to Basic Stacking. \n");
    top = NULL;
    while (1)

    {
</code>```

when i insert "x" I want program to display stack and exit but it does not work after I insert x in this programs it will be infinite loop and don't display the stack and don't exit what should i do????.

```<code>        char x ;

        int value;
        if (value != x)
        {

            printf("please enter Your Name:");
            scanf("%d", &value);
            push(value);
            fflush(stdin);
            display();
        }
        else
        {
            // popStack();
            display();
            break;
        }
    }
    getch();
}
</code>```

答:
Your comparison of value against x always invokes undefined behaviour. The scope of value is the loop body. Effectively you get a "new" value each time you go round the loop.

Your scanf is looking for a number. If you expect the loop to terminate when you press the x key on your keyboard, it is not going to work. The scanf will actually fail because x is not a valid match sequence for %d. On the other hand, if you type in 120 which is the ASCII code for x you might get lucky and see the loop terminate because the undefined behaviour might include reusing the same location for value on each iteration of the loop.

To fix this, define read value before you do the comparison to see if it is x. Also, you'll have to read it using, for example fgets(), then check it to see if it x and then, if it isn't maybe use strtol() or sscanf() to convert it to a number.

Title: How can i display stack C

Body:
How could I display stack when I insert x in to programs.

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int Data;
    struct Node* next;
} * top;

void popStack()
{
    struct Node *temp, *var = top;
    if (var == top)
    {
        top = top->next;
        free(var);
    }
    else
        printf("\nStack Empty");
}

void push(int value)
{
    struct Node* temp;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->Data = value;
    if (top == NULL)
    {
        top = temp;
        top->next = NULL;
    }
    else
    {
        temp->next = top;
        top = temp;
    }
}

void display()
{
    struct Node* var = top;
    if (var != NULL)
    {
        printf("\nElements are as:\n");
        while (var != NULL)
        {
            printf("\t%d\n", var->Data);
            var = var->next;
        }
        printf("\n");
    }
    else
        printf("\nStack is Empty");
}

int main(int argc, char* argv[])
{
    printf(" Wellcome to Basic Stacking. \n");
    top = NULL;
    while (1)

    {

when i insert "x" I want program to display stack and exit but it does not work after I insert x in this programs it will be infinite loop and don't display the stack and don't exit what should i do????.

        char x ;

        int value;
        if (value != x)
        {

            printf("please enter Your Name:");
            scanf("%d", &value);
            push(value);
            fflush(stdin);
            display();
        }
        else
        {
            // popStack();
            display();
            break;
        }
    }
    getch();
}


问:
how to use regexp to validate form input javascript
I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are

( ) { } ' ! # “ \ /

Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).

Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text

Here is HTML code:

```<code><form id="forma_prijava" class="forma_novi_proizvod"  action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
            <label for="unos_naziv_proizvoda">Naziv proizvoda</label>
        <input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
            <label for="unos_opis_proizvoda">Opis proizvoda</label>
        <textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
            <label for="unos_datum_proizvodnje">Datum proizvodnje</label>
        <input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
            <label for="unos_vrijeme_proizvodnje">Vrijeme proizvodnje</label>
        <input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
            <label for="unos_kolicina_proizvodnje">Količina proizvodnje</label>
        <input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">

            <button type="Submit" value="Submit">Dodaj proizvod</button>
            <button type="Reset" value="Reset">Poništi unos</button>
        </form>
</code>```

Here is js code:

```<code>window.onload = function(){
    var provjeri = function(){
        var re = new RegExp(/[^(){}'!#"\/]/, g);
        var uzorak = document.getElementById("forma_prijava"); //id of a form //
        var ok = re.test(uzorak.value);
        if(!ok){
            alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
            return false;
        }
        else{
            alert("OK"); // message if it's valid input //
            return true;
        }
    };
    document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};
</code>```

I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!

答:
You can use property pattern of the input Tag

```<code><input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
</code>```

Body:
I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are

( ) { } ' ! # “ \ /

Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).

Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text

Here is HTML code:

<form id="forma_prijava" class="forma_novi_proizvod"  action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
            Naziv proizvoda
        <input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
            Opis proizvoda
        <textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
            Datum proizvodnje
        <input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
            Vrijeme proizvodnje
        <input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
            Količina proizvodnje
        <input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">

            <button type="Submit" value="Submit">Dodaj proizvod</button>
            <button type="Reset" value="Reset">Poništi unos</button>
        </form>

Here is js code:

window.onload = function(){
    var provjeri = function(){
        var re = new RegExp(/[^(){}'!#"\/]/, g);
        var uzorak = document.getElementById("forma_prijava"); //id of a form //
        var ok = re.test(uzorak.value);
        if(!ok){
            alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
            return false;
        }
        else{
            alert("OK"); // message if it's valid input //
            return true;
        }
    };
    document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};

I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!

Body:
You can use property pattern of the input Tag

<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">


问:
How to use EXPECT_CALL for private member?
How to specify EXPECT_CALL for the private member?

My mocked private member is created in the constructor and calls function write. I get following warning:

GMOCK WARNING:

Uninteresting mock function call - returning directly.
      Function call: write(0x1010, 1)

How to write EXPECT_CALL to disable warning?

答:
Create a separate class for making a expect call to write, the instance of this class should be created in the MainTestClass.

```<code>struct writeMock
{ // make an expect call to write here
};

struct MainTestClass : ::testing::Test
{
MainTestClass() {}

writeMock writeMock_;
// other members here
};
</code>```

this is how your test suite will look like,

```<code>TEST_F(MainTestClass, TestCase1)
{
...
}
</code>```

Body:
Create a separate class for making a expect call to write, the instance of this class should be created in the MainTestClass.

struct writeMock
{ // make an expect call to write here
};

struct MainTestClass : ::testing::Test
{
MainTestClass() {}

writeMock writeMock_;
// other members here
};

this is how your test suite will look like,

TEST_F(MainTestClass, TestCase1)
{
...
}


问:
Modifying Xcode syntax highlighting to gray-out NSAssert lines
I want to modify Xcode syntax highlighting.  Namely, I do a lot of 'NSAsserts', which I find visually distracting, and so I would like lines starting with 'NSAssert' to be a light gray.  This way, I can focus upon my code logic instead of having to cognitively filter-out the NSAssert lines.</p>

答:
I use a lot of these too, and I liked your idea enough to work out the answer. Well, sort of: I have not worked out how to treat NSAsserts as a new item but I have worked out how to make them appear as comments in the syntax highlighter.

Create the directory ~/Library/Application Support/Developer/Shared/Xcode/Specifications

Copy BaseSupport.xclangspec from /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources to that directory

Apply this patch to the new copy:

```
--- /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources/BaseSupport.xclangspec    2010-10-05 00:27:45.000000000 +0100
+++ /Users/philwill/Library/Application Support/Developer/Shared/Xcode/Specifications/BaseSupport.xclangspec    2010-12-14 11:36:51.000000000 +0000
@@ -100,9 +100,8 @@
         Identifier = "xcode.lang.comment.singleline";
         BasedOn = "xcode.lang.comment"; // for text macros
         Syntax = {
-            Start = "//";
-            EscapeChar = "\\";
-            Until = "\n";
+            StartChars = "/N";
+       Match=("//.*$","NSC?Assert[12345]?[[:space:]]*\\([^;]*\\)[[:space:]]*;");
             IncludeRules = ( "xcode.lang.url", "xcode.lang.url.mail", "xcode.lang.comment.mark" );
             Type = "xcode.syntax.comment";
         };
```

Caveats:

This will mess up any //-comments
which contain escaped newline
characters. Don't do that.

This will theoretically slow down
syntax highlighting a little. I
haven't noticed any difference.

This will affect all languages you use in Xcode which normally allow //-comments.

Body:
I use a lot of these too, and I liked your idea enough to work out the answer. Well, sort of: I have not worked out how to treat NSAsserts as a new item but I have worked out how to make them appear as comments in the syntax highlighter.

Create the directory ~/Library/Application Support/Developer/Shared/Xcode/Specifications

Copy BaseSupport.xclangspec from /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources to that directory

Apply this patch to the new copy:

--- /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Versions/A/Resources/BaseSupport.xclangspec    2010-10-05 00:27:45.000000000 +0100
+++ /Users/philwill/Library/Application Support/Developer/Shared/Xcode/Specifications/BaseSupport.xclangspec    2010-12-14 11:36:51.000000000 +0000
@@ -100,9 +100,8 @@
         Identifier = "xcode.lang.comment.singleline";
         BasedOn = "xcode.lang.comment"; // for text macros
         Syntax = {
-            Start = "//";
-            EscapeChar = "\\";
-            Until = "\n";
+            StartChars = "/N";
+       Match=("//.*$","NSC?Assert[12345]?[[:space:]]*\\([^;]*\\)[[:space:]]*;");
             IncludeRules = ( "xcode.lang.url", "xcode.lang.url.mail", "xcode.lang.comment.mark" );
             Type = "xcode.syntax.comment";
         };

Caveats:

This will mess up any //-comments
which contain escaped newline
characters. Don't do that.

This will theoretically slow down
syntax highlighting a little. I
haven't noticed any difference.

This will affect all languages you use in Xcode which normally allow //-comments.


问:
Android how to make webView show pop up input dialog
Pop up like this pic

I tried this setting but didn't work

```<code>webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.setWebViewClient(new WebViewClient());
webview.setWebChromeClient(new WebChromeClient()) ;
</code>```

答: Use alert of of Javascript? Because I don't understand what you want.</p>

Body:
Pop up like this pic

I tried this setting but didn't work

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.setWebViewClient(new WebViewClient());
webview.setWebChromeClient(new WebChromeClient()) ;


问:
How to create an android application by explicitly creating AndroidManifest.xml?
I want to create an android application on the android studio from scratch without using the auto xml layout(AndroidManifest.xml) file generation and rather explicitly creating it by myself.</p>

答:
Using the new-project wizard will create an AndroidManifest.xml file for you, as all projects need one. If you do not want Android Studio to create an  AndroidManifest.xml for you, do not use the new-project wizard.

Instead, you will need to create all of the project files yourself, either by hand or by some other tool that you find or create. Then, import the project into Android Studio, if you wish to use the IDE to further manipulate the project files.


问:
WebRTC mouse pointer
Let's say we have a connection from A to B with webRTC. B sees also his own webcam in a window.
Is it possible to view the A mouse arrow on the B window where his own webcam is shown?

(so if Alice is connected with Bob, Alice can use his pointer to indicate to Bob where is the spoon in Bob's kitchen).

答:
This question has nothing to do with WebRTC: your solution can be implemented using Javascript, but I'm afraid it would be very hard to implement.

I would suggest opening another peer or channel from one client to the other, and sending the mouse pointer coordinates on canvas.onmousemove event.

Title: WebRTC mouse pointer


问:
Python xmlrpclib changes datetime object to DateTime instance on transmit
Messages exchanged between a client and a server using the xmlrpclib using Python 2.6.x creates a type of 'instance' on server side instead of type 'datetime'.
On the client side I create a new

```<code>updateTime = datetime(year, month, day, hour, minute, second)
print type(updateTime)
print updateTime
</code>```

results in

```<code><type 'datetime.datetime'>
2015-10-07 10:21:52
</code>```

when being send, the dictionary looks like this on the client side:

```<code>'updateTime': datetime.datetime(2015, 10, 7, 10, 21, 52)
</code>```

but the incoming dictionary on the server side looks like this:

```<code>'updateTime': <DateTime '20151007T10:21:52' at 7f4dbf4ceb90>
</code>```

printing the type and its string representation looks like this:

```<code><type 'instance'>
20151007T10:21:52
</code>```

We are using xmlrpclib.ServerProxy but changing use_datetime either to True or False does not make any difference at all.

```<code>xmlrpclib.ServerProxy('https://'+rpc_server_addr, allow_none=True, use_datetime=True)
</code>```

Why is this happening? I expected a tpye 'datetime.datetime' on the receiving side as well.

答:
The use_builtin_types=True works for me. All datetime values have type <class 'datetime.datetime'>.

Without this parameter all datetime were <class 'xmlrpc.client.DateTime'>

```<code>rpc = xmlrpc.client.ServerProxy('https://..../', use_builtin_types=True)
</code>```

The Python3 XML-RPC client documentation says:
The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values.

Body:
Messages exchanged between a client and a server using the xmlrpclib using Python 2.6.x creates a type of 'instance' on server side instead of type 'datetime'.
On the client side I create a new

updateTime = datetime(year, month, day, hour, minute, second)
print type(updateTime)
print updateTime

results in

<type 'datetime.datetime'>
2015-10-07 10:21:52

when being send, the dictionary looks like this on the client side:

'updateTime': datetime.datetime(2015, 10, 7, 10, 21, 52)

but the incoming dictionary on the server side looks like this:

'updateTime': <DateTime '20151007T10:21:52' at 7f4dbf4ceb90>

printing the type and its string representation looks like this:

<type 'instance'>
20151007T10:21:52

We are using xmlrpclib.ServerProxy but changing use_datetime either to True or False does not make any difference at all.

xmlrpclib.ServerProxy('https://'+rpc_server_addr, allow_none=True, use_datetime=True)

Why is this happening? I expected a tpye 'datetime.datetime' on the receiving side as well.

Body:
The use_builtin_types=True works for me. All datetime values have type <class 'datetime.datetime'>.

Without this parameter all datetime were <class 'xmlrpc.client.DateTime'>

rpc = xmlrpc.client.ServerProxy('https://..../', use_builtin_types=True)

The Python3 XML-RPC client documentation says:
The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values.


问:
Android in service how to know when screen is locked?
I want to handle an Androids application work in the background. I've read that I have to use services for this.
In this application, I need to know when the screen gets locked and when it gets unlocked again. Every time this happens, I have to do some actions.

For activities, I've seen we have onPause and onRestart for this, but I need to know when the screen is turned off and when it is turned on in a service. How can this information be retrieved from inside a service.

答:
I want create android application work in background , I've read that I have to use the services.

Yes, probably you have to use services to check is screen still on or went off. For example in onCreate of your Services class.

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver broadcast = new MyBroadcastReciverClass(); //or
            registerReceiver(broadcast , intentFilter );

Actually:

```<code>Intent.ACTION_SCREEN_OFF
</code>```

or

```<code>Intent.ACTION_SCREEN_ON
</code>```

Are 2 main things that will have to go in your BroadcastReceiver too. For example in your onReceive method:

```<code>if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        // CODE HERE FOR SCREEN OFF
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        // CODE HERE FOR SCREEN ON
    }
</code>```

For more detailed expnlanation take a look in this article: https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

Body:
I want create android application work in background , I've read that I have to use the services.

Yes, probably you have to use services to check is screen still on or went off. For example in onCreate of your Services class.

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver broadcast = new MyBroadcastReciverClass(); //or
            registerReceiver(broadcast , intentFilter );

Actually:

Intent.ACTION_SCREEN_OFF

or

Intent.ACTION_SCREEN_ON

Are 2 main things that will have to go in your BroadcastReceiver too. For example in your onReceive method:

if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        // CODE HERE FOR SCREEN OFF
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        // CODE HERE FOR SCREEN ON
    }

For more detailed expnlanation take a look in this article: https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/


问:
mysql return a record which is not the same as last record
Here is my query

```<code>SELECT `orders_status_id` FROM orders_status_history
WHERE `orders_id`='15' ORDER BY `date_added` DESC LIMIT 1, 1
</code>```

What I need was to get the second last record from a bunch of records.The above query is working at this point but now I want to place filter that if the second last record is empty or same as last then move one record previous.

As you can see second last record for orders_status_id is 17 (same as the last record) so it should return me "8"(move one step up). Same case applied when the second last record is empty then move one step up. In this example if instead of "8" it was "17" or empty then it should move one more step up until it is not same as last or empty.

thanks

EDITED:
this is the error I am getting

答:
The simplest method may be to use variables:

```<code>SELECT osh.*
FROM (SELECT osh.orders_status_id,
             (@rn := if(@osi = osh.orders_status_id, @rn,
                        if(@osi := osh.orders_status_id, @rn + 1, @rn + 1)
                       )
             ) rn
      FROM orders_status_history osh CROSS JOIN
           (SELECT @rn := 0, @osi := -1) params
      WHERE orders_id = 15
      ORDER BY date_added DESC
     ) osh
WHERE rn = 2
LIMIT 1;
</code>```

This enumerates the different values of order_status_id, choosing the second value that appears.

Body:
Here is my query

SELECT `orders_status_id` FROM orders_status_history
WHERE `orders_id`='15' ORDER BY `date_added` DESC LIMIT 1, 1

What I need was to get the second last record from a bunch of records.The above query is working at this point but now I want to place filter that if the second last record is empty or same as last then move one record previous.

As you can see second last record for orders_status_id is 17 (same as the last record) so it should return me "8"(move one step up). Same case applied when the second last record is empty then move one step up. In this example if instead of "8" it was "17" or empty then it should move one more step up until it is not same as last or empty.

thanks

EDITED:
this is the error I am getting

Body:
The simplest method may be to use variables:

SELECT osh.*
FROM (SELECT osh.orders_status_id,
             (@rn := if(@osi = osh.orders_status_id, @rn,
                        if(@osi := osh.orders_status_id, @rn + 1, @rn + 1)
                       )
             ) rn
      FROM orders_status_history osh CROSS JOIN
           (SELECT @rn := 0, @osi := -1) params
      WHERE orders_id = 15
      ORDER BY date_added DESC
     ) osh
WHERE rn = 2
LIMIT 1;

This enumerates the different values of order_status_id, choosing the second value that appears.


问:
Android Enable Zoom and Pinch Controls in Webview
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

```<code>this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);
</code>```

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

```<code>class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }
</code>```

So I end up creating it like this:

```<code>if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }
</code>```

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}
</code>```

In generateLayout we create the initial layout and create the holder for the webView:

```<code>private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }
</code>```

Then in initUI we create the webView itself:

```<code>@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}
</code>```

答:
here's my code,

```<code>public class PdfViewActivity extends AppCompatActivity {

            private Toolbar mToolbar;
            private TextView mTxtTitleToolbar;
            private WebView mWebViewPdf;
            private String strUrl;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_pdf_view);
                Intent intent = getIntent();
                strUrl = intent.getStringExtra("strUrl");
                setUI();
            }

            private void setUI() {
                mWebViewPdf = (WebView) findViewById(R.id.webview);
                mToolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(mToolbar);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setHomeButtonEnabled(true);
                mTxtTitleToolbar = (TextView) findViewById(R.id.text_toolbar);
                mTxtTitleToolbar.setText("PDF");
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                loadWebView();
            }

            public void loadWebView() {
                mWebViewPdf.setWebViewClient(new myWebClient());
                mWebViewPdf.getSettings().setJavaScriptEnabled(true);
                mWebViewPdf.getSettings().setLoadWithOverviewMode(true);
                mWebViewPdf.getSettings().setUseWideViewPort(true);
                mWebViewPdf.getSettings().setBuiltInZoomControls(true);
                mWebViewPdf.getSettings().setDisplayZoomControls(false);
                mWebViewPdf.loadUrl("http://docs.google.com/gview?embedded=true&url="
+ strUrl.trim());
            }

            public class myWebClient extends WebViewClient {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onPageFini`enter code here`shed(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
            }
        }
</code>```

xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:foo="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/rel_product_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/color_Black"
            app:contentInsetStart="@dimen/d_0"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:theme="@style/AppTheme.AppBarOverlay">

            <customview.CustomTextView
                android:id="@+id/text_toolbar"
                style="@style/TitleTextView"
                android:paddingRight="@dimen/d_40"
                foo:FontEnum="light" />

        </android.support.v7.widget.Toolbar>

    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/rel_product_detail"
        android:cacheColorHint="@color/transparent"
        android:fillViewport="true"
        android:scrollbars="none">

        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </ScrollView> </RelativeLayout>
</code>```

Body:
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }

So I end up creating it like this:

if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}

In generateLayout we create the initial layout and create the holder for the webView:

private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }

Then in initUI we create the webView itself:

@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}

Body:
here's my code,

public class PdfViewActivity extends AppCompatActivity {

            private Toolbar mToolbar;
            private TextView mTxtTitleToolbar;
            private WebView mWebViewPdf;
            private String strUrl;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_pdf_view);
                Intent intent = getIntent();
                strUrl = intent.getStringExtra("strUrl");
                setUI();
            }

            private void setUI() {
                mWebViewPdf = (WebView) findViewById(R.id.webview);
                mToolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(mToolbar);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setHomeButtonEnabled(true);
                mTxtTitleToolbar = (TextView) findViewById(R.id.text_toolbar);
                mTxtTitleToolbar.setText("PDF");
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                loadWebView();
            }

            public void loadWebView() {
                mWebViewPdf.setWebViewClient(new myWebClient());
                mWebViewPdf.getSettings().setJavaScriptEnabled(true);
                mWebViewPdf.getSettings().setLoadWithOverviewMode(true);
                mWebViewPdf.getSettings().setUseWideViewPort(true);
                mWebViewPdf.getSettings().setBuiltInZoomControls(true);
                mWebViewPdf.getSettings().setDisplayZoomControls(false);
                mWebViewPdf.loadUrl("http://docs.google.com/gview?embedded=true&url="
+ strUrl.trim());
            }

            public class myWebClient extends WebViewClient {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onPageFini`enter code here`shed(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
            }
        }

xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:foo="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/rel_product_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/color_Black"
            app:contentInsetStart="@dimen/d_0"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:theme="@style/AppTheme.AppBarOverlay">

            <customview.CustomTextView
                android:id="@+id/text_toolbar"
                style="@style/TitleTextView"
                android:paddingRight="@dimen/d_40"
                foo:FontEnum="light" />

        </android.support.v7.widget.Toolbar>

    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/rel_product_detail"
        android:cacheColorHint="@color/transparent"
        android:fillViewport="true"
        android:scrollbars="none">

        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </ScrollView> </RelativeLayout>


问:
Which is the Java Type for a PHP Project in PDT Eclipse PHP Development Tools
Does PHP Project also inherits from org.eclipse.core.resources.IProject ?

Thank you!

答:
All Eclipse projects of any type have an IProject.

The different types of project may also have their own project type with additional information. For example a Java project has IJavaProject. I don't know what PDT uses.


问:
NameError: name 'urlpatterns' is not defined
I'm trying to show an image using "ImageField"

```<code>from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

settings.py:

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"
</code>```

答:
```<code>from django.contrib import admin
from django.conf.urls import include, url

urlpatterns=[
url(r'^admin/', include(admin.site.urls))
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

write this total code in your urls.py

Body:
I'm trying to show an image using "ImageField"

from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    )
MEDIA_ROOT = ''
MEDIA_URL = "/media/"

Body:
from django.contrib import admin
from django.conf.urls import include, url

urlpatterns=[
url(r'^admin/', include(admin.site.urls))
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

write this total code in your urls.py


问:
Not understanding the FAIL/PASS in casperjs
I am using casperjs/phantomjs with this code

```<code>casper.test.begin('assertEquals() tests', 3, function(test) {
    test.assertEquals(1 + 1, 3);
    test.assertEquals([1, 2, 3], [1]);
    test.assertEquals({a: 1, b: 2}, {a: 1, b: 4});
    test.done();
});
</code>```

In the console I get Failed tests as expected but what I can't understand is why the test suite is marked as PASS

```<code>PASS assertEquals() tests (3 tests)
FAIL 1 test executed in 0.029s, 0 passed, 1 failed, 0 dubious, 0 skipped.
</code>```

答:
I didn't regonized that before like this, but you also get the Error-Messages of the failing (first) equal.

The last PASS is just saying that casperjs is finished with the testsuite, no matter what is failing inside the suite.

This is the full log:

```<code>    root@4332425a143d:/casperjs# casperjs test test.js
    Test file: test.js
    # assertEquals() tests
    FAIL Subject equals the expected value
    #    type: assertEquals
    #    file: test.js
    #    subject: 2
    #    expected: 3
    PASS assertEquals() tests (3 tests)
    FAIL 1 test executed in 0.025s, 0 passed, 1 failed, 0 dubious, 0 skipped.
</code>```

So that says that the first equals fails and the suite "assertEquals()" finished.

Body:
I am using casperjs/phantomjs with this code

casper.test.begin('assertEquals() tests', 3, function(test) {
    test.assertEquals(1 + 1, 3);
    test.assertEquals([1, 2, 3], [1]);
    test.assertEquals({a: 1, b: 2}, {a: 1, b: 4});
    test.done();
});

In the console I get Failed tests as expected but what I can't understand is why the test suite is marked as PASS

PASS assertEquals() tests (3 tests)
FAIL 1 test executed in 0.029s, 0 passed, 1 failed, 0 dubious, 0 skipped.

Body:
I didn't regonized that before like this, but you also get the Error-Messages of the failing (first) equal.

The last PASS is just saying that casperjs is finished with the testsuite, no matter what is failing inside the suite.

This is the full log:

    root@4332425a143d:/casperjs# casperjs test test.js
    Test file: test.js
    # assertEquals() tests
    FAIL Subject equals the expected value
    #    type: assertEquals
    #    file: test.js
    #    subject: 2
    #    expected: 3
    PASS assertEquals() tests (3 tests)
    FAIL 1 test executed in 0.025s, 0 passed, 1 failed, 0 dubious, 0 skipped.

So that says that the first equals fails and the suite "assertEquals()" finished.


问:
Using the AutoComplete feature of ComboBox, while limiting values to those in the list?
In WinForms 2.0, a ComboBox has an Auto-Complete feature, that displays a custom Drop-Down list with only the values that start with the entered text.

However, if I want to limit valid values to only those that appear in the ComboBox's list of items, I can do that by setting the DropDownStyle to DropDownList, which stops the user from entering a value.

However, now I can't use the Auto-Complete feature, which requires user input.

Is there another way to limit input to the list, while still allowing use of the Auto-Complete feature? Note that I have seen some custom solutions for this, but I really like the way the matching Auto-Complete items are displayed in a Drop-Down list, and sorted even though the original list may not be.

EDIT: I have thought about just validating the entered value, i.e. testing user input if it is valid in, say, the TextChanged event, or even using the Validating event. The question then is what is the expected behavior? Do I clear their value (an empty value is also invalid), or do I use a default value? Closest matching value?

P.s. Is there any other tags that I could add to this question?

答:
You could hook the keypress or textchanged event and validate that the text entered was an initial substring match for at least one of the list items, rejecting the keypress (or deleting the most recent character) if not. The only issue I can think of with this is that it may be a bit confusing to the user that some input is not accepted (particularly when typing the first character, at which point the autocomplete list won't be visible yet, so they won't know what valid values are).

Or just use it in dropdownlist mode - people can still type and it will jump to the first matching list item...

OwnerDisplayName: Schmuli

LastEditorDisplayName: DJ