问:
Firebase database not updating
After changing a few codes in my java application my firebase database stopped updating info. I even set the rules readable to avoid any permission problem.

Here is my rules:

```<code>{
  "rules": {
      ".read": true,
      ".write": true
  }
}
</code>```

And here is my java code:

```<code>package com.bogroup.ucuncuprogram;

import android.content.Context;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static com.facebook.FacebookSdk.getApplicationContext;

public class database{

    public void kullanicikontrol(String kullaniciadi,DatabaseReference mDatabase){

        mDatabase.child("users").child(kullaniciadi).setValue("9999999");
        //mDatabase.child("users").setValue("9999999");

        //chieldref.setValue("9999999");

        Context context = getApplicationContext();
        CharSequence text = kullaniciadi;
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

    }
}
</code>```

For the record i checked it with debugger and can see my firebase url and value kullaniciadi.

Edit: Below i added the class which calls this class to make database editing.

```<code>package com.bogroup.ucuncuprogram;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import static com.bogroup.ucuncuprogram.R.id.textView2;

public class ikinciekren extends AppCompatActivity{

    public EditText sayi;
    public TextView sayilar;
    public TextView bilgisayarinattigi;
    public TextView tv;
    public String esassonuc;
    public String bilgisayarsallama;
    public String bilgisayarsallama2;
    public sayisalla sallama;
    public database kullanici;
    public String bilgisayarsayisi;
    private String m_Text = "";
    //private Firebase mRootRef;
    public String idToken;
    public String myuid;
    private DatabaseReference mDatabase;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ImageView fbphoto;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ikinciekran);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Oyuna başlamak için 4 basamaklı sayınızı giriniz !");
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_NUMBER);
        int maxLength = 4;
        input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                m_Text = input.getText().toString();
                tv.setText("Saynız: "+m_Text);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
        sallama = new sayisalla();
        tv = (TextView) findViewById(R.id.textView);
        sayi = (EditText) findViewById(R.id.editText3);
        sayilar = (TextView) findViewById(textView2);
        bilgisayarinattigi = (TextView) findViewById(R.id.textView3);
        mDatabase = FirebaseDatabase.getInstance().getReference();
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            String name = user.getDisplayName();
            String email = user.getEmail();
            Uri photoUrl = user.getPhotoUrl();
            String uid = user.getUid();
            myuid = uid;
            bilgisayarsayisi = sallama.sayiat();
            sallama.yarat();

            fbphoto = (ImageView) findViewById(R.id.imageView1);
            boolean emailVerified = user.isEmailVerified();
            Picasso.with(this) // Context
                    .load(photoUrl) // URL or file
                    .into(fbphoto);

        }
        sayi.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sayi.setText("");
            }

        });
    }
    public void sayiat(View v){
        if (v.getId()==R.id.button2){
            if (sayilar.getText().toString().equals("")) {
                String b = sayi.getText().toString();
                esassonuc = sallama.dondur(b,bilgisayarsayisi,0);
                sayilar.setText(esassonuc);
                kullanici = new database();
                kullanici.kullanicikontrol(myuid,mDatabase);
                sayilar.setMovementMethod(new ScrollingMovementMethod());
                final int scrollAmount = sayilar.getLayout().getLineTop(sayilar.getLineCount()) - sayilar.getHeight();
                if (scrollAmount > 0) {
                    sayilar.scrollTo(0, scrollAmount);
                }else {
                    sayilar.scrollTo(0, 0);
                }
            }else{
                if (sayi.getText().length()==4) {
                    String a = sayilar.getText().toString();
                    String b = sayi.getText().toString();
                    esassonuc = sallama.dondur(b,bilgisayarsayisi,0);
                    sayilar.setText(a + "\n" + esassonuc+" aa ");
                    kullanici = new database();
                    kullanici.kullanicikontrol(myuid,mDatabase);
                    sayilar.setMovementMethod(new ScrollingMovementMethod());
                    final int scrollAmount = sayilar.getLayout().getLineTop(sayilar.getLineCount()) - sayilar.getHeight();
                    if (scrollAmount > 0) {
                        sayilar.scrollTo(0, scrollAmount);
                    }else {
                        sayilar.scrollTo(0, 0);
                    }
                }
            }
            if(!"++++".equals(esassonuc)){
                bilgisayarsallama2 = sallama.sayiyarat();
                bilgisayarsallama = sallama.dondur(bilgisayarsallama2,m_Text,1);
                if (bilgisayarinattigi.getText().toString()=="") {
                    bilgisayarinattigi.setText(bilgisayarsallama);
                }else{
                        String a = bilgisayarinattigi.getText().toString();
                        bilgisayarinattigi.setText(a + "\n" + bilgisayarsallama);
                        bilgisayarinattigi.setMovementMethod(new ScrollingMovementMethod());
                        final int scrollAmount = bilgisayarinattigi.getLayout().getLineTop(bilgisayarinattigi.getLineCount()) - bilgisayarinattigi.getHeight();
                        if (scrollAmount > 0) {
                            bilgisayarinattigi.scrollTo(0, scrollAmount);
                        }else {
                            bilgisayarinattigi.scrollTo(0, 0);
                        }
                }
            }else{
                toast("LOST");
            }
        }
    }
    public void cikis(View view) {
        if(view.getId()==R.id.button3){
            FirebaseAuth.getInstance().signOut();
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            finish();
        }
    }
    public void toast(String msg){
        Context context = getApplicationContext();
        CharSequence text = msg;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}
</code>```

答:
Please try these formalities.</p>

```<code>private DatabaseReference ref;
private FirebaseDatabase database;
database = FirebaseDatabase.getInstance();
ref= database.getReference("users");
ref.child(kullaniciadi).setValue("9999999");
</code>```

Title: Firebase database not updating

Body:
After changing a few codes in my java application my firebase database stopped updating info. I even set the rules readable to avoid any permission problem.

Here is my rules:

{
  "rules": {
      ".read": true,
      ".write": true
  }
}

And here is my java code:

package com.bogroup.ucuncuprogram;

import android.content.Context;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static com.facebook.FacebookSdk.getApplicationContext;

public class database{

    public void kullanicikontrol(String kullaniciadi,DatabaseReference mDatabase){

        mDatabase.child("users").child(kullaniciadi).setValue("9999999");
        //mDatabase.child("users").setValue("9999999");

        //chieldref.setValue("9999999");

        Context context = getApplicationContext();
        CharSequence text = kullaniciadi;
        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

    }
}

For the record i checked it with debugger and can see my firebase url and value kullaniciadi.

Edit: Below i added the class which calls this class to make database editing.

package com.bogroup.ucuncuprogram;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import static com.bogroup.ucuncuprogram.R.id.textView2;

public class ikinciekren extends AppCompatActivity{

    public EditText sayi;
    public TextView sayilar;
    public TextView bilgisayarinattigi;
    public TextView tv;
    public String esassonuc;
    public String bilgisayarsallama;
    public String bilgisayarsallama2;
    public sayisalla sallama;
    public database kullanici;
    public String bilgisayarsayisi;
    private String m_Text = "";
    //private Firebase mRootRef;
    public String idToken;
    public String myuid;
    private DatabaseReference mDatabase;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ImageView fbphoto;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ikinciekran);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Oyuna başlamak için 4 basamaklı sayınızı giriniz !");
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_NUMBER);
        int maxLength = 4;
        input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                m_Text = input.getText().toString();
                tv.setText("Saynız: "+m_Text);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
        sallama = new sayisalla();
        tv = (TextView) findViewById(R.id.textView);
        sayi = (EditText) findViewById(R.id.editText3);
        sayilar = (TextView) findViewById(textView2);
        bilgisayarinattigi = (TextView) findViewById(R.id.textView3);
        mDatabase = FirebaseDatabase.getInstance().getReference();
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            String name = user.getDisplayName();
            String email = user.getEmail();
            Uri photoUrl = user.getPhotoUrl();
            String uid = user.getUid();
            myuid = uid;
            bilgisayarsayisi = sallama.sayiat();
            sallama.yarat();

            fbphoto = (ImageView) findViewById(R.id.imageView1);
            boolean emailVerified = user.isEmailVerified();
            Picasso.with(this) // Context
                    .load(photoUrl) // URL or file
                    .into(fbphoto);

        }
        sayi.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sayi.setText("");
            }

        });
    }
    public void sayiat(View v){
        if (v.getId()==R.id.button2){
            if (sayilar.getText().toString().equals("")) {
                String b = sayi.getText().toString();
                esassonuc = sallama.dondur(b,bilgisayarsayisi,0);
                sayilar.setText(esassonuc);
                kullanici = new database();
                kullanici.kullanicikontrol(myuid,mDatabase);
                sayilar.setMovementMethod(new ScrollingMovementMethod());
                final int scrollAmount = sayilar.getLayout().getLineTop(sayilar.getLineCount()) - sayilar.getHeight();
                if (scrollAmount > 0) {
                    sayilar.scrollTo(0, scrollAmount);
                }else {
                    sayilar.scrollTo(0, 0);
                }
            }else{
                if (sayi.getText().length()==4) {
                    String a = sayilar.getText().toString();
                    String b = sayi.getText().toString();
                    esassonuc = sallama.dondur(b,bilgisayarsayisi,0);
                    sayilar.setText(a + "\n" + esassonuc+" aa ");
                    kullanici = new database();
                    kullanici.kullanicikontrol(myuid,mDatabase);
                    sayilar.setMovementMethod(new ScrollingMovementMethod());
                    final int scrollAmount = sayilar.getLayout().getLineTop(sayilar.getLineCount()) - sayilar.getHeight();
                    if (scrollAmount > 0) {
                        sayilar.scrollTo(0, scrollAmount);
                    }else {
                        sayilar.scrollTo(0, 0);
                    }
                }
            }
            if(!"++++".equals(esassonuc)){
                bilgisayarsallama2 = sallama.sayiyarat();
                bilgisayarsallama = sallama.dondur(bilgisayarsallama2,m_Text,1);
                if (bilgisayarinattigi.getText().toString()=="") {
                    bilgisayarinattigi.setText(bilgisayarsallama);
                }else{
                        String a = bilgisayarinattigi.getText().toString();
                        bilgisayarinattigi.setText(a + "\n" + bilgisayarsallama);
                        bilgisayarinattigi.setMovementMethod(new ScrollingMovementMethod());
                        final int scrollAmount = bilgisayarinattigi.getLayout().getLineTop(bilgisayarinattigi.getLineCount()) - bilgisayarinattigi.getHeight();
                        if (scrollAmount > 0) {
                            bilgisayarinattigi.scrollTo(0, scrollAmount);
                        }else {
                            bilgisayarinattigi.scrollTo(0, 0);
                        }
                }
            }else{
                toast("LOST");
            }
        }
    }
    public void cikis(View view) {
        if(view.getId()==R.id.button3){
            FirebaseAuth.getInstance().signOut();
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            finish();
        }
    }
    public void toast(String msg){
        Context context = getApplicationContext();
        CharSequence text = msg;
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

Body:
Please try these formalities.

private DatabaseReference ref;
private FirebaseDatabase database;
database = FirebaseDatabase.getInstance();
ref= database.getReference("users");
ref.child(kullaniciadi).setValue("9999999");


来源: stackexchange

问:
How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?
Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.

package com.example.android.generalknowledge;

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int baseScore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void submitResult(View view) {
        RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
        boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();

        RadioButton insects = (RadioButton) findViewById(R.id.insects);
        boolean answerIsInsects = insects.isChecked();

        CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
        boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();

        CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
        boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();

        CheckBox literature = (CheckBox) findViewById(R.id.literature);
        boolean literatureIsAnswer = literature.isChecked();

        CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
        boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();

        RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
        boolean answerIsNaziParty = naziParty.isChecked();

        RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
        boolean answerIsAll = allOfTheAbove.isChecked();

        RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
        boolean answerIsFilmFinance = filmFinance.isChecked();

        EditText enterNameHere = (EditText) findViewById(R.id.name_view);
        String name = enterNameHere.getText().toString();

        EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
        String answer = enterAnswerHere.getText().toString();
        if (enterAnswerHere.getText().toString().equals("Africa")) {
            baseScore += 1 ;
        }

        int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
                physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);

        Toast.makeText(MainActivity.this,
                name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
    }

    /**
     * This method is called when any of the radio buttons in question one is selected
     */

    public void onRadioButtonClickedOne(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.largest_railway_station:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.highest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.longest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none_of_the_above:
                if (checked)
                    //Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question two is selected
     */

    public void onRadioButtonClickedTwo(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.behaviour_of_human_beings:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.insects:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.origin_history:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.rock_formation:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when the checkboxes for question three are clicked
     */

    public void onCheckboxThreeClicked(View view) {
        //Is the button now checked?
        boolean checked = ((CheckBox) view).isChecked();

        // Check which checkbox is clicked
        switch (view.getId()) {
            case R.id.physics_chemistry:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.physiology_medicine:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.literature:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.peace_economics:
                if (checked)
                    // One of the Correct answers
                    break;
        }
    }

    /**
     * This method is called when any of the radio buttons in question four is selected
     */

    public void onRadioButtonClickedFour(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.labour_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.nazi_party:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.leading_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.democratic_party:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question six is selected
     */

    public void onRadioButtonClickedSix(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.develop_telescope:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.discovered_jupiter:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.movement_of_pendulum:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.all_of_the_above:
                if (checked)
                    // This is the correct answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question seven is selected
     */

    public void onRadioButtonClickedSeven(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.foreign_finance:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.film_finance:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.federation_football:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
                                    boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
                                    boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {

        if (questionOneAnswer) {
            baseScore += 1 ;
        }

        if (questionTwoAnswer) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer1) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer2) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer3) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer4) {
            baseScore += 1 ;
        }

        if (questionFourAnswer) {
            baseScore += 1 ;
        }

        if (questionSixAnswer) {
            baseScore += 1 ;
        }

        if (questionSevenAnswer) {
            baseScore += 1 ;
        }

       // EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
       // String answer = enterAnswerHere.getText().toString();
       // {
        //    if (answer == "Africa") {
        //        baseScore = baseScore + 1;
        //    }
       // }
        return baseScore;
    }
}
</code>```

答:
You can use handler for this may be there is better solution then this.

```<code>Handler mHandler=new Handler();
</code>```

//now in your click listener

```<code>        mHandler.removeCallbacks(mRunnable);//
        mHandler.postDelayed(mRunnable, 500);

        Runnable mRunnable  =new Runnable() {
        @Override
        public void run() {
            //calculate it
        }
    };
</code>```

//Wait for half sec before calculating the result if user clicked before then  stop runnable from calcualting and again go for calculation.
Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.

package com.example.android.generalknowledge;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int baseScore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void submitResult(View view) {
        RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
        boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();

        RadioButton insects = (RadioButton) findViewById(R.id.insects);
        boolean answerIsInsects = insects.isChecked();

        CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
        boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();

        CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
        boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();

        CheckBox literature = (CheckBox) findViewById(R.id.literature);
        boolean literatureIsAnswer = literature.isChecked();

        CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
        boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();

        RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
        boolean answerIsNaziParty = naziParty.isChecked();

        RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
        boolean answerIsAll = allOfTheAbove.isChecked();

        RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
        boolean answerIsFilmFinance = filmFinance.isChecked();

        EditText enterNameHere = (EditText) findViewById(R.id.name_view);
        String name = enterNameHere.getText().toString();

        EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
        String answer = enterAnswerHere.getText().toString();
        if (enterAnswerHere.getText().toString().equals("Africa")) {
            baseScore += 1 ;
        }

        int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
                physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);

        Toast.makeText(MainActivity.this,
                name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
    }

    /**
     * This method is called when any of the radio buttons in question one is selected
     */

    public void onRadioButtonClickedOne(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.largest_railway_station:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.highest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.longest_railway_station:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none_of_the_above:
                if (checked)
                    //Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question two is selected
     */

    public void onRadioButtonClickedTwo(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.behaviour_of_human_beings:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.insects:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.origin_history:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.rock_formation:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when the checkboxes for question three are clicked
     */

    public void onCheckboxThreeClicked(View view) {
        //Is the button now checked?
        boolean checked = ((CheckBox) view).isChecked();

        // Check which checkbox is clicked
        switch (view.getId()) {
            case R.id.physics_chemistry:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.physiology_medicine:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.literature:
                if (checked)
                    // One of the Correct answers
                    break;
        }
        switch (view.getId()) {
            case R.id.peace_economics:
                if (checked)
                    // One of the Correct answers
                    break;
        }
    }

    /**
     * This method is called when any of the radio buttons in question four is selected
     */

    public void onRadioButtonClickedFour(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.labour_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.nazi_party:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.leading_party:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.democratic_party:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question six is selected
     */

    public void onRadioButtonClickedSix(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.develop_telescope:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.discovered_jupiter:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.movement_of_pendulum:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.all_of_the_above:
                if (checked)
                    // This is the correct answer
                    break;
        }

    }

    /**
     * This method is called when any of the radio buttons in question seven is selected
     */

    public void onRadioButtonClickedSeven(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.foreign_finance:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.film_finance:
                if (checked)
                    // This is the correct answer
                    break;
            case R.id.federation_football:
                if (checked)
                    // Wrong answer
                    break;
            case R.id.none:
                if (checked)
                    // Wrong answer
                    break;
        }

    }

    private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
                                    boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
                                    boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {

        if (questionOneAnswer) {
            baseScore += 1 ;
        }

        if (questionTwoAnswer) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer1) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer2) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer3) {
            baseScore += 1 ;
        }

        if (questionThreeAnswer4) {
            baseScore += 1 ;
        }

        if (questionFourAnswer) {
            baseScore += 1 ;
        }

        if (questionSixAnswer) {
            baseScore += 1 ;
        }

        if (questionSevenAnswer) {
            baseScore += 1 ;
        }

       // EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
       // String answer = enterAnswerHere.getText().toString();
       // {
        //    if (answer == "Africa") {
        //        baseScore = baseScore + 1;
        //    }
       // }
        return baseScore;
    }
}

Body:
You can use handler for this may be there is better solution then this.

Handler mHandler=new Handler();

//now in your click listener

        mHandler.removeCallbacks(mRunnable);//
        mHandler.postDelayed(mRunnable, 500);

        Runnable mRunnable  =new Runnable() {
        @Override
        public void run() {
            //calculate it
        }
    };

//Wait for half sec before calculating the result if user clicked before then  stop runnable from calcualting and again go for calculation.
Hope it helps.


问:
cannot align ion-label to the right end
```<code> <ion-card>
<ion-card-content>
 <ion-label>Total Price</ion-label><ion-label text-right>Due Date</ion-label>
  <ion-label>xxx</ion-label><ion-label text-right>xxx</ion-label>
</ion-card-content></ion-card>
</code>```

Cannot align "Total Price" and "Due Date" in the same line.I need to align "Total Price" to the left end and the "Due Date" to the right end! Give me the best solution guys!

答:
You can try using ion-row and ion-col to make sure your text appears in a single row.

```<code> <ion-card>
<ion-card-content>
  <ion-row>
   <ion-col col-6>
    <ion-label>Total Price</ion-label>
   </ion-col>
   <ion-col col-6>
    <ion-label text-right>Due Date</ion-label>
   </ion-col>
   </ion-row>
   <ion-row>
    <ion-col col-6>
     <ion-label>xxx</ion-label>
    </ion-col>
    <ion-col col-6>
     <ion-label text-right>xxx</ion-label>
    <ion-col>
   <ion-row>
</ion-card-content></ion-card>
</code>```

Title: cannot align ion-label to the right end

Body:
 <ion-card>
<ion-card-content>
 <ion-label>Total Price</ion-label><ion-label text-right>Due Date</ion-label>
  <ion-label>xxx</ion-label><ion-label text-right>xxx</ion-label>
</ion-card-content></ion-card>

Cannot align "Total Price" and "Due Date" in the same line.I need to align "Total Price" to the left end and the "Due Date" to the right end! Give me the best solution guys!

Body:
You can try using ion-row and ion-col to make sure your text appears in a single row.

 <ion-card>
<ion-card-content>
  <ion-row>
   <ion-col col-6>
    <ion-label>Total Price</ion-label>
   </ion-col>
   <ion-col col-6>
    <ion-label text-right>Due Date</ion-label>
   </ion-col>
   </ion-row>
   <ion-row>
    <ion-col col-6>
     <ion-label>xxx</ion-label>
    </ion-col>
    <ion-col col-6>
     <ion-label text-right>xxx</ion-label>
    <ion-col>
   <ion-row>
</ion-card-content></ion-card>


问:
Embed wxmplot window in wxpython frame
Is it possible to embed the wxm multiplot window in a wx main frame?
This site ( http://newville.github.io/wxmplot/other.html#multiplotframe ) gives details about how to get a multiplot but the plot is displayed as separate window. I want to create a GUI with wx widgets but I am unable to put them all in the same window frame. </p>

答:
Well, MultiPlotFrame is a frame that contains some PlotPanels, so you can't do it directly, but look as the source code of multiframe

https://github.com/newville/wxmplot/blob/master/lib/multiframe.py

I guess you can pretty much take it almost as it is and turn it into something like MultiPlotPanel, and use that in your frame.

Title: Embed wxmplot window in wxpython frame


问:
Alert opens every time and not only the first time
I want my alert to only open the first time the app is launched on a new device but it currently opens every time the app is closed in multitasking and opened again. I have attached my code if anyone is able to help please?</p>

```<code>    override func viewDidAppear(_ animated: Bool) {
        // alert first time app is opened
        // making of alert

        let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

        //add ok button
        alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

        // detect if first launch
        let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
        if launchedBefore {
        }
        else {
            self.present(alert, animated: true, completion: nil)
            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }
    }
</code>```

答: There is a typo in your keys... While writing it you are using key launchedBefore  but when read it you are using launcedBefore

Body:
I want my alert to only open the first time the app is launched on a new device but it currently opens every time the app is closed in multitasking and opened again. I have attached my code if anyone is able to help please?

    override func viewDidAppear(_ animated: Bool) {
        // alert first time app is opened
        // making of alert

        let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

        //add ok button
        alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

        // detect if first launch
        let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
        if launchedBefore {
        }
        else {
            self.present(alert, animated: true, completion: nil)
            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }
    }


问:
error while building the apk in android
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        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.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}
</code>```

答:
You have too many methods. There can only be 65536 methods for dex.

So, enable multidex as following:

```<code> android {
    defaultConfig {
        // Enabling multidex support.
        multiDexEnabled true
    }
}

dependencies {
 compile 'com.android.support:multidex:1.0.0'
 }
</code>```

Title: error while building the apk in android

Body:
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        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.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}

Body:
You have too many methods. There can only be 65536 methods for dex.

So, enable multidex as following:

 android {
    defaultConfig {
        // Enabling multidex support.
        multiDexEnabled true
    }
}

dependencies {
 compile 'com.android.support:multidex:1.0.0'
 }


问:
lodash - Move object to first place in array?
I have an array of objects, with type of fruit/vegetable:

For the one type vegetable I have, I want it to be the first item in the array, but I am not sure how to do so with lodash.

```<code>var items = [
    {'type': 'fruit', 'name': 'apple'},
    {'type': 'fruit', 'name': 'banana'},
    {'type': 'vegetable', 'name': 'brocolli'}, // how to make this first item
    {'type': 'fruit', 'name': 'cantaloupe'}
];
</code>```

Here is a fiddle with my attempt:
https://jsfiddle.net/zg6js8af/

How can I get type vegetable to be the first item in the array regardless of its current index?

答:
Why use lodash when you do not need it (and can write functional code using a single reduce) ?

var items = [
  {'type': 'fruit', 'name': 'apple'},
  {'type': 'fruit', 'name': 'banana'},
  {'type': 'vegetable', 'name': 'brocolli'},
  {'type': 'fruit', 'name': 'cantaloupe'}
];

var final = items.reduce(function(arr,v) {
  if (v.type === 'vegetable') return [v].concat(arr)
  arr.push(v)
  return arr
},[]);
alert(JSON.stringify(final));
```

Body:
I have an array of objects, with type of fruit/vegetable:

For the one type vegetable I have, I want it to be the first item in the array, but I am not sure how to do so with lodash.

var items = [
    {'type': 'fruit', 'name': 'apple'},
    {'type': 'fruit', 'name': 'banana'},
    {'type': 'vegetable', 'name': 'brocolli'}, // how to make this first item
    {'type': 'fruit', 'name': 'cantaloupe'}
];

Here is a fiddle with my attempt:
https://jsfiddle.net/zg6js8af/

How can I get type vegetable to be the first item in the array regardless of its current index?


答:
You can disable the submit button once it is clicked. For eg:

```<code>onclick() {
   submitbutton.setEnabled(false);
}
</code>```

Prevent user to click on submit again and again.

You can enable it back using:

```<code>submitbutton.setEnabled(true);
</code>```

Title: How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?

Body:
You can disable the submit button once it is clicked. For eg:

onclick() {
   submitbutton.setEnabled(false);
}

Prevent user to click on submit again and again.

You can enable it back using:

submitbutton.setEnabled(true);


问:
Maven M2_HOME set to an invalid directory (Windows 7)
I've tried installing Maven to Windows 7 with poor results. Some basic info:

Maven installation directory:   C:\Program Files\Apache Software Foundation\apache-maven-3.0.4
System Variable "M2_HOME":  C:\Program Files\Apache Software Foundation\apache-maven-3.0.4\
System Variable "Path" :  %M2_HOME%apache-maven\src\bin;%JAVA_HOME%\bin

If I run mvn --version in the command path, I get the error message:

Please set the M2_HOME variable in your environment to match the location of the Maven installation

So at the moment the subdirectory for mvn is not set according to the instructions, which would be %M2_HOME%\bin. If I replace %M2_HOME%apache-maven\src\bin with that one, I get:

mvn is not recognized as an internal or external command, operable program or batch file

In the Maven installation directory (or in the zip-file) there is no \bin folder directly in apache-maven-3.0.4 and I wonder if there should be one?

I'm a complete novice to Maven, hopefully you guys can help.

By the way the Java command works from any directory, so I don't think that's the issue here, but I can't be sure.

答: set 'M2_HOME' and 'PATH' in environment variables for your account, remove 'PATH' from system environment variables.</p>


问:
stemming library in java
Is there any library for stemming in java!? </p>

答: There is an implementation of Porter's stemmer available on his website. The code is not very Java-ish, but it does what it's supposed to, plus it's only a single class.</p>

ContentLicense: CC BY-SA 2.5

Title: stemming library in java


问:
Send Textviews throught Whatsapp
I need to send all textview of a layout as string through whatsapp method, but if the textview is null must send a blank text.

this is my code:

```<code>public void sendButton(View view) {
    // Do something in response to button

    PackageManager pm = getPackageManager();
    try {

        TextView textview3 = (TextView) findViewById(R.id.textAmor3);
        TextView textview2 = (TextView) findViewById(R.id.textAmor2);

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");

        if (textview3 == null) {

        } else {

        }

        String both = textview2 + "-" + textview3;

        PackageInfo info = pm.getPackageInfo("com.whatsapp",
        PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, both );

        startActivity(Intent.createChooser(waIntent, "Share with"));

    } catch (PackageManager.NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }
}
}
</code>```

What do i must to do ?

thanks

答:
Change this

String both = textview2 + "-" + textview3;

to

String both = textview2.getText().toString() + "-" + textview3.getText().toString();

Title: Send Textviews throught Whatsapp

Body:
I need to send all textview of a layout as string through whatsapp method, but if the textview is null must send a blank text.

this is my code:

public void sendButton(View view) {
    // Do something in response to button

    PackageManager pm = getPackageManager();
    try {

        TextView textview3 = (TextView) findViewById(R.id.textAmor3);
        TextView textview2 = (TextView) findViewById(R.id.textAmor2);

        Intent waIntent = new Intent(Intent.ACTION_SEND);
        waIntent.setType("text/plain");

        if (textview3 == null) {

        } else {

        }

        String both = textview2 + "-" + textview3;

        PackageInfo info = pm.getPackageInfo("com.whatsapp",
        PackageManager.GET_META_DATA);
        //Check if package exists or not. If not then code
        //in catch block will be called
        waIntent.setPackage("com.whatsapp");

        waIntent.putExtra(Intent.EXTRA_TEXT, both );

        startActivity(Intent.createChooser(waIntent, "Share with"));

    } catch (PackageManager.NameNotFoundException e) {
        Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
                .show();
    }
}
}

What do i must to do ?

thanks


问:
WebGL - Set multiple vertices
I'm trying to translate some TypeScript code into a vertex shader to use with WebGL. My goal is to draw the bitangent lines of two circles. I have a function to calculate the tangent points here, https://jsfiddle.net/Zanchi/4xnp1n8x/2/ on line 27. Essentially, it returns a tuple of points with x and y values.

```<code>// First circle bottom tangent point
const t1 = {
  x: x1 + r1 * cos(PI/2 - alpha),
  y: y1 + r1 * sin(PI/2 - alpha)
}; //... and so on
</code>```

I know I can do the calcuation in JS and pass the values to the shader via an attribute, but I'd like to leverage the GPU to do the point calculations instead.

Is it possible to set multiple vertices in a single vertex shader call, or use multiple values calculated in the first call of the shader in subsequent calls?

答:
Is it possible to set multiple vertices in a single vertex shader call

No

or use multiple values calculated in the first call of the shader in subsequent calls?

No

A vertex shader outputs 1 vertex per iteration/call. You set the number of iterations when you call gl.drawArrays (gl.drawElements is more complicated)

I'm not sure you gain much by not just putting the values in an attribute. It might be fun to generate them in the vertex shader but it's probably not performant.

In WebGL1 there is no easy way to use a vertex shader to generate data. First off you'd need some kind of count or something that changes for each iteration and there is nothing that changes if you don't supply at least one attribute. You could supply one attribute with just a count [0, 1, 2, 3, ...] and use that count to generate vertices. This is what vertexshaderart.com does but it's all for fun, not for perf.

In WebGL2 there is the gl_VertexID built in variable which means you get a count for free, no need to supply an attribute. In WebGL2 you can also use transform feedback to write the output of a vertex shader to a buffer. In that way you can generate some vertices once into a buffer and then use the generated vertices from that buffer (and therefore probably get better performance than generating them every time).

Title: WebGL - Set multiple vertices

Body:
I'm trying to translate some TypeScript code into a vertex shader to use with WebGL. My goal is to draw the bitangent lines of two circles. I have a function to calculate the tangent points here, https://jsfiddle.net/Zanchi/4xnp1n8x/2/ on line 27. Essentially, it returns a tuple of points with x and y values.

// First circle bottom tangent point
const t1 = {
  x: x1 + r1 * cos(PI/2 - alpha),
  y: y1 + r1 * sin(PI/2 - alpha)
}; //... and so on

I know I can do the calcuation in JS and pass the values to the shader via an attribute, but I'd like to leverage the GPU to do the point calculations instead.

Is it possible to set multiple vertices in a single vertex shader call, or use multiple values calculated in the first call of the shader in subsequent calls?


问:
I am creating a sample website. How do I check how it looks on mobile devices?
I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?</p>

答:
use ngrok. It will expose the local/dev servers using their services. This command line tool will give you a resolvable url.

To use

```<code>$ ngrok http 80
</code>```

will expose the web server running on port 80.

```<code>ngrok by @inconshreveable
(Ctrl+C to quit)

Session Status                online
Version                       2.2.4
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://dbg6f82d.ngrok.io -> localhost:80

Forwarding                    https://dbf8f82d.ngrok.io -> localhost:80
</code>```

This will be accessible across the internet.

Body:
use ngrok. It will expose the local/dev servers using their services. This command line tool will give you a resolvable url.

To use

$ ngrok http 80

will expose the web server running on port 80.

ngrok by @inconshreveable
(Ctrl+C to quit)

Session Status                online
Version                       2.2.4
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://dbg6f82d.ngrok.io -> localhost:80

Forwarding                    https://dbf8f82d.ngrok.io -> localhost:80

This will be accessible across the internet.


问:
What is a fractal?
Duplicate of How to program a fractal

What are fractals?

Is this is one of the concepts that is brought over from Mathematics to programming to simplify or solve a particular set of problems?

 I am closing this question and have posted a related  question

答: Look up Procedural Generation for one way of how fractals are used in programming.  They are an excellent way of generating chaotic/seemingly complex data from a very simple source.  The generated data often benefits from self-similarity and other bits of organzation that make the content make more sense to people.</p>

OwnerDisplayName: Nick

Title: What is a fractal?

LastEditorDisplayName: Nick

OwnerDisplayName: Josh


问:
Sign Certificate with custom CA on runtime
Hallo, what specific functions do i have to use to generate certificate and programmaticaly sign it with my custom CA. I cant find anything useful in the openssl documentation. Thx for answer</p>

答: I recommend to look at the source of the respective command line tools, e.g. the ca subcommand. You'll find fragments of code that you can glue together to your needs.</p>


问:
Count the number of null values into an Oracle table?
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

```<code> CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');
</code>```

Now, I write the following code to compute the number of null values in the table TEST:

```<code>declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/
</code>```

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.

答:
The dynamic SQL you execute (this is the string used in EXECUTE IMMEDIATE) should be

```<code>select sum(
    decode(a,null,1,0)
    +decode(b,null,1,0)
    +decode(c,null,1,0)
    ) nullcols
from test;
</code>```

Where each summand corresponds to a NOT NULL column.

Here only one table scan is necessary to get the result.

Body:
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

 CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');

Now, I write the following code to compute the number of null values in the table TEST:

declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.

Body:
The dynamic SQL you execute (this is the string used in EXECUTE IMMEDIATE) should be

select sum(
    decode(a,null,1,0)
    +decode(b,null,1,0)
    +decode(c,null,1,0)
    ) nullcols
from test;

Where each summand corresponds to a NOT NULL column.

Here only one table scan is necessary to get the result.


问:
Phantom SWT Button Images?
I'm working on an old SWT (specifically, it's RCP) project and it has a virtual keyboard.  I added functionality to optionally have an image instead of a character.  When the button configuration is toggled from image back to button, it sometimes shows one of the other defined images AND the character.  I created a pop-up that reveals whether or not button.getImage() is null and when this phantom image is there, it is actually null, so the button seems to be constructed correctly, but is there some sort of dispose or redraw that I should be performing when switching back and forth between image and character?  Is there something else I'm doing wrong?

For control purposes, I created two buttons elsewhere in the application for testing and found that it still occurs:

testButton = new Button(buttonBar, SWT.PUSH);
testButton.setText("Test Button");
testButton.setEnabled(true);
testButton.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-51.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton.setImage(resizedImage);
            originalImage.dispose();
            testButton.setText("");
        } else {
            testButton.setImage(null);
            testButton.setText("Test Button");
        }
    }
});
testButton1 = new Button(buttonBar, SWT.PUSH);
testButton1.setText("Test Button 1");
testButton1.setEnabled(true);
testButton1.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton1.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-52.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton1.setImage(resizedImage);
            originalImage.dispose();
            testButton1.setText("");
        } else {
            testButton1.setImage(null);
            testButton1.setText("Test Button 1");
        }
    }
});
```

This is in Win7, Java 8_131, Eclipse Neon.

Here's an example of what I see.  The phantom image is behind the text in the right button.

答:
I got your problem Chris. What you are doing is that you are creating image each time you click on button.

Solution:

Create Image somewhere else, may be in constructor and reuse the
same image. your code should not create image object at runtime,
because creating image object is a heavy operation.

Code snippet: https://github.com/skumbha/testrepo/blob/master/TestDialog2.java

Optional:

Use testButton1.addSelectionListener(new SelectionAdapter() {}); instead of mouse down listener for buttons.( you will see lots of examples over net)

Use Jface Image registry to create image.

Looks like you are using JfaceDialog's "buttonbar", instead you can override createButtonsForButtonBar() method to create button in "buttonbar" and override buttonPressed()  method to add listeners for those buttons.

Code snippet: https://github.com/skumbha/testrepo/blob/master/TestDialog.java

You will get plenty of examples over net for each step.

Title: Phantom SWT Button Images?

Body:
I'm working on an old SWT (specifically, it's RCP) project and it has a virtual keyboard.  I added functionality to optionally have an image instead of a character.  When the button configuration is toggled from image back to button, it sometimes shows one of the other defined images AND the character.  I created a pop-up that reveals whether or not button.getImage() is null and when this phantom image is there, it is actually null, so the button seems to be constructed correctly, but is there some sort of dispose or redraw that I should be performing when switching back and forth between image and character?  Is there something else I'm doing wrong?

For control purposes, I created two buttons elsewhere in the application for testing and found that it still occurs:

testButton = new Button(buttonBar, SWT.PUSH);
testButton.setText("Test Button");
testButton.setEnabled(true);
testButton.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-51.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton.setImage(resizedImage);
            originalImage.dispose();
            testButton.setText("");
        } else {
            testButton.setImage(null);
            testButton.setText("Test Button");
        }
    }
});
testButton1 = new Button(buttonBar, SWT.PUSH);
testButton1.setText("Test Button 1");
testButton1.setEnabled(true);
testButton1.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton1.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-52.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton1.setImage(resizedImage);
            originalImage.dispose();
            testButton1.setText("");
        } else {
            testButton1.setImage(null);
            testButton1.setText("Test Button 1");
        }
    }
});

This is in Win7, Java 8_131, Eclipse Neon.

Here's an example of what I see.  The phantom image is behind the text in the right button.


问:
How to include jars from libs folder to another jar?
I have Gradle JAR (Main) project. I have other commons-io jars (dependent) that I would like to package them with the Main JAR. I tried below, but when I decompile Main JAR, I see all the dependent JARS inside libs folder with .jar extension.

```<code>jar {
    from("$projectDir") {
        include 'libs/**'
    }
}
</code>```

What I want is the class files from all the dependent JARs into Main JAR. I am doing this because the Main JAR is going to be used by multiple projects. So that way, I do not have to include all the dependent JARs.

Thanks

答:
use this.</p>

```<code>into(libForderName){
        from {
            configurations.compile.collect {
                it.isDirectory() ? it : it.getAbsoluteFile()
            }
        }
    }
</code>```

Body:
I have Gradle JAR (Main) project. I have other commons-io jars (dependent) that I would like to package them with the Main JAR. I tried below, but when I decompile Main JAR, I see all the dependent JARS inside libs folder with .jar extension.

jar {
    from("$projectDir") {
        include 'libs/**'
    }
}

What I want is the class files from all the dependent JARs into Main JAR. I am doing this because the Main JAR is going to be used by multiple projects. So that way, I do not have to include all the dependent JARs.

Thanks

Body:
use this.

into(libForderName){
        from {
            configurations.compile.collect {
                it.isDirectory() ? it : it.getAbsoluteFile()
            }
        }
    }


问:
Convert into a For Comprehension in Scala
Testing this I can see that it works:

```<code>def twoHtmlFutures = Action { request =>

  val async1 = as1.index(embed = true)(request) // Future[Result]
  val async2 = as2.index(embed = true)(request) // Future[Result]

  val async1Html = async1.flatMap(x => Pagelet.readBody(x)) // Future[Html]
  val async2Html = async2.flatMap(x => Pagelet.readBody(x)) // Future[Html]

  val source1 = Source.fromFuture(async1Html) // Source[Html, NotUsed]
  val source2 = Source.fromFuture(async2Html) // Source[Html, NotUsed]

  val merged = source1.merge(source2) // Source[Html, NotUsed]
  Ok.chunked(merged)
}
</code>```

But trying to put it into a For Comprehension is not working for me. This is what I tried:

```<code>def twoHtmlFutures2 = Action.async { request =>

  val async1 = as1.index(embed = true)(request)
  val async2 = as2.index(embed = true)(request)

  for {
    async1Res <- async1 // from Future[Result] to Result
    async2Res <- async2 // from Future[Result] to Result

    async1Html <- Pagelet.readBody(async1Res) // from Result to Html
    async2Html <- Pagelet.readBody(async2Res) // from Result to Html

  } yield {
    val source1 = single(async1Html) // from Html to Source[Html, NotUsed]
    val source2 = single(async2Html) // from Html to Source[Html, NotUsed]

    val merged = source1.merge(source2) // Source[Html, NotUsed]
    Ok.chunked(merged)
  }

}
</code>```

But this just jumps on-screen at the same time rather than at different times (streamed) as the first example does. Any helpers out there to widen my eyelids?Thanks

答:
Here's what your proposed for comprehension looks like after it's been desugared (courtesy of IntelliJ's "Desugar Scala code ..." menu option):

```<code>async1.flatMap((async1Res: Nothing) =>
  async2.flatMap((async2Res: Nothing) =>
    Pagelet.readBody(async1Res).flatMap((async1Html: Nothing) =>
      Pagelet.readBody(async2Res).map((async2Html: Nothing) =>
        Ok.chunked(merged)))))
</code>```

As you can see, the nesting, and the concluding flatMap/map pair, are very different from your original code plan.

As a general rule, every <- in a single for comprehension is turned into a flatMap() except for the final one, which is a map(), and each is nested inside the previous.

Body:
Testing this I can see that it works:

def twoHtmlFutures = Action { request =>

  val async1 = as1.index(embed = true)(request) // Future[Result]
  val async2 = as2.index(embed = true)(request) // Future[Result]

  val async1Html = async1.flatMap(x => Pagelet.readBody(x)) // Future[Html]
  val async2Html = async2.flatMap(x => Pagelet.readBody(x)) // Future[Html]

  val source1 = Source.fromFuture(async1Html) // Source[Html, NotUsed]
  val source2 = Source.fromFuture(async2Html) // Source[Html, NotUsed]

  val merged = source1.merge(source2) // Source[Html, NotUsed]
  Ok.chunked(merged)
}

But trying to put it into a For Comprehension is not working for me. This is what I tried:

def twoHtmlFutures2 = Action.async { request =>

  val async1 = as1.index(embed = true)(request)
  val async2 = as2.index(embed = true)(request)

  for {
    async1Res <- async1 // from Future[Result] to Result
    async2Res <- async2 // from Future[Result] to Result

    async1Html <- Pagelet.readBody(async1Res) // from Result to Html
    async2Html <- Pagelet.readBody(async2Res) // from Result to Html

  } yield {
    val source1 = single(async1Html) // from Html to Source[Html, NotUsed]
    val source2 = single(async2Html) // from Html to Source[Html, NotUsed]

    val merged = source1.merge(source2) // Source[Html, NotUsed]
    Ok.chunked(merged)
  }

}

But this just jumps on-screen at the same time rather than at different times (streamed) as the first example does. Any helpers out there to widen my eyelids?Thanks

Body:
Here's what your proposed for comprehension looks like after it's been desugared (courtesy of IntelliJ's "Desugar Scala code ..." menu option):

async1.flatMap((async1Res: Nothing) =>
  async2.flatMap((async2Res: Nothing) =>
    Pagelet.readBody(async1Res).flatMap((async1Html: Nothing) =>
      Pagelet.readBody(async2Res).map((async2Html: Nothing) =>
        Ok.chunked(merged)))))

As you can see, the nesting, and the concluding flatMap/map pair, are very different from your original code plan.

As a general rule, every <- in a single for comprehension is turned into a flatMap() except for the final one, which is a map(), and each is nested inside the previous.


问:
How to prevent attacks on WordPress wp-login.php page
On my website, the highest GPU usage is actually on the WordPress login page, not the home page. I have basically come to the conclusion that it is being attacked by a brute force attack, or something similar.

I have installed a plugin that prevents password attacks from bots, but it doesn't prevent the bots from actually visiting the page in the first place.

I want to change the location of the login page to something like wp-login-here.php, or perhaps there is a better solution. The Stealth Plugin seems like it would do the trick, but it is not compatible with recent versions of WordPress. Any ideas?

EDIT: The real solution to this problem was for me to do a clean install of WordPress, this time in a version that was supported by the Stealth plugin. After installing WP and the Stealth plugin on this earlier version of WP, I used the .htaccess file that the plugin created and copied it over (after making a few modifications) to the production site. The reason I accepted the answer I did was because Bad Behavior ended up being a good plugin, and the other advice was useful.

答:
How would I go about adding a password to a single file?

Add this to WP's current .htaccess:

```<code><FilesMatch "wp-login.php">
    AuthName "WordPress Admin"
    AuthType Basic
    AuthUserFile /path/to/.htpasswd
    require valid-user
</FilesMatch>
</code>```

Body:
How would I go about adding a password to a single file?

Add this to WP's current .htaccess:

<FilesMatch "wp-login.php">
    AuthName "WordPress Admin"
    AuthType Basic
    AuthUserFile /path/to/.htpasswd
    require valid-user
</FilesMatch>


问:
Hide a button in onload using angularjs
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

```<code>                <form id="show_details">

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>

<script>
    var app = angular
                    .module("intranet_App", [])
                    .controller(function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                       if($scope.editMode){
                          $scope.editMode = false;
                       }else{
                           $scope.editMode = true;
                       }
                    }
                    })
</script>
</code>```

答:
Try this using ng-show

```<code>  <button ng-show="editMode" class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
  <button ng-show="!editMode" class="btn btn-primary" id="projectDetailsUpdate" ng-click="goEvent()">Update</button>
</code>```

Title: Hide a button in onload using angularjs

Body:
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

                <form id="show_details">

                        Project Name
                        <input type="text">

                        Client
                        <input type="text">

                        Project Co-ordinator
                        <input type="text" disabled="true" >

                        Client Co-ordinator
                        <input type="text">

                        Resource
                        <input type="text" disabled="true">

                </form>

                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>

Body:
Try this using ng-show

  <button ng-show="editMode" class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
  <button ng-show="!editMode" class="btn btn-primary" id="projectDetailsUpdate" ng-click="goEvent()">Update</button>


问:
How to check whether the launch is first launch and include tutorial-LibGDX
I want to create a tutorial of my game for the first launch of game. Next time tutorial should not occur.
For this, I created a boolean value to be stored in preference to indicate whether the launch is first or not.

My singleton preference class is included here:

```<code>public class FirstLaunchNotifier {

    public static final FirstLaunchNotifier INSTANCE = new FirstLaunchNotifier();

    private final Preferences prefs;

    private static final String LAUNCH_KEY = "launch";
    private static final String PREF_NAME = "TMS";

    /* if false->first launch with tutorial.else if true->no tutorial */
    private boolean launchBoolean;

    public FirstLaunchNotifier() {
        prefs = Gdx.app.getPreferences(PREF_NAME);
        launchBoolean = prefs.getBoolean(LAUNCH_KEY, false);
    }

    public void saveLaunchState() {
        launchBoolean = true;
        prefs.putBoolean(LAUNCH_KEY, launchBoolean);
        prefs.flush();
    }

    public boolean getLaunchBoolean() {
    //  System.out.println("launch::: "+launchBoolean);
        return launchBoolean;

    }
</code>```

in my gamescreen class,currently I have update() method that I am calling inside render().

For tutorial part of first play of first launch,I want to call a separate update method tutorialUpdate().
I am confused of how to get this launchBool value properly with this update() and tutorialUpdate().

Once the tutorial is finished,game should come back to normal play.Before that saveLaunchState() should be called so that launchboolean become true to indicate that first play is over and no more tutorial required.

This is how I calls update() right now in render().

```<code>case RUN:
    update(delta);
break;
</code>```

Do i need to get the boolean value like this?

```<code>if(FirstLaunchNotifier.INSTANCE.getLaunchBoolean()) {
     update(delta);
     tutorial update();
}else{
     update(delta);
}
</code>```

Which is the proper way to do this?

答:
FirstLaunchNotifier as a singleton.

```<code>public class FirstLaunchNotifier {

    private static FirstLaunchNotifier instance;
    private  Preferences prefs;
    private boolean launchBoolean;

    private static final String LAUNCH_KEY = "launch";
    private static final String PREF_NAME = "TMS";

    private FirstLaunchNotifier(){

        prefs= Gdx.app.getPreferences(PREF_NAME);
        launchBoolean = prefs.getBoolean(LAUNCH_KEY, true);
    }

    public static FirstLaunchNotifier getInstance(){

        if(instance==null){
            instance=new FirstLaunchNotifier();
        }
        return instance;
    }

    public void saveLaunchState(boolean state) {
        launchBoolean=state;
        prefs.putBoolean(LAUNCH_KEY, launchBoolean);
        prefs.flush();
    }

    public boolean getLaunchBoolean() {
        return launchBoolean;
    }
}
</code>```

You can get object of FirstLaunchNotifier by FirstLaunchNotifier.getInstance() and do calculation according to your requirement like

```<code>if(FirstLaunchNotifier.getInstance().getLaunchBoolean()) {
     update(delta);
     tutorial update();
}else{
     update(delta);
}
</code>```

And when user completed tutorial part then just call

```<code>FirstLaunchNotifier.getInstance().saveLaunchState(false);
</code>```

Body:
I want to create a tutorial of my game for the first launch of game. Next time tutorial should not occur.
For this, I created a boolean value to be stored in preference to indicate whether the launch is first or not.

My singleton preference class is included here:

public class FirstLaunchNotifier {

    public static final FirstLaunchNotifier INSTANCE = new FirstLaunchNotifier();

    private final Preferences prefs;

    private static final String LAUNCH_KEY = "launch";
    private static final String PREF_NAME = "TMS";

    /* if false->first launch with tutorial.else if true->no tutorial */
    private boolean launchBoolean;

    public FirstLaunchNotifier() {
        prefs = Gdx.app.getPreferences(PREF_NAME);
        launchBoolean = prefs.getBoolean(LAUNCH_KEY, false);
    }

    public void saveLaunchState() {
        launchBoolean = true;
        prefs.putBoolean(LAUNCH_KEY, launchBoolean);
        prefs.flush();
    }

    public boolean getLaunchBoolean() {
    //  System.out.println("launch::: "+launchBoolean);
        return launchBoolean;

    }

in my gamescreen class,currently I have update() method that I am calling inside render().

For tutorial part of first play of first launch,I want to call a separate update method tutorialUpdate().
I am confused of how to get this launchBool value properly with this update() and tutorialUpdate().

Once the tutorial is finished,game should come back to normal play.Before that saveLaunchState() should be called so that launchboolean become true to indicate that first play is over and no more tutorial required.

This is how I calls update() right now in render().

case RUN:
    update(delta);
break;

Do i need to get the boolean value like this?

if(FirstLaunchNotifier.INSTANCE.getLaunchBoolean()) {
     update(delta);
     tutorial update();
}else{
     update(delta);
}

Which is the proper way to do this?

Body:
FirstLaunchNotifier as a singleton.

public class FirstLaunchNotifier {

    private static FirstLaunchNotifier instance;
    private  Preferences prefs;
    private boolean launchBoolean;

    private static final String LAUNCH_KEY = "launch";
    private static final String PREF_NAME = "TMS";

    private FirstLaunchNotifier(){

        prefs= Gdx.app.getPreferences(PREF_NAME);
        launchBoolean = prefs.getBoolean(LAUNCH_KEY, true);
    }

    public static FirstLaunchNotifier getInstance(){

        if(instance==null){
            instance=new FirstLaunchNotifier();
        }
        return instance;
    }

    public void saveLaunchState(boolean state) {
        launchBoolean=state;
        prefs.putBoolean(LAUNCH_KEY, launchBoolean);
        prefs.flush();
    }

    public boolean getLaunchBoolean() {
        return launchBoolean;
    }
}

You can get object of FirstLaunchNotifier by FirstLaunchNotifier.getInstance() and do calculation according to your requirement like

if(FirstLaunchNotifier.getInstance().getLaunchBoolean()) {
     update(delta);
     tutorial update();
}else{
     update(delta);
}

And when user completed tutorial part then just call

FirstLaunchNotifier.getInstance().saveLaunchState(false);


问:
MSBuild 15 - The type or namespace 'Fakes' does not exist in the namespace
I'm trying to set up automated builds and unit testing for a project which uses the Fakes library for it's unit tests. The project builds and tests fine on my Windows 10 PC (VS 2017 Enterprise installed), however using the same command to compile the project on the build server (also windows 10 with VS 2017 Enterprise) gives several errors about the Fakes not existing. The exact errors look like this:

XControllerTests.cs(10,20): error CS0234: The type or namespace 'Fakes' does not exist in the namespace 'System.Data.Common' (are you missing an assembly reference?) [C:\Runner\builds\xxx\XTests.csproj]

From my research, this is caused by using an old version of MSBuild, however I have checked the server, and confirmed it has the latest version & updates for visual studio installed. I also confirmed that the build script is using the correct version of MSBuild.exe, which is c:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe. Using this version on my desktop correctly compiles the project.

Why does the build not work on the (identical setup) build server?

答:
I have some workaround but It's not elegant.

You need to check path C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0 if there is Fakes folder. If not you need to install TestTools workload or copy from another machine.

Next you need to check C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Microsoft.Common.Targets\ImportAfter if there is file Microsoft.QualityTools.Testing.Fakes.ImportAfter.targets if not copy it from another machine. In this file is code for including fakes target to build process.

And finally you need to check if you have assembly Microsoft.QualityTools.Testing.Fakes.dll in GAC or another location where MSBuild find it.

This I did on my build machine with MS Build Tools 2017 and now build generate fakes assemblies.


问:
Jhipster or Spring Data JPA
I have a question related with pagination with native query. I need to retrieve
data between two dates and I don't want to lose pagination.  How to handle it? (And we are using Local Date) . Thanx</p>

答:
I would resolve it by using @Query annotation. Besides, I used Pageable object. If u fill the pageable object properly, u can manage it readily. Furthermore, sometimes, u can need to use @Param annotation. Look at the last sample in 5.3.4 Using Query and 5.3.6. Using named parameters.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query </p>

Title: Jhipster or Spring Data JPA


问:
No resource identifier found for attribute 'srcCompat' in package 'learnapp.android.example.com.learnapp'
I am getting Error:(26) No resource identifier found for attribute 'srcCompat' in package 'learnapp.android.example.com.learnapp'
when I try to run my app.I have just started learning android today.I have added a new activity and dint change anything in any xml files.

This is the exact error:

```<code>Documents/MyProjects/LearnApp/app/src/main/res/layout/activity_display_message.xml
Error:(26) No resource identifier found for attribute 'srcCompat' in package 'learnapp.android.example.com.learnapp'
</code>```

Here is my activity_display_message.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="learnapp.android.example.com.learnapp.DisplayMessageActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_display_message" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</LinearLayout>
</code>```

I have already read similar questions and saw that either the line

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

or

```<code>app:srcCompat="@android:drawable/ic_dialog_email" />
</code>```

was wrong in their case which is not in my case.

Incase it matters this activity's parent activity is MainActivity.java

答:
i got the similar issue.

my instructor try update API 22 to API 25, and it's work.
maybe you could try on the same.

Body:
I am getting Error:(26) No resource identifier found for attribute 'srcCompat' in package 'learnapp.android.example.com.learnapp'
when I try to run my app.I have just started learning android today.I have added a new activity and dint change anything in any xml files.

This is the exact error:

Documents/MyProjects/LearnApp/app/src/main/res/layout/activity_display_message.xml
Error:(26) No resource identifier found for attribute 'srcCompat' in package 'learnapp.android.example.com.learnapp'

Here is my activity_display_message.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="learnapp.android.example.com.learnapp.DisplayMessageActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_display_message" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</LinearLayout>

I have already read similar questions and saw that either the line

xmlns:app="http://schemas.android.com/apk/res-auto"

or

app:srcCompat="@android:drawable/ic_dialog_email" />

was wrong in their case which is not in my case.

Incase it matters this activity's parent activity is MainActivity.java


问:
How to get FlaskForm data using JQuery ajax
I'm trying to send a jquery ajax request using the field data from a flask form. I can currently get something like this to work... to send the form data as an ajax request to my python code that's running behind the scenes.

html

```<code><form id=test_form name="form_name">
  <input type="text" name="form_text">
  <input type="submit" value="Submit">
</form>
</code>```

javascript

```<code>$(function() {
  $('form#test_form').bind('submit', function() {
    $.getJSON('/_ard_connect', {
      var1: $('input[name="form_text"]').val()
    }, function(data) {
      $("#some_result").text(data.result);
    });
    return false;
  });
});
</code>```

python

```<code>@app.route('/_test_link')
def test_link():
    var1 = request.args.get('var1')
    answer = doSomething(var1)
    return jsonify( result=answer )
</code>```

if I define a FlaskForm like this:

```<code>class MyForm(FlaskForm):
    test_form = StringField(label='tt')

myform = MyForm()
</code>```

is it possible to pass something like var1: $('{{ myform.test_form.data }} ').val() to my getJSON function.

alternative(?)

I've also tired abstracting my ajax javascript and passing the form data as an argument

```<code><form id=test_form action="javascript: somefunc('{{ ardu.port.data }}')">
</code>```

but it will only get the default value...

答:
Case 1:

You can't do this in javascript file. Instead you can do that in view render template file ( html )

file.html

```<code>var1: $('{{ myform.test_form.data }} ').val()
</code>```

Case 2:

I think you are doing to update the action url based on some javascript function but this is also wrong. This somefunc can't execute itself in onload. Instead try window.onload method and execute the somefunc update the test_form url

Body:
I'm trying to send a jquery ajax request using the field data from a flask form. I can currently get something like this to work... to send the form data as an ajax request to my python code that's running behind the scenes.

html

<form id=test_form name="form_name">
  <input type="text" name="form_text">
  <input type="submit" value="Submit">
</form>

javascript

$(function() {
  $('form#test_form').bind('submit', function() {
    $.getJSON('/_ard_connect', {
      var1: $('input[name="form_text"]').val()
    }, function(data) {
      $("#some_result").text(data.result);
    });
    return false;
  });
});

python

@app.route('/_test_link')
def test_link():
    var1 = request.args.get('var1')
    answer = doSomething(var1)
    return jsonify( result=answer )

if I define a FlaskForm like this:

class MyForm(FlaskForm):
    test_form = StringField(label='tt')

myform = MyForm()

is it possible to pass something like var1: $('{{ myform.test_form.data }} ').val() to my getJSON function.

alternative(?)

I've also tired abstracting my ajax javascript and passing the form data as an argument

<form id=test_form action="javascript: somefunc('{{ ardu.port.data }}')">

but it will only get the default value...

Body:
Case 1:

You can't do this in javascript file. Instead you can do that in view render template file ( html )

file.html

var1: $('{{ myform.test_form.data }} ').val()

Case 2:

I think you are doing to update the action url based on some javascript function but this is also wrong. This somefunc can't execute itself in onload. Instead try window.onload method and execute the somefunc update the test_form url


问:
Ajaxify link so that it still accesses address on click but doesn't change page
I've got a link that removes an item from a cart, except that when you click that link it redirects you to the cart with the item now removed. Is it possible to make it so that you can still click it and it still does its thing but it doesn' change the page (i.e. it doesn't send the user to the cart)?

Note: I'm working with Liquid on Shopify

Link:

                {{ 'cart.general.remove' | t }}
```

答:
You can make use of cart js instead for make your things work as you want. Here is the details on shopify cart js - cart js Reference

The best way will be to send the line item number through the CartJS.removeItem function. You can also remove a cart item by it's id using removeItemById.

It provides cart.requestComplete event listener where you can code to reload your page after remove item request is completed.