问:
javascript - functions and equations confusion
```<code> var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2
</code>```

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

Body:
 var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

Body:
var sum = 0;
for (var n = 1; n <= 17; n++) {
   if (n % 3 === 0 || n % 5 === 0)
     sum += n;
}

console.log(sum);


来源: stackexchange

问:
rxJs & angular 4 & restangular: stack errorInterceptors
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

```<code>  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });
</code>```

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

```<code>Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

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

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

```<code>const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};
</code>```

答:
My solution involves extending the HTTP service offered by angular and overriding the methods to add the following behaviour:

Add retry logic for all of your HTTP calls like so:

post<T>(serviceUrl: string, data: any): Observable<T> {
    return Observable.defer(() => {
        return super.post<T>(serviceUrl, data);
    }).retryWhen((error) => {
        return this.refresh(error);
    });
}```
</div>
</div>
</p>

<ol start="2">
<li>Throw if the status code is different from 403.Else refresh the token and try again. You will try to do this, let's say 3 times. After that you can just give up :)</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>refresh(obs: Observable<any>): Observable<any> {
    return obs
        .switchMap((x: any) => {
            if (x.status === 403) {
                return Observable.of(x);
            }
            return Observable.throw(x);
        })
        .scan((acc, value) => {
            return acc + 1;
        }, 0)
        .takeWhile(acc => acc < 3)
        .flatMap(() => {
            console.log('Token refresh retry');
            return this.tokenRefreshService.refreshToken();
        });
}</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

  return true;
});

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};

Body:
My solution involves extending the HTTP service offered by angular and overriding the methods to add the following behaviour:

Add retry logic for all of your HTTP calls like so:

post<T>(serviceUrl: string, data: any): Observable<T> {
    return Observable.defer(() => {
        return super.post<T>(serviceUrl, data);
    }).retryWhen((error) => {
        return this.refresh(error);
    });
}

Throw if the status code is different from 403.Else refresh the token and try again. You will try to do this, let's say 3 times. After that you can just give up :)

refresh(obs: Observable<any>): Observable<any> {
    return obs
        .switchMap((x: any) => {
            if (x.status === 403) {
                return Observable.of(x);
            }
            return Observable.throw(x);
        })
        .scan((acc, value) => {
            return acc + 1;
        }, 0)
        .takeWhile(acc => acc < 3)
        .flatMap(() => {
            console.log('Token refresh retry');
            return this.tokenRefreshService.refreshToken();
        });
}


问:
fill color inside  and export diagram to excel
I wanna fill in color in  like what present in the picture,which is part of table.The width and position of black square can be calculated according to the data in the other part of table I do not attach below.

I wanna put a  inside the  to generate the black square.

The code is:

```<code><table class="table table-bordered" align="center">
  <thead>
    <tr>
      <th colspan="8" style="display:table-cell; vertical-align:middle">...</th>
      <th colspan="16" style="display:table-cell; vertical-align:middle">...</th>
    </tr>
    <tr>
      <th>...</th>
      <th></th>
      .......
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td><span> </span></td>
    </tr>
    .......
  </tbody>
</table>
<script>
  $("table tr:eq(2) td:eq(6) span").css({
    "display": "block",
    "background-color": "black",
    "height": "$(this).parent().css('height')",
    "width": "50%",
    "left": "0",
    "right": "50%",
  });
</script>
</code>```

But it does not work, black square do not been presented.How to solve this problem? And Besides, the table must be exported to excel including the black square,I know how to deal with text, but diagram to excel...I have no idea

This function can be realised by narrowing the width of every column in Excel,but i do not how to realise with code

答:
Adding content to your span in terms of a   fixes your immediate problem.

$("table tr:eq(2) td:eq(6) span").css({
    "display": "block",
    "background-color": "black",
    "height": "$(this).parent().css('height')",
    "width": "50%",
    "left": "0",
    "right": "50%",
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {border: black 1px solid;padding:0;}</code>```

      ...
      ...

      ...

      .......

      1
      2
      3
      4
      5
      6

```

As I mentioned in the comment, I don't see this working with excel exporting.

Title: fill color inside <td> and export diagram to excel

Body:
I wanna fill in color in  like what present in the picture,which is part of table.The width and position of black square can be calculated according to the data in the other part of table I do not attach below.

I wanna put a  inside the  to generate the black square.

The code is:

      ...
      ...

      ...

      .......

      1
      2
      3
      4
      5
      6

    .......

But it does not work, black square do not been presented.How to solve this problem? And Besides, the table must be exported to excel including the black square,I know how to deal with text, but diagram to excel...I have no idea

This function can be realised by narrowing the width of every column in Excel,but i do not how to realise with code

Body:
Adding content to your span in terms of a &nbsp; fixes your immediate problem.

$("table tr:eq(2) td:eq(6) span").css({
    "display": "block",
    "background-color": "black",
    "height": "$(this).parent().css('height')",
    "width": "50%",
    "left": "0",
    "right": "50%",
  });

td {border: black 1px solid;padding:0;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table table-bordered" align="center">
  <thead>
    <tr>
      <th colspan="8" style="display:table-cell; vertical-align:middle">...</th>
      <th colspan="16" style="display:table-cell; vertical-align:middle">...</th>
    </tr>
    <tr>
      <th>...</th>
      <th></th>
      .......
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td><span>&nbsp;</span></td>
    </tr>

  </tbody>
</table>

As I mentioned in the comment, I don't see this working with excel exporting.


问:
Amcharts - displaying legend entry for each column?
Consider this snippet: http://jsfiddle.net/ouLed1fp/

How to get a legend entry for each column? also, how to get the column name next to it? basically, I want a proper legend.

```<code><div id="chartdiv" style="width: 100%; height: 355px;"></div>
<script>

var chart;

var chartData = [{
    country: "USA",
    visits: 4025,
    subdata: [
        { country: "New York", visits: 1000 },
        { country: "California", visits: 785 },
        { country: "Florida", visits: 501 },
        { country: "Illinois", visits: 321 },
        { country: "Washington", visits: 101 }
    ]},
{
    country: "China",
    visits: 1882},
{
    country: "Japan",
    visits: 1809},
{
    country: "Germany",
    visits: 1322}];

AmCharts.ready(function() {
    // SERIAL CHART
    chart = new AmCharts.AmSerialChart();
    chart.dataProvider = chartData;
    chart.categoryField = "country";
    chart.startDuration = 1;

    // AXES
    // category
    var categoryAxis = chart.categoryAxis;
    categoryAxis.labelRotation = 90;
    categoryAxis.gridPosition = "start";

    // value
    // in case you don't want to change default settings of value axis,
    // you don't need to create it, as one value axis is created automatically.
    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.valueField = "visits";
    graph.balloonText = "[[category]]: [[value]]";
    graph.type = "column";
    graph.lineAlpha = 0;
    graph.fillAlphas = 0.8;
    chart.addGraph(graph);

    chart.addListener("clickGraphItem", function (event) {
        // let's look if the clicked graph item had any subdata to drill-down into
        if (event.item.dataContext.subdata != undefined) {
            // wow it has!
            // let's set that as chart's dataProvider
            event.chart.dataProvider = event.item.dataContext.subdata;
            event.chart.validateData();
        }
    });

    var legend = new AmCharts.AmLegend();
    chart.addLegend(legend, "legenddiv");

    chart.write("chartdiv");

});

</script>
</code>```

答:
Got it working using this: https://www.amcharts.com/kbase/generate-legend-markers-column/</p>

```<code>/*
  Plugin to generate legend markers based on category
  and fillColor/lineColor field from the chart data by using
  the legend's custom data array.

  The plugin assumes there is  only one graph object.
*/
AmCharts.addInitHandler(function(chart) {
  //check if legend is enabled and custom generateFromData property
  //is set before running
  if (!chart.legend || !chart.legend.enabled || !chart.legend.generateFromData) {
    return;
  }

  var categoryField = chart.categoryField;
  var colorField = chart.graphs[0].lineColorField || chart.graphs[0].fillColorsField;
  var legendData =  chart.dataProvider.map(function(data) {
    var markerData = {
      "title": data[categoryField] + ": " + data[chart.graphs[0].valueField],
      "color": data[colorField]
    };
    if (!markerData.color) {
      markerData.color = chart.graphs[0].lineColor;
    }
    return markerData;
  });

  chart.legend.data = legendData;

}, ["serial"]);

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "marginRight": 70,
  "legend": {
    "generateFromData": true //custom property for the plugin
  },
  "dataProvider": [{
    "country": "USA",
    "visits": 3025,
    "color": "#FF0F00"
  }, {
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
  }, {
    "country": "Japan",
    "visits": 1809,
    "color": "#FF9E01"
  }, {
    "country": "Germany",
    "visits": 1322,
    "color": "#FCD202"
  }, {
    "country": "UK",
    "visits": 1122,
    "color": "#F8FF01"
  }, {
    "country": "France",
    "visits": 1114,
    "color": "#B0DE09"
  }, {
    "country": "India",
    "visits": 984,
    "color": "#04D215"
  }, {
    "country": "Spain",
    "visits": 711,
    "color": "#0D8ECF"
  }, {
    "country": "Netherlands",
    "visits": 665,
    "color": "#0D52D1"
  }, {
    "country": "Russia",
    "visits": 580,
    "color": "#2A0CD0"
  }, {
    "country": "South Korea",
    "visits": 443,
    "color": "#8A0CCF"
  }, {
    "country": "Canada",
    "visits": 441,
    "color": "#CD0D74"
  }],
  "valueAxes": [{
    "axisAlpha": 0,
    "position": "left",
    "title": "Visitors from country"
  }],
  "startDuration": 1,
  "graphs": [{
    "balloonText": "<b>[[category]]: [[value]]</b>",
    "fillColorsField": "color",
    "fillAlphas": 0.9,
    "lineAlpha": 0.2,
    "type": "column",
    "valueField": "visits"
  }],
  "chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
  },
  "categoryField": "country",
  "categoryAxis": {
    "gridPosition": "start",
    "labelRotation": 45
  },
  "export": {
    "enabled": true
  }

});
</code>```

Body:
Got it working using this: https://www.amcharts.com/kbase/generate-legend-markers-column/

/*
  Plugin to generate legend markers based on category
  and fillColor/lineColor field from the chart data by using
  the legend's custom data array.

  The plugin assumes there is  only one graph object.
*/
AmCharts.addInitHandler(function(chart) {
  //check if legend is enabled and custom generateFromData property
  //is set before running
  if (!chart.legend || !chart.legend.enabled || !chart.legend.generateFromData) {
    return;
  }

  var categoryField = chart.categoryField;
  var colorField = chart.graphs[0].lineColorField || chart.graphs[0].fillColorsField;
  var legendData =  chart.dataProvider.map(function(data) {
    var markerData = {
      "title": data[categoryField] + ": " + data[chart.graphs[0].valueField],
      "color": data[colorField]
    };
    if (!markerData.color) {
      markerData.color = chart.graphs[0].lineColor;
    }
    return markerData;
  });

  chart.legend.data = legendData;

}, ["serial"]);

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "marginRight": 70,
  "legend": {
    "generateFromData": true //custom property for the plugin
  },
  "dataProvider": [{
    "country": "USA",
    "visits": 3025,
    "color": "#FF0F00"
  }, {
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
  }, {
    "country": "Japan",
    "visits": 1809,
    "color": "#FF9E01"
  }, {
    "country": "Germany",
    "visits": 1322,
    "color": "#FCD202"
  }, {
    "country": "UK",
    "visits": 1122,
    "color": "#F8FF01"
  }, {
    "country": "France",
    "visits": 1114,
    "color": "#B0DE09"
  }, {
    "country": "India",
    "visits": 984,
    "color": "#04D215"
  }, {
    "country": "Spain",
    "visits": 711,
    "color": "#0D8ECF"
  }, {
    "country": "Netherlands",
    "visits": 665,
    "color": "#0D52D1"
  }, {
    "country": "Russia",
    "visits": 580,
    "color": "#2A0CD0"
  }, {
    "country": "South Korea",
    "visits": 443,
    "color": "#8A0CCF"
  }, {
    "country": "Canada",
    "visits": 441,
    "color": "#CD0D74"
  }],
  "valueAxes": [{
    "axisAlpha": 0,
    "position": "left",
    "title": "Visitors from country"
  }],
  "startDuration": 1,
  "graphs": [{
    "balloonText": "<b>[[category]]: [[value]]</b>",
    "fillColorsField": "color",
    "fillAlphas": 0.9,
    "lineAlpha": 0.2,
    "type": "column",
    "valueField": "visits"
  }],
  "chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
  },
  "categoryField": "country",
  "categoryAxis": {
    "gridPosition": "start",
    "labelRotation": 45
  },
  "export": {
    "enabled": true
  }

});


问:
Javascript - unable to understand function parentheses
I am confused how the way functions are called. Sometimes they are given in functionName() format and sometimes just the name, functionName.

For example in HTML, when we call onclick="functionName()" but in Javascript we just pass function functionName as argument to another function.
setTimeout(functionName, 1000);

Here's an example from a book, suppose we have to pass a callback function with arguments.

```<code>var mySetTimeout = function(callback, delay){
  var dollars = 100;
  callback(dollars);
};
var onCompletion = function(dollars,name){
  console.log(name + ": Here's your $" + dollars);
};
var getMoney = function (name) {
  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);
};
getMoney('Simon');
</code>```

Here in mySetTimeout function we are passing callback as an argument but with nothing in it. But later on in mySetTimeout function we are passing callback function with argument.

Can anyone explain me the all the cases? Thanks!

答:
You need to understand a few things about callback functions, anonymous functions etc to get this idea. It's very common to use anonymous functions in JS.

I will try to explain you in the simplest possible way. In your code, in the first line: refer my comment.

```<code>var mySetTimeout = function(callback, delay){ // Note 01
  var dollars = 100;
  callback(dollars); // Note 02
};
</code>```

Note 01: Here, callback is nothing more than a string parameter. It's not a function, but a function name. You tell that you want to run a function called "callback" and you pass that name. Then you run that function by simply calling, callback(), where "callback" is the parameter you passed above to this function.

Note 02: Here, you actually run a function with that name you defined above.

In this line of code,

```<code>  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);
</code>```

You can see that instead of "callback" string parameter, you have defined the function itself because inside the "mySetTimeout" function, it runs that first parameter as a function.

So basically, you could have done the same as below:

```<code>var myCallbackFunction = function(dollars){
    onCompletion(dollars,name);
  };

var requestB = mySetTimeout(myCallbackFunction, 1000);
</code>```

Now you see that first parameter holds a function and when that is invoked inside the "mySetTimeout" function, the function you defined above will be actually run. Basically, I tried to explain that you can hold a function within a variable. That's the purpose of anonymous functions / lambda functions.

I tried to explain you this in the simplest way. Hope this helps. Google "JavaScript anonymous functions" and you will have enough things to learn.

Body:
I am confused how the way functions are called. Sometimes they are given in functionName() format and sometimes just the name, functionName.

For example in HTML, when we call onclick="functionName()" but in Javascript we just pass function functionName as argument to another function.
setTimeout(functionName, 1000);

Here's an example from a book, suppose we have to pass a callback function with arguments.

var mySetTimeout = function(callback, delay){
  var dollars = 100;
  callback(dollars);
};
var onCompletion = function(dollars,name){
  console.log(name + ": Here's your $" + dollars);
};
var getMoney = function (name) {
  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);
};
getMoney('Simon');

Here in mySetTimeout function we are passing callback as an argument but with nothing in it. But later on in mySetTimeout function we are passing callback function with argument.

Can anyone explain me the all the cases? Thanks!

Body:
You need to understand a few things about callback functions, anonymous functions etc to get this idea. It's very common to use anonymous functions in JS.

I will try to explain you in the simplest possible way. In your code, in the first line: refer my comment.

var mySetTimeout = function(callback, delay){ // Note 01
  var dollars = 100;
  callback(dollars); // Note 02
};

Note 01: Here, callback is nothing more than a string parameter. It's not a function, but a function name. You tell that you want to run a function called "callback" and you pass that name. Then you run that function by simply calling, callback(), where "callback" is the parameter you passed above to this function.

Note 02: Here, you actually run a function with that name you defined above.

In this line of code,

  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);

You can see that instead of "callback" string parameter, you have defined the function itself because inside the "mySetTimeout" function, it runs that first parameter as a function.

So basically, you could have done the same as below:

var myCallbackFunction = function(dollars){
    onCompletion(dollars,name);
  };

var requestB = mySetTimeout(myCallbackFunction, 1000);

Now you see that first parameter holds a function and when that is invoked inside the "mySetTimeout" function, the function you defined above will be actually run. Basically, I tried to explain that you can hold a function within a variable. That's the purpose of anonymous functions / lambda functions.

I tried to explain you this in the simplest way. Hope this helps. Google "JavaScript anonymous functions" and you will have enough things to learn.


问:
how to load nsnotification text from an array
I am wondering how its possible to load the text displayed in an nsnotifcation using an array?
I want the message shown in this notification to be loaded from an array and not for it to be a fixed text value.</p>

答:
Not sure what your question is asking, but if you have a NSString as an object in an array, you can access it by using:

```<code>NSString *yourMessageString = [yourArray objectAtIndex:0];
</code>```

for example.

EDIT:
To set the alert message to the message in the array, simply do this:

```<code>UIAlertView *alert = [[UIAlertView alloc]
                     initWithTitle:@"Your Title"
                     message:[yourArray objectAtIndex:0]
                     delegate:self
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
[alert show];
[alert release];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Not sure what your question is asking, but if you have a NSString as an object in an array, you can access it by using:

NSString *yourMessageString = [yourArray objectAtIndex:0];

for example.

EDIT:
To set the alert message to the message in the array, simply do this:

UIAlertView *alert = [[UIAlertView alloc]
                     initWithTitle:@"Your Title"
                     message:[yourArray objectAtIndex:0]
                     delegate:self
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
[alert show];
[alert release];


答:
Use a variable to add the numbers and return it after for loop.

Below it the exapmle.

function getList() {
  var sum = 0;

  for (var n = 1; n <= 17; n++) {
    if (n % 3 == 0 || n % 5 == 0) {
      sum += n;
    }
  }

  return sum;
}

console.log(getList());```

Title: javascript - functions and equations confusion


问:
How to use explode function for finding the result like this? and please explain the meaning of each $delimiter used inside the explode function
My input is $text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) '

I am applying explode function on this input

```<code>function multiexplode ($delimiters,$string)
{
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}
$exploded = multiexplode(array(' ',":" ), $text);
for($i=0;$i<(count($exploded));$i++)
    echo "<br> $exploded[$i]";
</code>```

My output is coming like this

```<code>0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - "LEE
9 - power"
10 - and
11 - system
12 - )
13 - )
</code>```

But I want to output like the following

```<code>0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - LEE power
9 - and
10 - system
11 - )
12 - )
</code>```

I want to store all words inside " " in one element of array.

答:
Check the following code:

```<code>$text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) ';

preg_match_all('/"(?:\.|[^"])*"|\S+/', $text, $exploded);
for($i=0;$i<(count($exploded[0]));$i++)
    echo "<br>". $exploded[0][$i];
</code>```

UPDATE based on comment

For input of $text = '((LED AND DIODE) OR ("LEE power" and system)) ';

```<code>$text = '((LED AND DIODE) OR ("LEE power" and system)) ';
$re = '/"(?:\.|[^"])*"|\(?|\)|(\'(.*?)\'|(\w+))/';
preg_match_all($re, $text, $exploded);

for($i=0;$i<(count($exploded[0]));$i++)
    if($exploded[0][$i]!='')
        echo "<br>". $exploded[0][$i];
</code>```

Body:
My input is $text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) '

I am applying explode function on this input

function multiexplode ($delimiters,$string)
{
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}
$exploded = multiexplode(array(' ',":" ), $text);
for($i=0;$i<(count($exploded));$i++)
    echo "
 $exploded[$i]";

My output is coming like this

0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - "LEE
9 - power"
10 - and
11 - system
12 - )
13 - )

But I want to output like the following

0 - (
1 - (
2 - LED
3 - AND
4 - DIODE
5 - )
6 - OR
7 - (
8 - LEE power
9 - and
10 - system
11 - )
12 - )

I want to store all words inside " " in one element of array.

Body:
Check the following code:

$text = '( ( LED AND DIODE ) OR ( "LEE power" and system ) ) ';

preg_match_all('/"(?:\.|[^"])*"|\S+/', $text, $exploded);
for($i=0;$i<(count($exploded[0]));$i++)
    echo "<br>". $exploded[0][$i];

UPDATE based on comment

For input of $text = '((LED AND DIODE) OR ("LEE power" and system)) ';

$text = '((LED AND DIODE) OR ("LEE power" and system)) ';
$re = '/"(?:\.|[^"])*"|\(?|\)|(\'(.*?)\'|(\w+))/';
preg_match_all($re, $text, $exploded);

for($i=0;$i<(count($exploded[0]));$i++)
    if($exploded[0][$i]!='')
        echo "<br>". $exploded[0][$i];


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答: Because you're ordering your result in descending order. You should remove the desc in ORDER BY. You can explicitly put ASC to indicate the order as ascending.

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"


问:
Access jframe from another function and add jpanel into it - java swing
I am trying to achieve a specific GUI, BUT I am failed to insert a JPanel into my jframe which is initialized in another function, any idea how to do so ?

here is my code :

```<code>public class CDRTable {
    int totalRecords;
    private final String[] columnNames = { "Year", "String", "Comment" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI() throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }

        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        JPanel p = new JPanel(new BorderLayout());
        p.add(box, BorderLayout.NORTH);
        p.add(new JScrollPane(table));
        return p;
    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI());
        f.setBounds(30, 50, 1300, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}
</code>```

When i try to access the jframe initialized in createAndShowGUI() from public JComponent makeUI() it shows an error

f cannot be resolved

I am very new to JAVA, so please ignore if you feel irritated by my question :)

答:
Somehow, I achieved what I wanted, so I thought I should put the answer my self here.</p>

```<code>public class CDRTable {
    //JFrame f;
    int totalRecords;
    private final String[] columnNames = { "ANUMBER", "BNUMBER", "DATETIME" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI(Container f) throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }
        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        UIManager.put("TabbedPane.selected", Color.lightGray);
        JTabbedPane tabbedPane = new JTabbedPane();
        f.add(tabbedPane);

        JPanel panel = new JPanel();
        tabbedPane.addTab("TABLE", null, panel, null);
        panel.setBackground(Color.white);

        JPanel panel_1 = new JPanel();
        tabbedPane.addTab("GRAPH", null, panel_1, null);
        panel_1.setBackground(Color.white);

        JScrollPane scrollpane = new JScrollPane();
        panel.add(scrollpane, BorderLayout.SOUTH);
        scrollpane.setViewportView(table);

        table.getTableHeader().setBackground(new Color(26,82,118));
        table.getTableHeader().setForeground(Color.white);
        table.getTableHeader().setPreferredSize(new Dimension(100, 40));
        table.setRowHeight(30);

        first.setBackground(new Color(84, 153, 199));
        prev.setBackground(new Color(84, 153, 199));
        next.setBackground(new Color(84, 153, 199));
        last.setBackground(new Color(84, 153, 199));

        first.setForeground(Color.white);
        prev.setForeground(Color.white);
        next.setForeground(Color.white);
        last.setForeground(Color.white);

        panel.add(box);
        panel.add(new JScrollPane(table));
        return scrollpane;

    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame("CDR TABLE");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI(f));
        f.setBounds(30, 50, 1300, 600);
        f.setLayout(new GridLayout(0, 2));
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}
</code>```

Body:
I am trying to achieve a specific GUI, BUT I am failed to insert a JPanel into my jframe which is initialized in another function, any idea how to do so ?

here is my code :

public class CDRTable {
    int totalRecords;
    private final String[] columnNames = { "Year", "String", "Comment" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI() throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }

        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        JPanel p = new JPanel(new BorderLayout());
        p.add(box, BorderLayout.NORTH);
        p.add(new JScrollPane(table));
        return p;
    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI());
        f.setBounds(30, 50, 1300, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

When i try to access the jframe initialized in createAndShowGUI() from public JComponent makeUI() it shows an error

f cannot be resolved

I am very new to JAVA, so please ignore if you feel irritated by my question :)

Body:
Somehow, I achieved what I wanted, so I thought I should put the answer my self here.

public class CDRTable {
    //JFrame f;
    int totalRecords;
    private final String[] columnNames = { "ANUMBER", "BNUMBER", "DATETIME" };
    private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override
        public Class<?> getColumnClass(int column) {
            return (column == 0) ? Integer.class : Object.class;
        }
    };
    private final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    private final JTable table = new JTable(model);
    private final JButton first = new JButton(new AbstractAction("|<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = 1;
            initFilterAndButton();
        }
    });
    private final JButton prev = new JButton(new AbstractAction("<") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex -= 1;
            initFilterAndButton();
        }
    });
    private final JButton next = new JButton(new AbstractAction(">") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex += 1;
            initFilterAndButton();
        }
    });
    private final JButton last = new JButton(new AbstractAction(">|") {
        public void actionPerformed(ActionEvent e) {
            currentPageIndex = maxPageIndex;
            initFilterAndButton();
        }
    });
    private final JTextField field = new JTextField(2);
    private final JLabel label = new JLabel();

    public JComponent makeUI(Container f) throws ClassNotFoundException, SQLException {

        table.setFillsViewportHeight(true);
        table.setRowSorter(sorter);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM cdr LIMIT 1000");

        totalRecords = 1000;
        for (int i = 0; i < totalRecords; i++) {
            model.addRow(new Object[] { 0,0,0 });
        }
        table.setModel(DbUtils.resultSetToTableModel(rs));

        JPanel po = new JPanel();
        po.add(field);
        po.add(label);
        JPanel box = new JPanel(new GridLayout(1, 4, 2, 2));
        for (JComponent r : Arrays.asList(first, prev, po, next, last)) {
            box.add(r);
        }
        int rowCount = model.getRowCount();
        int v = rowCount % itemsPerPage == 0 ? 0 : 1;
        maxPageIndex = rowCount / itemsPerPage + v;
        initFilterAndButton();
        label.setText(String.format("/ %d", maxPageIndex));
        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        field.getInputMap(JComponent.WHEN_FOCUSED).put(enter, "Enter");
        field.getActionMap().put("Enter", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int v = Integer.parseInt(field.getText());
                    if (v > 0 && v <= maxPageIndex) {
                        currentPageIndex = v;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                initFilterAndButton();
            }
        });

        UIManager.put("TabbedPane.selected", Color.lightGray);
        JTabbedPane tabbedPane = new JTabbedPane();
        f.add(tabbedPane);

        JPanel panel = new JPanel();
        tabbedPane.addTab("TABLE", null, panel, null);
        panel.setBackground(Color.white);

        JPanel panel_1 = new JPanel();
        tabbedPane.addTab("GRAPH", null, panel_1, null);
        panel_1.setBackground(Color.white);

        JScrollPane scrollpane = new JScrollPane();
        panel.add(scrollpane, BorderLayout.SOUTH);
        scrollpane.setViewportView(table);

        table.getTableHeader().setBackground(new Color(26,82,118));
        table.getTableHeader().setForeground(Color.white);
        table.getTableHeader().setPreferredSize(new Dimension(100, 40));
        table.setRowHeight(30);

        first.setBackground(new Color(84, 153, 199));
        prev.setBackground(new Color(84, 153, 199));
        next.setBackground(new Color(84, 153, 199));
        last.setBackground(new Color(84, 153, 199));

        first.setForeground(Color.white);
        prev.setForeground(Color.white);
        next.setForeground(Color.white);
        last.setForeground(Color.white);

        panel.add(box);
        panel.add(new JScrollPane(table));
        return scrollpane;

    }

    private final int itemsPerPage = 100;
    private int maxPageIndex;
    private int currentPageIndex = 1;

    private void initFilterAndButton() {
        sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
            @Override
            public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
                int ti = currentPageIndex - 1;
                int ei = entry.getIdentifier();
                return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
            }
        });
        first.setEnabled(currentPageIndex > 1);
        prev.setEnabled(currentPageIndex > 1);
        next.setEnabled(currentPageIndex < maxPageIndex);
        last.setEnabled(currentPageIndex < maxPageIndex);
        field.setText(Integer.toString(currentPageIndex));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CDRTable obj = new CDRTable();
                    obj.createAndShowGUI();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void createAndShowGUI() throws ClassNotFoundException, SQLException {
        JFrame f = new JFrame("CDR TABLE");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new CDRTable().makeUI(f));
        f.setBounds(30, 50, 1300, 600);
        f.setLayout(new GridLayout(0, 2));
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}


问:
sudo in php exec()
I don't know what the deal is here…

So I want to run an applescript: sudo osascript myscript.scpt

This works fine in the terminal, but not when I execute it via PHP's exec(); nothing happens. The console says

```<code>no tty present and no askpass program specified ; TTY=unknown ; …
</code>```

I did my research, and it seems I'm missing the password for the sudo command. I tried a couple different ways to get around this, including:

writing %admin ALL=(ALL) ALL in /etc/sudoers

and proc_open() instead of exec()

none of which seem to be working, consequently driving me CrAzY!

So basically, is there a clear-cut way to get PHP to execute a simple terminal command?

EDIT: to clarify, myscript.scpt is a simple appleScript that changes the onscreen UI (for a larger project).  In theory, simply osascript myscript.scpt should be enough, however the sudo is for some reason necessary to invoke some response from the system.  If the sudo could be somehow eliminated, I don't think I would be having this permissions problem.

答: Run sudo visudo command then set -%sudo   ALL=(ALL:ALL) to %sudo   ALL=(ALL:ALL) NOPASSWD: ALL it will work.

Title: sudo in php exec()

Body:
I don't know what the deal is here…

So I want to run an applescript: sudo osascript myscript.scpt

This works fine in the terminal, but not when I execute it via PHP's exec(); nothing happens. The console says

no tty present and no askpass program specified ; TTY=unknown ; …

I did my research, and it seems I'm missing the password for the sudo command. I tried a couple different ways to get around this, including:

writing %admin ALL=(ALL) ALL in /etc/sudoers

and proc_open() instead of exec()

none of which seem to be working, consequently driving me CrAzY!

So basically, is there a clear-cut way to get PHP to execute a simple terminal command?

EDIT: to clarify, myscript.scpt is a simple appleScript that changes the onscreen UI (for a larger project).  In theory, simply osascript myscript.scpt should be enough, however the sudo is for some reason necessary to invoke some response from the system.  If the sudo could be somehow eliminated, I don't think I would be having this permissions problem.


问:
Remove submit.x and submit.y but retain other values in URL
With my PHP form, I want to pass one value to the URL, but remove submit.x and submit.y. Here's my form:

```<code><form action="booking.php" method="get">
<input type="image" value="access" class="rollbtn" src="../images/book-btn.gif" alt="Book" name="submit" />
</form>
</code>```

I want the URL to display booking.php?submit=access - but omit the x and y coordinates that result from the type="image". If I add onsubmit="this.submit();return false;" it strips everything. Is there a way to do this, or should I just use type="submit" and style the button?

答:
I ran into a similar need, I solved it using jQuery doing something like this:

```<code><script src="where_you_have_jquery.js"></script>
<script>
$('#my_form').submit(function(){
   $('#submit_img').attr('disabled',true);
});
</script>
</code>```

Your submit image has to have "submit_img" (in this case) as its id attribute, for this to work. And your form id="my_form".

Body:
With my PHP form, I want to pass one value to the URL, but remove submit.x and submit.y. Here's my form:

<form action="booking.php" method="get">
<input type="image" value="access" class="rollbtn" src="../images/book-btn.gif" alt="Book" name="submit" />
</form>

I want the URL to display booking.php?submit=access - but omit the x and y coordinates that result from the type="image". If I add onsubmit="this.submit();return false;" it strips everything. Is there a way to do this, or should I just use type="submit" and style the button?

Body:
I ran into a similar need, I solved it using jQuery doing something like this:

<script src="where_you_have_jquery.js"></script>
<script>
$('#my_form').submit(function(){
   $('#submit_img').attr('disabled',true);
});
</script>

Your submit image has to have "submit_img" (in this case) as its id attribute, for this to work. And your form id="my_form".


答:
You can simply change your query to this (order by text ASC):

```<code>SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
(`user_1` = '1' OR `user_2` = '1')
ORDER BY text ASC LIMIT 3
</code>```

If you still want to order by ID, simply change the DESC to ASC

Title: PHP: MYSQLI Change Order By Style

Body:
You can simply change your query to this (order by text ASC):

SELECT * FROM `chat`
WHERE `chat-code` = 'vm1mxo3dpi9gzuo' AND
(`user_1` = '1' OR `user_2` = '1')
ORDER BY text ASC LIMIT 3

If you still want to order by ID, simply change the DESC to ASC

ContentLicense: CC BY-SA 4.0


问:
How to enable proxy servers with anaconda python
We are trying to get the conda install (on windows 8) to work behind a firewall via a proxy server.  Currently,  we are able to use pip to install packages while on our company network by using this at the command prompt:

```<code>pip install pandas --proxy=http://abc.def.xyz.com:1234
</code>```

No passwords need to be specified,  just the proxy server and port. The conda documentation states that proxy servers are possible:

```<code># Proxy settings: http://[username]:[password]@[server]:[port]
proxy_servers:
    http: http://user:pass@corp.com:8080
    https: https://user:pass@corp.com:8080
</code>```

I have tried this with various combinations to see if I can get it to work with or without putting in my username and password.

```<code># formats tried:
http: http://user:pass@abc.def.xyz.com:1234
http: http://abc.def.xyz.com:1234
</code>```

I cannot seem to get it to work. Tried various combinations of quoting things too (passwords have special chars).  Also tried with and without the domain\user.

I can see under the hood, conda is using urlib3 (while pip may be using urlib proxy handler?).  Note that having your username and password in a file is generally frowned upon.

I know we could set up our own http or file location channel and put all the packages there and add the channel to the .condarc config settings. However I would prefer not to have to manage a repository of packages and versions locally.

So.... is there a way to specify,  in the .condarc file the proxy server and port (without user and password) so that conda install works behind a firewall just like pip install on the command line?  Or even an inline call like pip has and works... something like:

```<code>conda install pandas --proxy=abc.def.xyz.com:1234
</code>```

Thanks in advance...

PS:  I really love conda.  I spent last weekend setting up many virtual environments on my home PC.  Documentation was great and everything worked flawlessly. Overall,  much better than pip... if only we could only get this to work inside our company :)

答:
Late answer but maybe other people faced with this problem can benefit.

Create a .condarc file contaninig :

```<code>channels:
- defaults

# Show channel URLs when displaying what is going to be downloaded and
# in 'conda list'. The default is False.
show_channel_urls: True
allow_other_channels: True

proxy_servers:
    http: http://172.**.*.***:8080
    https: https://172.**.*.***:8080

ssl_verify: False
</code>```

Change IP adresses with your own proxy settings.

Put this file in your user's main folder (for me : C:\Users\bakayim)

Restart your anaconda prompt

Body:
We are trying to get the conda install (on windows 8) to work behind a firewall via a proxy server.  Currently,  we are able to use pip to install packages while on our company network by using this at the command prompt:

pip install pandas --proxy=http://abc.def.xyz.com:1234

No passwords need to be specified,  just the proxy server and port. The conda documentation states that proxy servers are possible:

# Proxy settings: http://[username]:[password]@[server]:[port]
proxy_servers:
    http: http://user:pass@corp.com:8080
    https: https://user:pass@corp.com:8080

I have tried this with various combinations to see if I can get it to work with or without putting in my username and password.

# formats tried:
http: http://user:pass@abc.def.xyz.com:1234
http: http://abc.def.xyz.com:1234

I cannot seem to get it to work. Tried various combinations of quoting things too (passwords have special chars).  Also tried with and without the domain\user.

I can see under the hood, conda is using urlib3 (while pip may be using urlib proxy handler?).  Note that having your username and password in a file is generally frowned upon.

I know we could set up our own http or file location channel and put all the packages there and add the channel to the .condarc config settings. However I would prefer not to have to manage a repository of packages and versions locally.

So.... is there a way to specify,  in the .condarc file the proxy server and port (without user and password) so that conda install works behind a firewall just like pip install on the command line?  Or even an inline call like pip has and works... something like:

conda install pandas --proxy=abc.def.xyz.com:1234

Thanks in advance...

PS:  I really love conda.  I spent last weekend setting up many virtual environments on my home PC.  Documentation was great and everything worked flawlessly. Overall,  much better than pip... if only we could only get this to work inside our company :)

Body:
Late answer but maybe other people faced with this problem can benefit.

Create a .condarc file contaninig :

channels:
- defaults

# Show channel URLs when displaying what is going to be downloaded and
# in 'conda list'. The default is False.
show_channel_urls: True
allow_other_channels: True

proxy_servers:
    http: http://172.**.*.***:8080
    https: https://172.**.*.***:8080

ssl_verify: False

Change IP adresses with your own proxy settings.

Put this file in your user's main folder (for me : C:\Users\bakayim)

Restart your anaconda prompt


问:
Is the Oct 2010 Macbook Air able to run WP7 tools with GPU recognition?
Pretty much as the title says, using bootcamp.

WDDM1.1 compliance and GPU recognition confirmed by the WP7 emulator running with EnableFrameRateCounters showing.

I'm considering a Macbook air as a compromise to resolve a need to access iphone dev tools and upgrade my Win7 mobile capability to something reasonably performant with one device.

My current laptop barely runs Win7 and borders on unusable for WP7 tooling hence the interest to try and solve two problems with one device - if realistic.

I assume if the device can run WP7 tools satisfactorily, it would be capable of anything else I might want to do when booted under Win7.

答: The new MacBook Airs do not have very powerful processors. The 11" maxes at 1.66 Ghz, while the 13" maxes at 2.13 Ghz. However, they do have the same GPU as the current 13" MacBook Pro. Also, since they use solid state drives, data access is significantly faster. Overall, it will not be the fastest computer you've used, but it should be enough to work.</p>


问:
Change value in NSDictionary
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'
</code>```

This is my sample server data :

```<code>{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}
</code>```

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

```<code>NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
</code>```

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

```<code>[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];
</code>```

I also tried this :

```<code>    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];
</code>```

Giving same error.

答:
Download these categories classes and add them into your project with:

```<code>#import "NSDictionary+FRMutableDeepCopy.h"

NSMutableDictionary *dixDataMutable = [[dixResponse objectForKey:@"data"] mutableDeepCopy];
</code>```

After that you can update nested dictionary.

Title: Change value in NSDictionary

Body:
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'

This is my sample server data :

{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];

I also tried this :

    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];

Giving same error.

Body:
Download these categories classes and add them into your project with:

#import "NSDictionary+FRMutableDeepCopy.h"

NSMutableDictionary *dixDataMutable = [[dixResponse objectForKey:@"data"] mutableDeepCopy];

After that you can update nested dictionary.


问:
How does c++ handle 0*(large expression)
Concerning speed, if I need to calculate a large expression, say:

```<code>switch1*(large expression 1)+switch2*(large expression 2)
</code>```

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

答:
Theoretically, the compiler could generate code to avoid computing the expression if it could show that it had no side-effects. But in practice, it's unlikely to add code to check if the value is zero because it has no reason to think that it will be.

On the other hand, logical operations (|| and &&) are guaranteed to short-circuit in C++. So you should use them.

Body:
Concerning speed, if I need to calculate a large expression, say:

switch1*(large expression 1)+switch2*(large expression 2)

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?


问:
Remove the cells below the selected one from the UITableView Swift 3
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

```<code>var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)
</code>```

Thanks in advance!

答:
As your myArray was declared as a constant, you cannot modify it.

Change

```<code>let myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

to

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

and remove objects as normal.

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
let selectedIndex = 3
for index in selectedIndex...myArray.count-1 {
    myArray.removeLast()
}
print(myArray)
</code>```

Body:
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

var myArray = ["rahul","rahib","suhail","alex","siya"]

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)

Thanks in advance!

Body:
As your myArray was declared as a constant, you cannot modify it.

Change

let myArray = ["rahul","rahib","suhail","alex","siya"]

to

var myArray = ["rahul","rahib","suhail","alex","siya"]

and remove objects as normal.

var myArray = ["rahul","rahib","suhail","alex","siya"]
let selectedIndex = 3
for index in selectedIndex...myArray.count-1 {
    myArray.removeLast()
}
print(myArray)


问:
Eclipse Maven project structure
I am fairly new to maven. In Eclipse, I created a maven project
Inside this I can see src/main/java and src/test/java also there is one more src folder which again contains main and test folder. Here I am confused in which src folder I need to write the code. What is the main benefit of using main and test folder? Why there are two main and two src folder

答:
In any application you will have two "kinds" of code:

Production code

Test code

Production code is what produces your application. In Maven (and Gradle too) you define a "main" module where your code will be located. So it's located at src/main. Inside you may have several folders:

src/main/java for Java code

src/main/kotlin for Kotlin code

...

Test code is what assures that your Production code works fine. As Production code it needs to be placed inside a "module" usually called "test". So your test code will be located a src/test. And as in Production code you may have several folders:

src/test/java for tests written in Java

src/test/kotlin for tests written in Kotlin

...

It's a good practice to test your Production code to ensure that it indeed works as it should. The reality is that it's not strange to find a developer that doesn't write any test because "it's time consuming". But I strongly recommend you to learn how to write quality tests

That's all talking about "development time". At "deploy time" the only code that became an application is the only that is located inside main module

Title: Eclipse Maven project structure


问:
php form action not reading php variable
It is working when I use page name but not working when I am using page name in php variable.

```<code><?php $action_page = "page2.php"; ?>
<form action="<?php $action_page; ?>" method="post">

</form>
</code>```

Unable to get it where I am wrong.

答:
You missed echo the variable. So when you see the source you will find action attribute with none

Just echo your varibale.

Body:
It is working when I use page name but not working when I am using page name in php variable.

<?php $action_page = "page2.php"; ?>
<form action="<?php $action_page; ?>" method="post">

</form>

Unable to get it where I am wrong.


答:
You need to 'echo' that php variable.</p>

```<code><form action="<?php echo $action_page; ?>" method="post">

</form>
</code>```

Title: php form action not reading php variable

Body:
You need to 'echo' that php variable.

<form action="<?php echo $action_page; ?>" method="post">

</form>


问:
Fastest primality test
Could you suggest a fast, deterministic method that is usable in practice, for testing if a large number is prime or not?

Also, I would like to know how to use non-deterministic primality tests correctly. For example, if I'm using such a method, I can be sure that a number is not prime if the output is "no", but what about the other case, when the output is "probably"? Do I have to test for primality manually in this case?

Thanks in advance.

答:
If you're looking to find a random prime for use in RSA keys, you should use a probabilistic test initially. If the probability is high enough for your needs then stop there. If you must be certain, then once you find a large random probable-prime, verify it with AKS or another non-probabilistic test. This lets you check a lot of non-primes quickly while being certain when you think you've found one.

If you're trying to verify a specific existing number is prime then you should use one of the tests that answers with certainty. There are other non-polynomial-time tests too, use the one that is fastest in practice.

Title: Fastest primality test


答:
You missed something.You should echo your variable.

Your code with the required echo:

```<code><?php $action_page = "page2.php"; ?>
<form action="<?php echo $action_page; ?>" method="post">

</form>
</code>```

Without an echo you'll only get an error.

You can also leave PHP out of this. Just HTML works fine too:

```<code><form action="page2.php" method="post">

</form>
</code>```

Body:
You missed something.You should echo your variable.

Your code with the required echo:

<?php $action_page = "page2.php"; ?>
<form action="<?php echo $action_page; ?>" method="post">

</form>

Without an echo you'll only get an error.

You can also leave PHP out of this. Just HTML works fine too:

<form action="page2.php" method="post">

</form>


问:
FallBackValue in IMultiValueConverter is UnsetValue
I am trying to use a single IMultiValueConverter for more than one controls in XAML.

I am using a simple string Literal to tell what value the IMultiValueConverter is supposed to return.

But I am getting DependencyProperty.UnsetValue in values[2],ie value of parametter named Command when it comes to convert function of ModifierCategoryEnableDisable.

Similar arrangment is working on similar controls on this XAML form within other IMultiValueConverters but not here.
 Please guide what am i missing?

NOTE:

CurrentRec is the currently selected object from the ViewModel

DM_CategoryData is a Class and Current_Selected_Category is a List<DM_CategoryData> in the ViewModel's current object,ie CurrenRec.

XAML:

```<code><GroupBox Width="226" Height="117"  Margin="0" Canvas.Top="252" Header="Modifiers" Canvas.Left="55" >
         <GroupBox.IsEnabled>
             <MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}">
                     <Binding Path="SearchFound" />
                     <Binding Path="CurrentRec.Current_Selected_Category"/>
                     <Binding Path="Command" FallbackValue="1" />
              </MultiBinding>
        </GroupBox.IsEnabled>
 </GroupBox>
</code>```

C#:

```<code>public class ModifierCategoryEnableDisable : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string Command = values[2].ToString();
        bool Retval1 = false;
        string Retval2 = "";
        switch(Command)
        {
            case "1":
                bool SearchFound = (bool)values[0];
                DM_CategoryData CurrentSelectedItemCategory = (DM_CategoryData)(values[1]);
                Retval1 = SearchFound && (CurrentSelectedItemCategory == null ? true : CurrentSelectedItemCategory.IsModifier.Equals("1") ? false : true);
                break;
            case "2":
                Retval2 = "0";
                break;
        }

        if(Command.Equals("1"))
        {
            return Retval1;
        }
        else
        {
            return Retval2;
        }
   }
}
</code>```

答: You are trying to set the fallbackvalue for GroupBox.IsEnabled property and it is a bool type. But you are setting the value as 1. So only Values[2] returns the UnsetValue. Try to set bool value as Fallbackvalue.</p>

Body:
I am trying to use a single IMultiValueConverter for more than one controls in XAML.

I am using a simple string Literal to tell what value the IMultiValueConverter is supposed to return.

But I am getting DependencyProperty.UnsetValue in values[2],ie value of parametter named Command when it comes to convert function of ModifierCategoryEnableDisable.

Similar arrangment is working on similar controls on this XAML form within other IMultiValueConverters but not here.
 Please guide what am i missing?

NOTE:

CurrentRec is the currently selected object from the ViewModel

DM_CategoryData is a Class and Current_Selected_Category is a List<DM_CategoryData> in the ViewModel's current object,ie CurrenRec.

XAML:

<GroupBox Width="226" Height="117"  Margin="0" Canvas.Top="252" Header="Modifiers" Canvas.Left="55" >
         <GroupBox.IsEnabled>
             <MultiBinding Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource MDNS}">
                     <Binding Path="SearchFound" />
                     <Binding Path="CurrentRec.Current_Selected_Category"/>
                     <Binding Path="Command" FallbackValue="1" />
              </MultiBinding>
        </GroupBox.IsEnabled>
 </GroupBox>

C#:

public class ModifierCategoryEnableDisable : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string Command = values[2].ToString();
        bool Retval1 = false;
        string Retval2 = "";
        switch(Command)
        {
            case "1":
                bool SearchFound = (bool)values[0];
                DM_CategoryData CurrentSelectedItemCategory = (DM_CategoryData)(values[1]);
                Retval1 = SearchFound && (CurrentSelectedItemCategory == null ? true : CurrentSelectedItemCategory.IsModifier.Equals("1") ? false : true);
                break;
            case "2":
                Retval2 = "0";
                break;
        }

        if(Command.Equals("1"))
        {
            return Retval1;
        }
        else
        {
            return Retval2;
        }
   }
}


问:
should the app first start with the default language?
I have created 4 languages for the app. I can change the Lauaguage, ok, but if close the app and then start I it again, the app starts atfirst with the default string.xml.

How to let the app starts with the last selected Language ?

should I call the the methode by OnCreate in the mainActivity ?

```<code>     @SuppressWarnings("deprecation")
    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        Configuration conf = getResources().getConfiguration();
        conf.locale = myLocale;
        getResources().updateConfiguration(conf, dm);
        Intent refresh = new Intent(this, Languages.class);
        startActivity(refresh);
        /*         "en" = English
            "hi" =Hindi
            "fr" =French
            "it" =Italian
            "de" =German
            "es" =Spanish
            "ja" =Japanese
            "ko" =Korean
            "nl" =Dutch
            "pt" =Portuguese
            "ru" =Russian
            "zh" =Chinese
            "ar" = arabic
   */
    }
</code>```

How can the user change the default language ?

答: Why don't you store the selected language in shared preferences? That way you can always check for the selected language when your app starts, and then load the appropriate language file. </p>

Body:
I have created 4 languages for the app. I can change the Lauaguage, ok, but if close the app and then start I it again, the app starts atfirst with the default string.xml.

How to let the app starts with the last selected Language ?

should I call the the methode by OnCreate in the mainActivity ?

     @SuppressWarnings("deprecation")
    public void setLocale(String lang) {
        Locale myLocale = new Locale(lang);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        Configuration conf = getResources().getConfiguration();
        conf.locale = myLocale;
        getResources().updateConfiguration(conf, dm);
        Intent refresh = new Intent(this, Languages.class);
        startActivity(refresh);
        /*         "en" = English
            "hi" =Hindi
            "fr" =French
            "it" =Italian
            "de" =German
            "es" =Spanish
            "ja" =Japanese
            "ko" =Korean
            "nl" =Dutch
            "pt" =Portuguese
            "ru" =Russian
            "zh" =Chinese
            "ar" = arabic
   */
    }

How can the user change the default language ?


问:
ASMX returning JSON always inside an xml tag
I have asmx services that return json strings. I use DataContractJsonSerializer class and the resulting json is fine.

When I call these services to consume in a web app, the response is always coming backencapsulated in an xml tag. Any ways to get rid of the xml and return only the json.

Example response :

```<code>< ?xml version="1.0" encoding="utf-8" ?>
< string xmlns="http://whatever.net/">

{"Success":true,"Data":{"RoomList":[{"CreatedAt":"\/Date(1291192978793-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"Reterras numagona alantis","RoomID":44,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":12},{"CreatedAt":"\/Date(1291115544347-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"12122","RoomID":43,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":2},{"CreatedAt":"\/Date(1291115537413-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"12122","RoomID":42,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":2}],"TotalCount":42}}

< / string>
</code>```

答:
Sounds similar to this question:

How to let an ASMX file output JSON

Body:
I have asmx services that return json strings. I use DataContractJsonSerializer class and the resulting json is fine.

When I call these services to consume in a web app, the response is always coming backencapsulated in an xml tag. Any ways to get rid of the xml and return only the json.

Example response :

< ?xml version="1.0" encoding="utf-8" ?>
< string xmlns="http://whatever.net/">

{"Success":true,"Data":{"RoomList":[{"CreatedAt":"\/Date(1291192978793-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"Reterras numagona alantis","RoomID":44,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":12},{"CreatedAt":"\/Date(1291115544347-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"12122","RoomID":43,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":2},{"CreatedAt":"\/Date(1291115537413-0800)\/","GameTimeOut":0,"MatchPointingType":0,"MoveTimeOut":0,"Name":"12122","RoomID":42,"SFID":null,"StartingMatchPoints":0,"UpdateAt":null,"UserID":2}],"TotalCount":42}}

< / string>