问:
how do I stop timer from showing up in my other levels?
I made a game with 3 levels, easy,normal, and hard.

easy has 300 seconds before the timeup activity shows up,
normal has 600 seconds ,
hard has 900 seconds

for example, I chose easy but I lose so I went back to choose what level I would take next. I chose normal but the timer page for easy shows up.

how do I stop the TIMER from popping up in my other levels.

I am missing something

activity for level:

```<code>public class EasyAct extends AppCompatActivity {
    Button b1, b2, b3, b4;
    TextView tv1, tv2, tv3, tv4;
    int score =0;
    TriviaQuizHelper1 triviaQuizHelper1;
    TriviaQuestion1 currentQuestion;
    List<TriviaQuestion1> list;
    int qid = 0;
    int level = 1;

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

        tv1 = (TextView) findViewById(R.id.triviaQuestion);
        tv2 = (TextView) findViewById(R.id.triviTimer);
        b1 = (Button) findViewById(R.id.buttonA);
        b2 = (Button) findViewById(R.id.buttonB);
        b3 = (Button) findViewById(R.id.buttonC);
        b4 = (Button) findViewById(R.id.buttonD);
        tv3 = (TextView) findViewById(R.id.level);
        tv4 = (TextView) findViewById(R.id.score);
        CountDownTimer countDownTimer = new CountDownTimer(300 * 1000, 1000) {
            @Override
            public void onTick(long l) {
                tv2.setText("Timer:" + l / 1000 + " " + "sec");
            }

            @Override
            public void onFinish() {
                tv2.setText("TIME OUT");
                Intent intent = new Intent(EasyAct.this, timeup.class);
                startActivity(intent);
            }
        };
        countDownTimer.start();
        triviaQuizHelper1 = new TriviaQuizHelper1(this);
        SQLiteDatabase sqLiteDatabase = triviaQuizHelper1.getWritableDatabase();
        triviaQuizHelper1.allQuestion1();
        list = triviaQuizHelper1.getAllQuestion();
        currentQuestion = list.get(qid);
        view();
    }

    public void view() {
        tv1.setText(currentQuestion.getQuestion());
        b1.setText(" "+currentQuestion.getOpta());
        b2.setText(" "+currentQuestion.getOptb());
        b3.setText(" "+currentQuestion.getOptc());
        b4.setText(" "+currentQuestion.getOptd());
        tv3.setText("Level:"+level);
        tv4.setText("Score:"+score);
    }

    public void ButtonA(View view) {

        if (b1.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonB(View view) {
        if (b2.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonC(View view) {
        if (b3.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonD(View view) {
        if (b4.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    @Override
    public void onBackPressed() {
        Intent a = new Intent(Intent.ACTION_MAIN);
        a.addCategory(Intent.CATEGORY_HOME);
        a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(a);
        finish();

    }
}
</code>```

答:
You need to stop the timer before you switch activities. If you don't, the new activity will be displayed on the screen, but the timer from the old activity can still fire. To do this explicitly, you'll need a reference to the timer that you can access outside of your onCreate() method. A simple way to do this is by declaring your CountDownTimer as a class field. Then you can access the variable anywhere inside this class.

```<code>public class EasyAct extends AppCompatActivity {
    Button b1, b2, b3, b4;
    TextView tv1, tv2, tv3, tv4;
    int score =0;
    TriviaQuizHelper1 triviaQuizHelper1;
    TriviaQuestion1 currentQuestion;
    List<TriviaQuestion1> list;
    // declaring CountDownTimer as a class field
    CountDownTimer countDownTimer;
    int qid = 0;
    int level = 1;

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

        tv1 = (TextView) findViewById(R.id.triviaQuestion);
        tv2 = (TextView) findViewById(R.id.triviTimer);
        b1 = (Button) findViewById(R.id.buttonA);
        b2 = (Button) findViewById(R.id.buttonB);
        b3 = (Button) findViewById(R.id.buttonC);
        b4 = (Button) findViewById(R.id.buttonD);
        tv3 = (TextView) findViewById(R.id.level);
        tv4 = (TextView) findViewById(R.id.score);

        // initializing the CountDownTimer instance
        countDownTimer = new CountDownTimer(300 * 1000, 1000) {
            @Override
            public void onTick(long l) {
                tv2.setText("Timer:" + l / 1000 + " " + "sec");
            }
</code>```

Then you can call countDownTimer.stop() before you call startActivity().

Body:
I made a game with 3 levels, easy,normal, and hard.

easy has 300 seconds before the timeup activity shows up,
normal has 600 seconds ,
hard has 900 seconds

for example, I chose easy but I lose so I went back to choose what level I would take next. I chose normal but the timer page for easy shows up.

how do I stop the TIMER from popping up in my other levels.

I am missing something

activity for level:

public class EasyAct extends AppCompatActivity {
    Button b1, b2, b3, b4;
    TextView tv1, tv2, tv3, tv4;
    int score =0;
    TriviaQuizHelper1 triviaQuizHelper1;
    TriviaQuestion1 currentQuestion;
    List<TriviaQuestion1> list;
    int qid = 0;
    int level = 1;

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

        tv1 = (TextView) findViewById(R.id.triviaQuestion);
        tv2 = (TextView) findViewById(R.id.triviTimer);
        b1 = (Button) findViewById(R.id.buttonA);
        b2 = (Button) findViewById(R.id.buttonB);
        b3 = (Button) findViewById(R.id.buttonC);
        b4 = (Button) findViewById(R.id.buttonD);
        tv3 = (TextView) findViewById(R.id.level);
        tv4 = (TextView) findViewById(R.id.score);
        CountDownTimer countDownTimer = new CountDownTimer(300 * 1000, 1000) {
            @Override
            public void onTick(long l) {
                tv2.setText("Timer:" + l / 1000 + " " + "sec");
            }

            @Override
            public void onFinish() {
                tv2.setText("TIME OUT");
                Intent intent = new Intent(EasyAct.this, timeup.class);
                startActivity(intent);
            }
        };
        countDownTimer.start();
        triviaQuizHelper1 = new TriviaQuizHelper1(this);
        SQLiteDatabase sqLiteDatabase = triviaQuizHelper1.getWritableDatabase();
        triviaQuizHelper1.allQuestion1();
        list = triviaQuizHelper1.getAllQuestion();
        currentQuestion = list.get(qid);
        view();
    }

    public void view() {
        tv1.setText(currentQuestion.getQuestion());
        b1.setText(" "+currentQuestion.getOpta());
        b2.setText(" "+currentQuestion.getOptb());
        b3.setText(" "+currentQuestion.getOptc());
        b4.setText(" "+currentQuestion.getOptd());
        tv3.setText("Level:"+level);
        tv4.setText("Score:"+score);
    }

    public void ButtonA(View view) {

        if (b1.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonB(View view) {
        if (b2.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonC(View view) {
        if (b3.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    public void ButtonD(View view) {
        if (b4.getText().toString().equals(" "+currentQuestion.getAnswer())){
            score+=300;
            if(qid<19){
                qid++;
                currentQuestion = list.get(qid);
                view();
            }else{
                Intent intent=new Intent(EasyAct.this,ResultWon.class);
                startActivity(intent);
                finish();
            }
        }
        else {
            Intent intent=new Intent(EasyAct.this,ResultPlayAgain.class);
            Bundle b=new Bundle();
            b.putInt("xscore",score);
            intent.putExtras(b);
            startActivity(intent);
            finish();
        }
    }
    @Override
    public void onBackPressed() {
        Intent a = new Intent(Intent.ACTION_MAIN);
        a.addCategory(Intent.CATEGORY_HOME);
        a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(a);
        finish();

    }
}

Body:
You need to stop the timer before you switch activities. If you don't, the new activity will be displayed on the screen, but the timer from the old activity can still fire. To do this explicitly, you'll need a reference to the timer that you can access outside of your onCreate() method. A simple way to do this is by declaring your CountDownTimer as a class field. Then you can access the variable anywhere inside this class.

public class EasyAct extends AppCompatActivity {
    Button b1, b2, b3, b4;
    TextView tv1, tv2, tv3, tv4;
    int score =0;
    TriviaQuizHelper1 triviaQuizHelper1;
    TriviaQuestion1 currentQuestion;
    List<TriviaQuestion1> list;
    // declaring CountDownTimer as a class field
    CountDownTimer countDownTimer;
    int qid = 0;
    int level = 1;

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

        tv1 = (TextView) findViewById(R.id.triviaQuestion);
        tv2 = (TextView) findViewById(R.id.triviTimer);
        b1 = (Button) findViewById(R.id.buttonA);
        b2 = (Button) findViewById(R.id.buttonB);
        b3 = (Button) findViewById(R.id.buttonC);
        b4 = (Button) findViewById(R.id.buttonD);
        tv3 = (TextView) findViewById(R.id.level);
        tv4 = (TextView) findViewById(R.id.score);

        // initializing the CountDownTimer instance
        countDownTimer = new CountDownTimer(300 * 1000, 1000) {
            @Override
            public void onTick(long l) {
                tv2.setText("Timer:" + l / 1000 + " " + "sec");
            }

Then you can call countDownTimer.stop() before you call startActivity().


来源: stackexchange

问:
Python Json. Getting only the last element in the json array
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

```<code>[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]
</code>```

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

```<code>rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
</code>```

when i return the value, i get

```<code>{
  "Ingreient ID": 19682
}
</code>```

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

答:
Given the number of answers I figured hey why not one more.

If you have complicated expressions, you may want to look at jmespath, which is like xslt for json, e.g.:

```<code>>>> import jmespath
>>> jmespath.search('Recipes[0].Ingredients[*].IngredientID', recipes)
[1142, 1523, 20197, 19682]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }

when i return the value, i get

{
  "Ingreient ID": 19682
}

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

Body:
Given the number of answers I figured hey why not one more.

If you have complicated expressions, you may want to look at jmespath, which is like xslt for json, e.g.:

>>> import jmespath
>>> jmespath.search('Recipes[0].Ingredients[*].IngredientID', recipes)
[1142, 1523, 20197, 19682]


问:
Populate select only if option tag doesn't exist
I want to populate the select #current_location only if it hasn't been done yet.

```<code>$(document).ready(function(){
            $('#current_location').on('change', function (){
                   /*
                    * Populate the select
                    * I want to populate the select only if it hasn't been done yet
                    */
                   $.getJSON('fetch.php', {action: 'homepage' , key: 'current_location' }, function(data){
                       var options = '';
                       for (var x = 0; x < data.length; x++) {
                           options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                       }
                       $('#current_location').html(options);
                   });

                $.getJSON('fetch.php', {action: 'homepage' , key: $('#current_location').val() }, function(data){
                    var options = '';
                    for (var x = 0; x < data.length; x++) {
                        options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                    }
                    $('#destination').html(options);
                });

            });
        });
</code>```

答:
check option length .

```<code>var length = $('#YourSelectList')
    .children('option')
    .length;
if (length > 0) {

} else {

}
</code>```

Body:
I want to populate the select #current_location only if it hasn't been done yet.

$(document).ready(function(){
            $('#current_location').on('change', function (){
                   /*
                    * Populate the select
                    * I want to populate the select only if it hasn't been done yet
                    */
                   $.getJSON('fetch.php', {action: 'homepage' , key: 'current_location' }, function(data){
                       var options = '';
                       for (var x = 0; x < data.length; x++) {
                           options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                       }
                       $('#current_location').html(options);
                   });

                $.getJSON('fetch.php', {action: 'homepage' , key: $('#current_location').val() }, function(data){
                    var options = '';
                    for (var x = 0; x < data.length; x++) {
                        options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                    }
                    $('#destination').html(options);
                });

            });
        });

Body:
check option length .

var length = $('#YourSelectList')
    .children('option')
    .length;
if (length > 0) {

} else {

}


问:
Custom drupal form with predetermined values
I need to customise my forms in drupal so that each  field has a value placed in it using a php script.

I have a php script which takes a url and gets a page title and meta description. It's easy enough to pass these values into a form by placing the required php in the input value. I can do this on a static 'test' form.

However, I'm not sure how to do this with a node form as I don't directly have access to the input value.

Any ideas or solutions would be greatly appreciated.

答: Use hook_form_alter() in order to alter some existing form entity. A basic knowledge about Form API and module development is sufficient.

ContentLicense: CC BY-SA 2.5


问:
Laravel 5.4 - Bootstrap glyphicons don't work after sass integration
Well, I just installed fresh Laravel 5.4. Then installed npm and decided first time to use webpack instead of gulp.js. As you know, Laravel default provides sass Bootstrap integration. Used this command to generate my css from sass.

npm run dev

Bootstrap, Jquery worked perfect, but Glyphicons weren't displayed. Checking my public/css/app.css I saw, that Glyphicons font-face path are not suitable.

```<code> src: url(/fonts/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1);
</code>```

If I, manually use ../fonts instead of /fonts it will work. I tried to figure out and edit the default path. In _variables.css I set:

```<code>$icon-font-path = "../fonts" - but npm gives error.
</code>```

By default it is: "~bootstrap-sass/assets/fonts/bootstrap/"

Copied fonts folder inside puclic/css folder, didn't work.

Added options to the webpack.mix.js file:

```<code>options({processCssUrls: false})
</code>```

and in _variables.css again set:

```<code>$icon-font-path = "../fonts"
</code>```

Run npm-run-dev and it worked, glyphicons were displayed. But, I don't want to set false for processCssUrls. Because, in this case I will not able to minimize css files using command: npm run production.

Also, I followed this question, but couldn't find any answer, all solutions didn't work.

glyphicons not showing with sass bootstrap integration

答:
Finally, found the solution. In webpack.config.js set:

```<code>publicPath: '../'
</code>```

instead of Mix.resourceRoot

```<code>{
    test: /\.(woff2?|ttf|eot|svg|otf)$/,
    loader: 'file-loader',
    options: {
        name: 'fonts/[name].[ext]?[hash]',
        publicPath: Mix.resourceRoot
    }
},
</code>```

Body:
Well, I just installed fresh Laravel 5.4. Then installed npm and decided first time to use webpack instead of gulp.js. As you know, Laravel default provides sass Bootstrap integration. Used this command to generate my css from sass.

npm run dev

Bootstrap, Jquery worked perfect, but Glyphicons weren't displayed. Checking my public/css/app.css I saw, that Glyphicons font-face path are not suitable.

 src: url(/fonts/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1);

If I, manually use ../fonts instead of /fonts it will work. I tried to figure out and edit the default path. In _variables.css I set:

$icon-font-path = "../fonts" - but npm gives error.

By default it is: "~bootstrap-sass/assets/fonts/bootstrap/"

Copied fonts folder inside puclic/css folder, didn't work.

Added options to the webpack.mix.js file:

options({processCssUrls: false})

and in _variables.css again set:

$icon-font-path = "../fonts"

Run npm-run-dev and it worked, glyphicons were displayed. But, I don't want to set false for processCssUrls. Because, in this case I will not able to minimize css files using command: npm run production.

Also, I followed this question, but couldn't find any answer, all solutions didn't work.

glyphicons not showing with sass bootstrap integration

Body:
Finally, found the solution. In webpack.config.js set:

publicPath: '../'

instead of Mix.resourceRoot

{
    test: /\.(woff2?|ttf|eot|svg|otf)$/,
    loader: 'file-loader',
    options: {
        name: 'fonts/[name].[ext]?[hash]',
        publicPath: Mix.resourceRoot
    }
},


问:
Showing Below Average Scores in Player Scoring Program
I'm trying to create a program in which the user can enter up to 100 player names and scores, and then have it print out all the players' names and scores, followed by an average of the scores, and finally, display players whose scores were below average. I've managed to do all of that except for the final piece, displaying below average scores. I'm kind of unsure about how to go about it. In my DesplayBelowAverage function, I've attempted to have it read the current player's score and compare it to the average to see if it should be printed out as a below average score, but it doesn't seem to recognize the averageScore value I created in the CalculateAverageScores function. Here's my code:</p>

```<code>#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
int CalculateAverageScores(int [], int);
void DisplayPlayerData(string [], int [], int);
void DisplayBelowAverage(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements << endl;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberEntered);

    CalculateAverageScores(scores, numberEntered);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames[], int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }

        cout << "Enter score for " << playerNames[index] << ": ";
        cin >> scores[index];
        cin.ignore();
    }

    return index;
}

void DisplayPlayerData(string playerNames[], int scores[], int size)
{
    int index;

    cout << "Name     Score" << endl;

    for (index = 0; index < size; index++)
    {
        cout << playerNames[index] << "     " << scores[index] << endl;
    }
}

int CalculateAverageScores(int scores[], int size)
{
    int index;
    int totalScore = 0;
    int averageScore = 0;

    for (index = 0; index < size; index++)
    {
        totalScore = (totalScore + scores[index]);
    }
    averageScore = totalScore / size;
    cout << "Average Score: " << averageScore;

    return index;
}

void DisplayBelowAverage(string playerNames[], int scores[], int size)
{
    int index;

    cout << "Players who scored below average" << endl;
    cout << "Name     Score" << endl;

    for (index = 0; index < size; index++)
    {
        if(scores[index] < averageScore)
        {
            cout << playerNames[index] << "     " << scores[index] << endl;
        }
    }
}
</code>```

答:
You are calculating the averageScore variable in the CalculateAverageScore and it is local to that function only so DisplayBelowAverage has no idea about the averageScore value. That's why your logic is not working.

In order to solve this there are two options:

Declare the averageScore as global (although it is not advisable to have global variables)

Pass the averageScore to the DisplayBelowAverage as a parameter. This is a better approach. So what you should do is return the average score that you calculate in CalculateAverageScore and store it in some variable and then pass that to DisplayBelowAverage function as a parameter.

Hope this helps

Body:
I'm trying to create a program in which the user can enter up to 100 player names and scores, and then have it print out all the players' names and scores, followed by an average of the scores, and finally, display players whose scores were below average. I've managed to do all of that except for the final piece, displaying below average scores. I'm kind of unsure about how to go about it. In my DesplayBelowAverage function, I've attempted to have it read the current player's score and compare it to the average to see if it should be printed out as a below average score, but it doesn't seem to recognize the averageScore value I created in the CalculateAverageScores function. Here's my code:

#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
int CalculateAverageScores(int [], int);
void DisplayPlayerData(string [], int [], int);
void DisplayBelowAverage(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements << endl;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberEntered);

    CalculateAverageScores(scores, numberEntered);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames[], int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }

        cout << "Enter score for " << playerNames[index] << ": ";
        cin >> scores[index];
        cin.ignore();
    }

    return index;
}

void DisplayPlayerData(string playerNames[], int scores[], int size)
{
    int index;

    cout << "Name     Score" << endl;

    for (index = 0; index < size; index++)
    {
        cout << playerNames[index] << "     " << scores[index] << endl;
    }
}

int CalculateAverageScores(int scores[], int size)
{
    int index;
    int totalScore = 0;
    int averageScore = 0;

    for (index = 0; index < size; index++)
    {
        totalScore = (totalScore + scores[index]);
    }
    averageScore = totalScore / size;
    cout << "Average Score: " << averageScore;

    return index;
}

void DisplayBelowAverage(string playerNames[], int scores[], int size)
{
    int index;

    cout << "Players who scored below average" << endl;
    cout << "Name     Score" << endl;

    for (index = 0; index < size; index++)
    {
        if(scores[index] < averageScore)
        {
            cout << playerNames[index] << "     " << scores[index] << endl;
        }
    }
}


问:
How to get json array from json file?
im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?

Code Pasted here;

```<code>var points;

        var l_nOldX;
        var l_nOldY;
        function createHotspots(){
        var points = new Array(
            /*Tamilnadu*/
        [38.7, 85.6, "0168"],
        [36.1, 85.3, "1843"],
        [38.5, 88.3, "39647"],
        [34.8, 29.2, "12320"]
    );
    var divHotspot = document.getElementById("loadImages");
    for(pi = 0; pi < points.length; pi++){
        var hs = document.createElement("div");
        hs.className = "hotspot";
        hs.style.position = "absolute";
        hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
        hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
        hs.style.width = "15px";
        hs.style.height = "15px";
        var html;
        if (points[pi][0] < 31) {
            html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
            // alert('a');
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipright").show();
            });
        }

        else {
            html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipnormal").show();
            });

        }

        $('.divclose').on('click touchstart', function () {
            //debugger;

            $('.tbltooltipnormal').hide();
            $('.tbltooltipleft').hide();
            $('.tbltooltipright').hide();
            return false;
        });

        divHotspot.appendChild(hs);
    }

}
</code>```

In above code i've  get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.

thanks in Advance.

答:
Please try this. Should solve your problem</p>

```<code>$.getJSON('<path_to_your_json_file>/file.json', function(data) {
 var points = data;
});
</code>```

Title: How to get json array from json file?

Body:
im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?

Code Pasted here;

var points;

        var l_nOldX;
        var l_nOldY;
        function createHotspots(){
        var points = new Array(
            /*Tamilnadu*/
        [38.7, 85.6, "0168"],
        [36.1, 85.3, "1843"],
        [38.5, 88.3, "39647"],
        [34.8, 29.2, "12320"]
    );
    var divHotspot = document.getElementById("loadImages");
    for(pi = 0; pi < points.length; pi++){
        var hs = document.createElement("div");
        hs.className = "hotspot";
        hs.style.position = "absolute";
        hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
        hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
        hs.style.width = "15px";
        hs.style.height = "15px";
        var html;
        if (points[pi][0] < 31) {
            html = "

" + points[pi][2] + "

";
            // alert('a');
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipright").show();
            });
        }

        else {
            html = "

" + points[pi][2] + "

";
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipnormal").show();
            });

        }

        $('.divclose').on('click touchstart', function () {
            //debugger;

            $('.tbltooltipnormal').hide();
            $('.tbltooltipleft').hide();
            $('.tbltooltipright').hide();
            return false;
        });

        divHotspot.appendChild(hs);
    }

}

In above code i've  get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.

thanks in Advance.

Body:
Please try this. Should solve your problem

$.getJSON('<path_to_your_json_file>/file.json', function(data) {
 var points = data;
});


问:
Custom status bar and navigationbar from Google sign in controller
I integrate Google sign SDK into my app. But I don't know how to change color of status bar and bar tint color of navigation bar also. I tried to change the colors with [[UITabBar appearance] setBarTintColor] and [[UIApplication sharedApplication] setStatusBarStyle] from appdelegate, but nothing happened. I really need the help from you. Thanks. </p>

答:
Custom status bar

```<code>UIView *addStatusBar = [[UIView alloc] init];
addStatusBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 20);
addStatusBar.backgroundColor = //yourColor;
[self.view addSubview:addStatusBar];
</code>```

Body:
Custom status bar

UIView *addStatusBar = [[UIView alloc] init];
addStatusBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 20);
addStatusBar.backgroundColor = //yourColor;
[self.view addSubview:addStatusBar];


问:
Cycle through a list to do Find & Replace
In my script theString is typically less than 200 words.
theFindList and replaceWithList have 78 terms in each... to find every occurrence of each term from the first list and replace it with the corresponding term in the second list.
Script runs fine, but it's slow to do the sed command in 78 different do shell script calls in a repeat loop.
It would be faster if the everything was passed to the shell for the iterations to be done there. How do I do that?
Here's the relevant repeat portion of what is now in applescript. I'll be putting the thing into Automator, so something I can do in a "run shell script" action would work. I could have the find and replace lists in a string of tab delimited data. The find and replace lists are constant, so need those baked into the shell script and only needs to receive theString from the previous action.</p>

```<code>set theString to "foo 1.0 is better than foo 2.0. The fee 5 is the best."
set toFindList to {"foo", "fee", "fo", "fum"}
set replaceWith to {"bar", "bee", "bo", "bum"}
set cf to count of toFindList
-- replace each occurrence of the word followed by a space and a digit
repeat with n from 1 to cf
    set toFindThis to item n of toFindList
    set replaceWithThis to item n of replaceWithList
    set scriptText to "echo " & quoted form of theString & " | sed -e 's/" & toFindThis & " \\([0-9]\\)/" & replaceWithThis & " \\1/'g"
    set theString to do shell script scriptText
end repeat
return theString
</code>```

答:
Ok, using the sed -f commandfile technique, I got it working. The script takes a tab delimited string or file, then builds a sed command file from that.</p>

```<code>property theString: "foo 1.0 is better than foo 2.0. The fee 5 is the best."
property substitutionList : "foo    bar
fee bee
fo  bo
bum bum" -- this tab delim list will have 78 terms

set tabReplace to "\\( [0-9]\\)/"
set paragraphReplace to "\\1/g
s/"

-- parse the replace string into lists
set commandString to ""
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab
set commandString to text items of substitutionList
set AppleScript's text item delimiters to tabReplace
set commandString to "s/" & commandString as string
set AppleScript's text item delimiters to return
set commandString to text items of commandString
set AppleScript's text item delimiters to paragraphReplace
set commandString to (commandString as string) & "\\1/g"
set AppleScript's text item delimiters to otid

set commandFilePath to ((path to temporary items from user domain) as text) & "commandFile.sed"
try
    set fileRef to open for access file commandFilePath with write permission
    set eof of fileRef to 0
    write commandString to fileRef
    close access fileRef
on error
    close access fileRef
end try
set posixPath to POSIX path of file commandFilePath

set scriptText to "echo " & quoted form of theString & " | sed -f " & quoted form of posixPath
set theString to do shell script scriptText
return theString
</code>```

Body:
In my script theString is typically less than 200 words.
theFindList and replaceWithList have 78 terms in each... to find every occurrence of each term from the first list and replace it with the corresponding term in the second list.
Script runs fine, but it's slow to do the sed command in 78 different do shell script calls in a repeat loop.
It would be faster if the everything was passed to the shell for the iterations to be done there. How do I do that?
Here's the relevant repeat portion of what is now in applescript. I'll be putting the thing into Automator, so something I can do in a "run shell script" action would work. I could have the find and replace lists in a string of tab delimited data. The find and replace lists are constant, so need those baked into the shell script and only needs to receive theString from the previous action.

set theString to "foo 1.0 is better than foo 2.0. The fee 5 is the best."
set toFindList to {"foo", "fee", "fo", "fum"}
set replaceWith to {"bar", "bee", "bo", "bum"}
set cf to count of toFindList
-- replace each occurrence of the word followed by a space and a digit
repeat with n from 1 to cf
    set toFindThis to item n of toFindList
    set replaceWithThis to item n of replaceWithList
    set scriptText to "echo " & quoted form of theString & " | sed -e 's/" & toFindThis & " \\([0-9]\\)/" & replaceWithThis & " \\1/'g"
    set theString to do shell script scriptText
end repeat
return theString

Body:
Ok, using the sed -f commandfile technique, I got it working. The script takes a tab delimited string or file, then builds a sed command file from that.

property theString: "foo 1.0 is better than foo 2.0. The fee 5 is the best."
property substitutionList : "foo    bar
fee bee
fo  bo
bum bum" -- this tab delim list will have 78 terms

set tabReplace to "\\( [0-9]\\)/"
set paragraphReplace to "\\1/g
s/"

-- parse the replace string into lists
set commandString to ""
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab
set commandString to text items of substitutionList
set AppleScript's text item delimiters to tabReplace
set commandString to "s/" & commandString as string
set AppleScript's text item delimiters to return
set commandString to text items of commandString
set AppleScript's text item delimiters to paragraphReplace
set commandString to (commandString as string) & "\\1/g"
set AppleScript's text item delimiters to otid

set commandFilePath to ((path to temporary items from user domain) as text) & "commandFile.sed"
try
    set fileRef to open for access file commandFilePath with write permission
    set eof of fileRef to 0
    write commandString to fileRef
    close access fileRef
on error
    close access fileRef
end try
set posixPath to POSIX path of file commandFilePath

set scriptText to "echo " & quoted form of theString & " | sed -f " & quoted form of posixPath
set theString to do shell script scriptText
return theString


答:
You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:  </p>

```<code>var points;
var l_nOldX;
var l_nOldY;

function createHotspots(points){ // <---pass the array
    var points = points; // assign it here
    var divHotspot = document.getElementById("loadImages");
   ...
}

$.ajax({
   url:'points.json', //<----call the json file
   type:'GET',
   dataType:'json',
   success:createHotspots // reference to the data
});
</code>```

Title: How to get json array from json file?

Body:
You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:

var points;
var l_nOldX;
var l_nOldY;

function createHotspots(points){ // <---pass the array
    var points = points; // assign it here
    var divHotspot = document.getElementById("loadImages");
   ...
}

$.ajax({
   url:'points.json', //<----call the json file
   type:'GET',
   dataType:'json',
   success:createHotspots // reference to the data
});


问:
Java Exceptions: exception myException is never thrown in body of corresponding try statement
I understand the idea of this error. But I guess I don't understand how this works down the call stack.

File Main.java:

```<code>public static void main(String[] args) {
    try {
         Function1();
      } catch (myException e) {
      System.out.println(e.getMessage());
    }
}
public static void Function1() {
    Function2();
}
</code>```

Function2 exists in another file:

File2.java

```<code>public void Function2() throws myException {
     ....
}
</code>```

So through several calls (down the call stack) I have Function2 which specifies the requirement "throws myException". How come the main function (where the error is being directed at) doesn't recognize that I throw myException down the line?

Any guidance in where the 'hole' in my "exception knowledge" lies would be greatly appreciated.

aitee,

答:
The hole is that Function2 declares that it throws the exception, but Function1 does not. Java doesn't dig its way through possible call hierarchies, but goes directly by what you declare in throws statements.

Function1 gets away with not declaring the throw probably because myException is a RuntimeException.

Body:
I understand the idea of this error. But I guess I don't understand how this works down the call stack.

File Main.java:

public static void main(String[] args) {
    try {
         Function1();
      } catch (myException e) {
      System.out.println(e.getMessage());
    }
}
public static void Function1() {
    Function2();
}

Function2 exists in another file:

File2.java

public void Function2() throws myException {
     ....
}

So through several calls (down the call stack) I have Function2 which specifies the requirement "throws myException". How come the main function (where the error is being directed at) doesn't recognize that I throw myException down the line?

Any guidance in where the 'hole' in my "exception knowledge" lies would be greatly appreciated.

aitee,


问:
Property 'files' does not exist on type 'EventTarget' error in typescript
I am trying to access the value of the input file from my ionic 2 application but still I'm facing the issue of property files does not exist on type 'EventTarget'.
As it is properly working in js but not in typescript.
The code is given below:

```<code>  document.getElementById("customimage").onchange= function(e?) {
            var files: any = e.target.files[0];
              EXIF.getData(e.target.files[0], function() {
                  alert(EXIF.getTag(this,"GPSLatitude"));
              });
          }
</code>```

Please help me solve this issue as it is not building my ionic 2 application.

答:
The e.target property type depends on the element you are returning on getElementById(...). files is a property of input element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

In this case, the TypeScript compiler doesn't know you are returning an input element and we dont have an Event class specific for this. So, you can create one like the following code:

```<code>interface HTMLInputEvent extends Event {
    target: HTMLInputElement & EventTarget;
}

document.getElementById("customimage").onchange = function(e?: HTMLInputEvent) {
    let files: any = e.target.files[0];
    //...
}
</code>```

Body:
I am trying to access the value of the input file from my ionic 2 application but still I'm facing the issue of property files does not exist on type 'EventTarget'.
As it is properly working in js but not in typescript.
The code is given below:

  document.getElementById("customimage").onchange= function(e?) {
            var files: any = e.target.files[0];
              EXIF.getData(e.target.files[0], function() {
                  alert(EXIF.getTag(this,"GPSLatitude"));
              });
          }

Please help me solve this issue as it is not building my ionic 2 application.

Body:
The e.target property type depends on the element you are returning on getElementById(...). files is a property of input element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

In this case, the TypeScript compiler doesn't know you are returning an input element and we dont have an Event class specific for this. So, you can create one like the following code:

interface HTMLInputEvent extends Event {
    target: HTMLInputElement & EventTarget;
}

document.getElementById("customimage").onchange = function(e?: HTMLInputEvent) {
    let files: any = e.target.files[0];
    //...
}


问:
'fbauth2 is missing from your Info.plist under LSApplicationQueriesSchemes and is required for iOS 9.0'
What does this error mean?

When I run my project at 'ProjectA...eter' I can share to FB.

But when I run it at 'ProjectA...Checkin' the error appeared

Anybody helps me about this error.

Thank you for supporting me

答:
You Have to register Your App on The Facebook
From There You will get a Code and you have to copy the Code and paste in info.plist File .
Register Your App  Click the Link Below.

https://developers.facebook.com/docs/marketing-api/access

Hope it Helps


问:
React-Native : how show loading screen before list view populated
Here is my code .I am using ComponentwillMount Function for API and then using isLoading variable and accordingly displaying the particular view.But its doesnt work...  its seems to be I done something wrong please took a glance and help me out I am new to react - native

```<code>const UserPage = React.createClass({

    getInitialState() {
        return {
            dataSource: dataSource.cloneWithRows(dataList),
            isLoading:true
        }
    },

    componentWillMount() {

        SharedPreferences.getItem("sender_id", (value) => {
            let user_id = value;
            let url = "BaseURL/fetchSendTokens?user_id="+user_id;
            fetch(url, {
                method: "GET",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                },
            })
                .then((response) => response.json())
                .then((responseData) => {
                    if (responseData.responsecode === 1) {
                        dataList = responseData.data;
                        this.setState = ({
                            dataSource: this.state.dataSource.cloneWithRows(dataList),
                            isLoading:false,
                        })
                    }
                    else {
                        ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                    }
                })
                .catch(e => {
                    ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                })
                .done();
        });
    },

    renderRow(rowData, sectionID,){

        let  currentView = (rowData.visitor_profileImageUrl)?
            <Image
                source={{uri:rowData.visitor_profileImageUrl}}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/> :
            <Image
                source={userprofilepic}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/>;

        return <View key={ sectionID }>
            <View style={{ flex: 1,height:70,flexDirection: 'row'}}>
                <View>
                    {currentView}
                </View>
                <Text style={{fontSize : 18,marginTop:15,marginLeft:20,color:"black"}} >{ rowData.visitor_name }</Text>
            </View>
        </View>
    },

    render() {
        let loadingGif = "URL-loading.gif";
        let currentView = (this.state.isLoading)?<View style={styles.background}>
                <View style={styles.markWrap}>
                    <Image source={{uri:loadingGif}} style={styles.verifyLogo} resizeMode="contain"/>
                </View>
            </View>:
            <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} enableEmptySections={true}/>;

        return(
            <View>
                {currentView}
            </View>
        );

    },
});
</code>```

答:
Your problem is a typo:

```<code>                    this.setState = ({
                        datasource: this.state.dataSource.cloneWithRows(dataList),
                        isLoading:false,
                    })
</code>```

Should be:

```<code>                    this.setState = ({
                        dataSource: this.state.dataSource.cloneWithRows(dataList),
                        isLoading:false,
                    })
</code>```

Note that you seem to keep around a global dataSource and dataList - that's usually not a good practice. If you need to keep data, use props and callbacks to pass it around, not globals.

Body:
Here is my code .I am using ComponentwillMount Function for API and then using isLoading variable and accordingly displaying the particular view.But its doesnt work...  its seems to be I done something wrong please took a glance and help me out I am new to react - native

const UserPage = React.createClass({

    getInitialState() {
        return {
            dataSource: dataSource.cloneWithRows(dataList),
            isLoading:true
        }
    },

    componentWillMount() {

        SharedPreferences.getItem("sender_id", (value) => {
            let user_id = value;
            let url = "BaseURL/fetchSendTokens?user_id="+user_id;
            fetch(url, {
                method: "GET",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                },
            })
                .then((response) => response.json())
                .then((responseData) => {
                    if (responseData.responsecode === 1) {
                        dataList = responseData.data;
                        this.setState = ({
                            dataSource: this.state.dataSource.cloneWithRows(dataList),
                            isLoading:false,
                        })
                    }
                    else {
                        ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                    }
                })
                .catch(e => {
                    ToastAndroid.show('Please try again...', ToastAndroid.SHORT);
                })
                .done();
        });
    },

    renderRow(rowData, sectionID,){

        let  currentView = (rowData.visitor_profileImageUrl)?
            <Image
                source={{uri:rowData.visitor_profileImageUrl}}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/> :
            <Image
                source={userprofilepic}
                style={{height:40,width:40,margin:15,borderRadius:100}}
                resizeMode="contain"/>;

        return <View key={ sectionID }>
            <View style={{ flex: 1,height:70,flexDirection: 'row'}}>
                <View>
                    {currentView}
                </View>
                <Text style={{fontSize : 18,marginTop:15,marginLeft:20,color:"black"}} >{ rowData.visitor_name }</Text>
            </View>
        </View>
    },

    render() {
        let loadingGif = "URL-loading.gif";
        let currentView = (this.state.isLoading)?<View style={styles.background}>
                <View style={styles.markWrap}>
                    <Image source={{uri:loadingGif}} style={styles.verifyLogo} resizeMode="contain"/>
                </View>
            </View>:
            <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} enableEmptySections={true}/>;

        return(
            <View>
                {currentView}
            </View>
        );

    },
});

Body:
Your problem is a typo:

                    this.setState = ({
                        datasource: this.state.dataSource.cloneWithRows(dataList),
                        isLoading:false,
                    })

Should be:

                    this.setState = ({
                        dataSource: this.state.dataSource.cloneWithRows(dataList),
                        isLoading:false,
                    })

Note that you seem to keep around a global dataSource and dataList - that's usually not a good practice. If you need to keep data, use props and callbacks to pass it around, not globals.


问:
How to make function work once per image
I have 5 images with the same function in a javascript field and I want to know how to be able to use the function once per image </p>

<p>my current code </p>

```<code>function move()
{
    // move to the first now
    document.getElementsByTagName('div')[0].insertBefore
    (this, document.getElementsByTagName('div')[0].firstChild)
}

img1.onclick=move
img2.onclick=move
img3.onclick=move
img4.onclick=move
img5.onclick=move
</code>```

答:
Set once to true at .addEventListener() third parameter

```<code>[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});
</code>```

var [img1, img2, img3, img4, img5] = document.images;

function move() {
  alert(this.alt)
}

[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img alt="1"><img alt="2"><img alt="3"><img alt="4"><img alt="5"></code>```

Body:
I have 5 images with the same function in a javascript field and I want to know how to be able to use the function once per image

my current code

function move()
{
    // move to the first now
    document.getElementsByTagName('div')[0].insertBefore
    (this, document.getElementsByTagName('div')[0].firstChild)
}

img1.onclick=move
img2.onclick=move
img3.onclick=move
img4.onclick=move
img5.onclick=move

Body:
Set once to true at .addEventListener() third parameter

[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});

var [img1, img2, img3, img4, img5] = document.images;

function move() {
  alert(this.alt)
}

[img1, img2, img3, img4, img5]
.forEach(function(img) {
  img.addEventListener("click", move, {once:true})
});

<img alt="1"><img alt="2"><img alt="3"><img alt="4"><img alt="5">


问:
Can a two column layout shrink to 1 column if no content present in first column?
I have posted my workaround to illustrate my problem at the end of this post.

I have two columns, the left one may or may not contain an image thumbnail and the right one that always contains text.

The image containers width is set at a % and the image itself fills 100% of its parents width with an proportional height.

The img then has the equivalant of background-size:cover applied to center, crop and fill its parent container.

Is there any way with css to have the text column fill 100% of the width of the blog-container if there is no thumbnail image added?

My current solution which involves using :empty to display:none the img tags parent container if there is no content in it but I need a solution where I can specify a width of image-container instead, and have it shrink to 0 if no image present.

Hopefully this isnt too convoluted, any clarification please ask. Support back to IE10 required. I was hoping flexbox could help?

```<code><div class="blog-container">

     <div class="featured-image-container">
          <div class="featured-image-blog"><?php the_post_thumbnail('this is the img'); ?</div>
     </div>

      <div class="blog-entry-content-container">
          <div class="blog-excerpt-container">
              <?php the_excerpt;?>
          </div>
      </div>

 </div>

//SCSS
@mixin maintain-ratio($ratio: 1 1) {
@if length($ratio) < 2 or length($ratio)>2 {
    @warn "$ratio must be a list with two values.";
}
$width: 100%;
$height: percentage(nth($ratio, 2) / nth($ratio, 1));
width: $width;
height: 0;
padding-bottom: $height;
}

//CSS

.blog-container {
width: 100%;
display: flex;
display: -webkit-flex;
-webkit-flex-direction: column;
flex-direction: column;
}

.ourblog .featured-image-blog {
width:32%!important;/*I WANT TO MOVE THIS TO A PARENT CONTAINER (.image-container)*/
@include maintain-ratio(3 1);
margin: 10px 25px 20px 0!important;
font-size: 0!important;
position:relative!important;
overflow:hidden;   }

.ourblog .featured-image-blog img {
position: absolute;
/* Position the image in the middle of its container. */
top: -9999px;
right: -9999px;
bottom: -9999px;
left: -9999px;
margin: auto;
/* The following values determine the exact image behaviour. */
/* You can simulate background-size: cover/contain/etc.
 by changing between min/max/standard width/height values.
 These values simulate background-size: cover
 */
min-width: 100%;
min-height: 100%;
}

/*hide empty featured image container. !!!ensure no whitespace between tags in html!!! */
.ourblog .featured-image-blog:empty {
display: none!important;
}
</code>```

答:
Use flex row then set then use the flex shorthand on the columns to make them flex to the available space. Basic example http://codepen.io/anon/pen/QpYzaV

```<code>.blog-container {
width: 100%;
display: flex; // is flex row by default
margin-bottom: 20px;
}

.featured-image-container {
  flex: 1 0 30%;
  img {
    width: 100%;
  }
}

.blog-entry-content-container {
  padding: 20px;
  background: grey;
  flex: 1 0 100%;
}
</code>```

Use has post thumbnail to render the container if it has an image set.

```<code><?php if ( has_post_thumbnail() ) : ?>
    <!-- show the image container -->
    <div class="featured-image-container">
        <?php the_post_thumbnail(); ?>
    </div>
    <?php else : ?>
    <!-- show nothing -->
<?php endif; ?>
</code>```

Body:
I have posted my workaround to illustrate my problem at the end of this post.

I have two columns, the left one may or may not contain an image thumbnail and the right one that always contains text.

The image containers width is set at a % and the image itself fills 100% of its parents width with an proportional height.

The img then has the equivalant of background-size:cover applied to center, crop and fill its parent container.

Is there any way with css to have the text column fill 100% of the width of the blog-container if there is no thumbnail image added?

My current solution which involves using :empty to display:none the img tags parent container if there is no content in it but I need a solution where I can specify a width of image-container instead, and have it shrink to 0 if no image present.

Hopefully this isnt too convoluted, any clarification please ask. Support back to IE10 required. I was hoping flexbox could help?

<?php the_post_thumbnail('this is the img'); ?

              <?php the_excerpt;?>

//SCSS
@mixin maintain-ratio($ratio: 1 1) {
@if length($ratio) < 2 or length($ratio)>2 {
    @warn "$ratio must be a list with two values.";
}
$width: 100%;
$height: percentage(nth($ratio, 2) / nth($ratio, 1));
width: $width;
height: 0;
padding-bottom: $height;
}

//CSS

.blog-container {
width: 100%;
display: flex;
display: -webkit-flex;
-webkit-flex-direction: column;
flex-direction: column;
}

.ourblog .featured-image-blog {
width:32%!important;/*I WANT TO MOVE THIS TO A PARENT CONTAINER (.image-container)*/
@include maintain-ratio(3 1);
margin: 10px 25px 20px 0!important;
font-size: 0!important;
position:relative!important;
overflow:hidden;   }

.ourblog .featured-image-blog img {
position: absolute;
/* Position the image in the middle of its container. */
top: -9999px;
right: -9999px;
bottom: -9999px;
left: -9999px;
margin: auto;
/* The following values determine the exact image behaviour. */
/* You can simulate background-size: cover/contain/etc.
 by changing between min/max/standard width/height values.
 These values simulate background-size: cover
 */
min-width: 100%;
min-height: 100%;
}

/*hide empty featured image container. !!!ensure no whitespace between tags in html!!! */
.ourblog .featured-image-blog:empty {
display: none!important;
}

Body:
Use flex row then set then use the flex shorthand on the columns to make them flex to the available space. Basic example http://codepen.io/anon/pen/QpYzaV

.blog-container {
width: 100%;
display: flex; // is flex row by default
margin-bottom: 20px;
}

.featured-image-container {
  flex: 1 0 30%;
  img {
    width: 100%;
  }
}

.blog-entry-content-container {
  padding: 20px;
  background: grey;
  flex: 1 0 100%;
}

Use has post thumbnail to render the container if it has an image set.

<?php if ( has_post_thumbnail() ) : ?>
    <!-- show the image container -->
    <div class="featured-image-container">
        <?php the_post_thumbnail(); ?>
    </div>
    <?php else : ?>
    <!-- show nothing -->
<?php endif; ?>


问:
Transferring Value through session in JSP
I have 4 jsp forms name Sample1.jsp,Sample2.jsp,Sample3.jsp,Sample4.jsp
I want to transfer value from one page to another through Session
and I used this method

Sample1.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="sample2.jsp" method="post">
            <h1>Page1</h1>
            <input type="text" name="name">
            <input type="submit" value="Go">
        </form>
    </body>
</html>
</code>```

Sample2.jsp
Got the value name from Sample1.jsp and redirected to sample3.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>page2</h1>
        <%
            String name = request.getParameter("name");
            session.setAttribute("name",name);
            out.println(name);
            //response.sendRedirect("sample3.jsp");
            request.getRequestDispatcher("sample3.jsp").forward(request, response);
        %>
    </body>
</html>
</code>```

Sample3.jsp
Got the value name from Sample2.jsp and not displaying the anchor tag hyperlink in Sample3.jsp and directly jump to Sample4.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Page 3</h1>
        <%
            String lname = (String)session.getAttribute("name");
            out.println(lname);
            //session.setAttribute("lname",lname);
        %>

        <a href="<%request.getRequestDispatcher("sample4.jsp").forward(request, response);%>" value=""><%out.println(lname);%> </a>
    </body>
</html>
</code>```

The Code directly jump to Sample4.jsp without allowing the user to click the hyperlink in anchor tags in Form Sample3.jsp. Wanted to stop the page and allow the user to Click and move forward.

Sample4.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>page 4</h1>
        <%String name =(String)session.getAttribute("name");
        out.println(name);%>

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

答:
Don't use a RequestDispatcher in your  tags. The session values will remain persistent even in the Sample4.jsp, so even a basic hyperlink to it will be fine to use the values present in the Session.

Also if you wish to check out when to use forward() and when to use sendRedirect() method check out this link: http://javarevisited.blogspot.in/2011/09/sendredirect-forward-jsp-servlet.html

ContentLicense: CC BY-SA 4.0

Body:
I have 4 jsp forms name Sample1.jsp,Sample2.jsp,Sample3.jsp,Sample4.jsp
I want to transfer value from one page to another through Session
and I used this method

Sample1.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form action="sample2.jsp" method="post">

Page1

            <input type="text" name="name">
            <input type="submit" value="Go">
        </form>

Sample2.jsp
Got the value name from Sample1.jsp and redirected to sample3.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

page2

        <%
            String name = request.getParameter("name");
            session.setAttribute("name",name);
            out.println(name);
            //response.sendRedirect("sample3.jsp");
            request.getRequestDispatcher("sample3.jsp").forward(request, response);
        %>

Sample3.jsp
Got the value name from Sample2.jsp and not displaying the anchor tag hyperlink in Sample3.jsp and directly jump to Sample4.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Page 3

        <%
            String lname = (String)session.getAttribute("name");
            out.println(lname);
            //session.setAttribute("lname",lname);
        %>

        <a href="<%request.getRequestDispatcher("sample4.jsp").forward(request, response);%>" value=""><%out.println(lname);%>

The Code directly jump to Sample4.jsp without allowing the user to click the hyperlink in anchor tags in Form Sample3.jsp. Wanted to stop the page and allow the user to Click and move forward.

Sample4.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

page 4

        <%String name =(String)session.getAttribute("name");
        out.println(name);%>

Body:
Don't use a RequestDispatcher in your <a> tags. The session values will remain persistent even in the Sample4.jsp, so even a basic hyperlink to it will be fine to use the values present in the Session.

Also if you wish to check out when to use forward() and when to use sendRedirect() method check out this link: http://javarevisited.blogspot.in/2011/09/sendredirect-forward-jsp-servlet.html


问:
Arduino Replace : with _
I am messing around with replacing all :with _ in my ESP8266 Mac Address. I tried the replace() Method like this:

```<code>WiFi.macAddress().replace(WiFi.macAddress().begin(),
WiFi.macAddress().end(), ':', '_');
</code>```

But it does not work and throws 'class String' has no member begin.

I am no C++ pro so maybe you can help me replacing all : in the Mac Address with _!

答:
As long as replace method is void and replaces the characters on fly, you need to get MAC into a variable before manipulating it.</p>

```<code>String MAC = WiFi.macAddress();
MAC.replace(':', '_');
Serial.println(MAC);
</code>```

Title: Arduino Replace : with _

Body:
I am messing around with replacing all :with _ in my ESP8266 Mac Address. I tried the replace() Method like this:

WiFi.macAddress().replace(WiFi.macAddress().begin(),
WiFi.macAddress().end(), ':', '_');

But it does not work and throws 'class String' has no member begin.

I am no C++ pro so maybe you can help me replacing all : in the Mac Address with _!

Body:
As long as replace method is void and replaces the characters on fly, you need to get MAC into a variable before manipulating it.

String MAC = WiFi.macAddress();
MAC.replace(':', '_');
Serial.println(MAC);