问:
How to intercept all AJAX requests made by different JS libraries
I am building a web app with different JS libraries (AngularJS, OpenLayers,...) and need a way to intercept all AJAX responses to be able, in case the logged user session expired (response gets back with 401 Unauthorized status), to redirect him to the login page.

I know AngularJS offers interceptors to manage such scenarios, but wasn't able to find a way to achieve such injection into OpenLayers requests. So I opted for a vanilla JS approach.

Here I found this piece of code...

```<code>(function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        this.addEventListener("readystatechange", function() {
            console.log(this.readyState); // this one I changed
        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);
</code>```

...which I adapted and looks like it behaves as expected (only tested it on last Google Chrome).

As it modifies the prototype of XMLHTTPRequest I am wondering how dangerous this could result or if it could produce serious performance issues. And by the way would there be any valid alternative?

Update: how to intercept requests before they get sent

The previous trick works ok. But what if in the same scenarion you want to inject some headers before the request gets sent? Do the following:

```<code>(function(send) {

    XMLHttpRequest.prototype.send = function(data) {

        // in this case I'm injecting an access token (eg. accessToken) in the request headers before it gets sent
        if(accessToken) this.setRequestHeader('x-access-token', accessToken);

        send.call(this, data);
    };

})(XMLHttpRequest.prototype.send);
</code>```

答:
As kindly pointed out by by Firefox AMO Editor Rob W,

The following code changes the behavior of XMLHttpRequest. By default,
  if the third ("async") parameter is not specified, it defaults to
  true. When it is specified and undefined, it is equivalent to "false",
  which turns a request in a synchronous HTTP request. This causes the
  UI to block while the request is being processed, and some features of
  the XMLHttpRequest API are disabled too.

...

To fix this, replace open.call(....) with open.apply(this, arguments);

And here is a reference link:

https://xhr.spec.whatwg.org/#the-open()-method

Body:
I am building a web app with different JS libraries (AngularJS, OpenLayers,...) and need a way to intercept all AJAX responses to be able, in case the logged user session expired (response gets back with 401 Unauthorized status), to redirect him to the login page.

I know AngularJS offers interceptors to manage such scenarios, but wasn't able to find a way to achieve such injection into OpenLayers requests. So I opted for a vanilla JS approach.

Here I found this piece of code...

(function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        this.addEventListener("readystatechange", function() {
            console.log(this.readyState); // this one I changed
        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);

...which I adapted and looks like it behaves as expected (only tested it on last Google Chrome).

As it modifies the prototype of XMLHTTPRequest I am wondering how dangerous this could result or if it could produce serious performance issues. And by the way would there be any valid alternative?

Update: how to intercept requests before they get sent

The previous trick works ok. But what if in the same scenarion you want to inject some headers before the request gets sent? Do the following:

(function(send) {

    XMLHttpRequest.prototype.send = function(data) {

        // in this case I'm injecting an access token (eg. accessToken) in the request headers before it gets sent
        if(accessToken) this.setRequestHeader('x-access-token', accessToken);

        send.call(this, data);
    };

})(XMLHttpRequest.prototype.send);


来源: stackexchange

问:
Angular 1.4 - reuse same controller in $routeProvider
I am trying to use same controller on both full and mobile views using $routeProvider. Code below does not work out of the box. What am i missing?

Also i could use another idea - same controller, but different templateUrl based on user agent. Can i do that?

```<code>   $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])
</code>```

答:
You can use 2 different controller that share the same function (the controller logic) or use 2 different controller that uses their own function but share a service with all logic inside.

Following is a sample of first case:

angular.module('FunnyAnt.Examples.Routing', ['ngRoute']);

function sharedController($scope) {
  $scope.name = "Shared";
}

angular.module('FunnyAnt.Examples.Routing')
  .controller('HomeController', sharedController);

angular.module('FunnyAnt.Examples.Routing')
  .controller('AboutController', sharedController);

angular.module('FunnyAnt.Examples.Routing')
  .config(function($routeProvider) {
    $routeProvider.
    when('/home', {
      templateUrl: 'embedded.home.html',
      controller: 'HomeController'
    }).
    when('/about', {
      templateUrl: 'embedded.about.html',
      controller: 'AboutController'
    }).
    otherwise({
      redirectTo: '/home'
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular-route.js"></script>

<div ng-app="FunnyAnt.Examples.Routing">

  <script type="text/ng-template" id="embedded.home.html">
    <h1> Home: {{ name }} </h1>
  </script>

  <script type="text/ng-template" id="embedded.about.html">
    <h1> About: {{ name }} </h1>
  </script>

  <div id="navigation">
    Home
    About
  </div>

  <div ng-view></div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use same controller on both full and mobile views using $routeProvider. Code below does not work out of the box. What am i missing?

Also i could use another idea - same controller, but different templateUrl based on user agent. Can i do that?

   $routeProvider
        .when("/details/:id", {
            templateUrl: "views/details.html",
            controller: "detailsController"
        })
        .when("/mdetails/:id", {
            templateUrl:  "views/mobiledetails.html",
            controller: "detailsController"
        })

}])

Body:
You can use 2 different controller that share the same function (the controller logic) or use 2 different controller that uses their own function but share a service with all logic inside.

Following is a sample of first case:

angular.module('FunnyAnt.Examples.Routing', ['ngRoute']);

function sharedController($scope) {
  $scope.name = "Shared";
}

angular.module('FunnyAnt.Examples.Routing')
  .controller('HomeController', sharedController);

angular.module('FunnyAnt.Examples.Routing')
  .controller('AboutController', sharedController);

angular.module('FunnyAnt.Examples.Routing')
  .config(function($routeProvider) {
    $routeProvider.
    when('/home', {
      templateUrl: 'embedded.home.html',
      controller: 'HomeController'
    }).
    when('/about', {
      templateUrl: 'embedded.about.html',
      controller: 'AboutController'
    }).
    otherwise({
      redirectTo: '/home'
    });
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular-route.js"></script>

<div ng-app="FunnyAnt.Examples.Routing">

  <script type="text/ng-template" id="embedded.home.html">
    <h1> Home: {{ name }} </h1>
  </script>

  <script type="text/ng-template" id="embedded.about.html">
    <h1> About: {{ name }} </h1>
  </script>

  <div id="navigation">
    <a href="#/home">Home</a>
    <a href="#/about">About</a>
  </div>

  <div ng-view></div>
</div>


问:
ReactJS How to add a show more/show less button
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

```<code>class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return <div className="container">
     <h3>Click show more to see more data</h3>
     <div className="row">
       <h3>List of Cars</h3>
       <ul>
         {this.cars.slice(0,3).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
       </ul>
     </div>
     <p>
      <a className="btn btn-primary" onClick={this.showMore()}>Show more</a>.
     </p>
   </div>;
  }
}

React.render(<Application />, document.getElementById('app'));
</code>```

Here is a JSBin with the code in action

Can someone help me out?

答:
Here is one solution. JSBin here

First, put all of your component data into its state.

```<code>this.state = {
  cars: [
    { "name" : "Audi", "country" : "Germany"},
    { "name" : "BMW", "country" : "Germany" },
    { "name" : "Chevrolet", "country" : "USA" },
    { "name" : "Citroen", "country" : "France" },
    { "name" : "Hyundai", "country" : "South Korea" },
    { "name" : "Mercedes-Benz", "country" : "Germany" },
    { "name" : "Renault", "country" : "France" },
    { "name" : "Seat", "country" : "Spain" },
  ],
  itemsToShow: 3,
  expanded: false
}

this.showMore = this.showMore.bind(this);
</code>```

Let's use itemsToShow to know how many items to show when not expanded. We can use an expanded variable to change the button text based on the user's action. We're also binding showMore to this component so that the button knows what component's method to call when clicked.

In our render, let's change a few things, like so

```<code><ul>
  {this.state.cars.slice(0, this.state.itemsToShow).map((car, i) =>
    <li key={i}>{car.name} - {car.country}</li>
  )}
</ul>
</code>```

We're going to render from 0 to however many itemsToShow we have. Then we can change the button's text depending on the expanded value like so

```<code><a className="btn btn-primary" onClick={this.showMore}>
  {this.state.expanded ? (
    <span>Show less</span>
  ) : (
    <span>Show more</span>
  )}
</a>.
</code>```

Finally, let's write the showMore method that actually changes the value of itemsToShow.

```<code>showMore() {
  this.state.itemsToShow === 3 ? (
    this.setState({ itemsToShow: this.state.cars.length, expanded: true })
  ) : (
    this.setState({ itemsToShow: 3, expanded: false })
  )
}
</code>```

Body:
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return

Click show more to see more data

List of Cars

         {this.cars.slice(0,3).map((car, i) =>
{car.name} - {car.country}
)}

      Show more.

;
  }
}

React.render(<Application />, document.getElementById('app'));

Here is a JSBin with the code in action

Can someone help me out?

Body:
Here is one solution. JSBin here

First, put all of your component data into its state.

this.state = {
  cars: [
    { "name" : "Audi", "country" : "Germany"},
    { "name" : "BMW", "country" : "Germany" },
    { "name" : "Chevrolet", "country" : "USA" },
    { "name" : "Citroen", "country" : "France" },
    { "name" : "Hyundai", "country" : "South Korea" },
    { "name" : "Mercedes-Benz", "country" : "Germany" },
    { "name" : "Renault", "country" : "France" },
    { "name" : "Seat", "country" : "Spain" },
  ],
  itemsToShow: 3,
  expanded: false
}

this.showMore = this.showMore.bind(this);

Let's use itemsToShow to know how many items to show when not expanded. We can use an expanded variable to change the button text based on the user's action. We're also binding showMore to this component so that the button knows what component's method to call when clicked.

In our render, let's change a few things, like so

<ul>
  {this.state.cars.slice(0, this.state.itemsToShow).map((car, i) =>
    <li key={i}>{car.name} - {car.country}</li>
  )}
</ul>

We're going to render from 0 to however many itemsToShow we have. Then we can change the button's text depending on the expanded value like so

<a className="btn btn-primary" onClick={this.showMore}>
  {this.state.expanded ? (
    <span>Show less</span>
  ) : (
    <span>Show more</span>
  )}
</a>.

Finally, let's write the showMore method that actually changes the value of itemsToShow.

showMore() {
  this.state.itemsToShow === 3 ? (
    this.setState({ itemsToShow: this.state.cars.length, expanded: true })
  ) : (
    this.setState({ itemsToShow: 3, expanded: false })
  )
}

ContentLicense: CC BY-SA 4.0


问:
ValueError: Expecting , delimiter
I am stuck in a problem with this simple code, unable to debug the problem. when I ran the code it gave me this error.

ValueError: Expecting , delimiter: line 4 column 4 (char 20)

Here is my code:

```<code>   import json
   input='''
[
{ "id":"001"
  "name":"nikhil"
  "x":'2'
},
{ "id":"002"
  "name":"chuck"
  "x":"2"
}
]'''

info=json.loads(input)
print "User count:",len(info)

for item in info:

    print "Name",item("name")
    print "id",item("id")
    print "Attribute",item("x")
</code>```

答:
need commas

```<code>import json
#here after "id" : "001" we have ,
    input='''
    [
    { "id":"001",
      "name":"nikhil",
      "x":'2'
    },
    { "id":"002",
      "name":"chuck",
      "x":"2"
    }
    ]'''

    info=json.loads(input)
    print "User count:",len(info)

    for item in info:

        print "Name",item("name")
        print "id",item("id")
        print "Attribute",item("x")
</code>```

Title: ValueError: Expecting , delimiter

Body:
I am stuck in a problem with this simple code, unable to debug the problem. when I ran the code it gave me this error.

ValueError: Expecting , delimiter: line 4 column 4 (char 20)

Here is my code:

   import json
   input='''
[
{ "id":"001"
  "name":"nikhil"
  "x":'2'
},
{ "id":"002"
  "name":"chuck"
  "x":"2"
}
]'''

info=json.loads(input)
print "User count:",len(info)

for item in info:

    print "Name",item("name")
    print "id",item("id")
    print "Attribute",item("x")

Body:
need commas

import json
#here after "id" : "001" we have ,
    input='''
    [
    { "id":"001",
      "name":"nikhil",
      "x":'2'
    },
    { "id":"002",
      "name":"chuck",
      "x":"2"
    }
    ]'''

    info=json.loads(input)
    print "User count:",len(info)

    for item in info:

        print "Name",item("name")
        print "id",item("id")
        print "Attribute",item("x")


问:
How to dynamically change CSS elements to be HTTPS or HTTP
I have CSS with background-image's elements that refer to another site.
Problem is, that in IE you can't have resources if you are in HTTP while they are in HTTPS and vise versa.

I am using ASP.NET and I want to find a way of letting the CSS know about if it was requested in HTTPS or NOT...

And I MUST use absolute... (its on a different site)

Thanks!

答: Just omit the protocol (http: or https:) in your URLs: //domain/path/image.png will use the same protocol as the current page.

ContentLicense: CC BY-SA 2.5


问:
how to disable slider in bootstrap-slider.js?
is there any solution to stop dragging when click on the button.

the documentation do not give proper description

http://www.eyecon.ro/bootstrap-slider/

```<code>$("#stopDrag").click(function(){

});
</code>```

DEMO  http://jsfiddle.net/sweetmaanu/npGw2/

答:
The functionality to disable sliders has been implemented by setting the data-slider-enabled attribute to true or false.

So you can implement a disabled slider like this:

```<code><input id="slide" type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="5" data-slider-enabled="false"/>
</code>```

Or an enabled slider like this:

```<code><input id="slide" type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="5" data-slider-enabled="true"/>
</code>```

You can also enable and disable your sliders like this with jQuery:

```<code>$("#slide").slider();
$("#slide").slider("enable");
$("#slide").slider("disable");
</code>```

Or like this with pure JavaScript:

```<code>var slide = new Slider("#slide");
slide.enable();
slide.disable();
</code>```

For your implementation you would need to do this:

```<code>$("#stopDrag").click(function(){
    $("#slide").slider("disable");
});
</code>```

Body:
is there any solution to stop dragging when click on the button.

the documentation do not give proper description

http://www.eyecon.ro/bootstrap-slider/

$("#stopDrag").click(function(){

});

DEMO  http://jsfiddle.net/sweetmaanu/npGw2/

Body:
The functionality to disable sliders has been implemented by setting the data-slider-enabled attribute to true or false.

So you can implement a disabled slider like this:

<input id="slide" type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="5" data-slider-enabled="false"/>

Or an enabled slider like this:

<input id="slide" type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="5" data-slider-enabled="true"/>

You can also enable and disable your sliders like this with jQuery:

$("#slide").slider();
$("#slide").slider("enable");
$("#slide").slider("disable");

Or like this with pure JavaScript:

var slide = new Slider("#slide");
slide.enable();
slide.disable();

For your implementation you would need to do this:

$("#stopDrag").click(function(){
    $("#slide").slider("disable");
});


问:
Is terminating an object is the same as nulling it?
So i have been going through "Effective Java 2nd Ed."

In item 7 he talks about not using finalizers because they can cause a lot of problems .

But instead of using finalizers we can " provide an explicit termination method" and an example of those is the close statement . and i did not understand what is " termination statements and what are the differences between them and finalizers ?

I came to the conclusion that terminating an object is like nulling it thus the resourses is released . but i think i don`t understand the difference that well . so i appreciate any help .

Thanks !

答:
But instead of using finalizers we can " provide an explicit
  termination method" and an example of those is the close statement .

The authors refers to a close() method that provides a way to clean an object that uses resources to free.

For example when you create and manipulate an InputStream or an OutputStream, you don't want to rely on Java finalizers (that may exist for some subclasses of these interface. For example it is the case for the FileInputStream class that defines a finalize() method) to release the resources associated to the stream but you want to use the method provided by the API to do it : void close() as it is more reliable as finalizer.

java.sql.Statement works in the same way : it provides a close() method to release JDBC resources associated to the statement instance.

I came to the conclusion that terminating an object is like nulling it
  thus the resourses is released .

Assigning an object to null will not necessary free all resources that should be freed. Besides if the object or a field of the object is still referenced by another living object, the object would be not illegible to be garbage collected

At last, being garbage collected may also take a some time.

Why wait if we don't need to use the object ?


问:
Mathematical Concept In Multi-Dimensional Array Sorting
I have found this code written online(not by me), and was hoping to get an answer on what the mathematical formula or concept is that makes this function work. I am curious as to how this person designed this. First, I will explain the requirements that the function must produce, then I will supply the code, and a link to a working code pen for further hacking. P.S. The problem uses the word "vector", but since this is Javascript, vector just means array.

Function Requirements

Given a vector of vectors of words, ex.
[['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']].

Write a function that prints all combinations of one word from the first vector, one word from the second vector, etc.
The solution may not use recursion. The number of vectors and number of elements within each vector may vary.

Example output: 'quick, brown, dog', 'lazy black fox' etc.

My Current Level Of Understanding
I am already aware that by using the principle of multiplication, to find the number of possible combinations available in this scenario is to just multiply the lengths of each inner vector by each other. For this specific example, we get a total of 12(2x3x2) different possible combinations. Where I fall off however, is inside the 4 nested for loops section of the program.

Whoever wrote the code, clearly understands some concept or formula that I do not. Just two examples, are the "previous" variable used inside the loops, and the strategic placement of where they decide to increment the j variable. It seems to me that they might be aware of some mathematical formula.

Code
Below is the code without comments. If you however go to this codepen, I have included the same code with plenty of comments that explain how the program works, so you don't have to trace everything out from scratch. You can also test the output in the built-in console.

```<code>function comboMaker(vector) {

  var length = vector.length;

  var solutions = 1;
  for (var i = 0; i < length; i++) {
    solutions *= vector[i].length;
  }

  var combinations = [];
  for (var i = 0; i < solutions; i++) {
    combinations[i] = [];
  }

  var previous = 1;

  for (var i = 0; i < length; i++) {

    for (var j = 0; j < solutions;) {

      var wordCount = vector[i].length;
      previous *= vector[i].length;

      for (var l = 0; l < wordCount; l++) {

        for (var k = 0; k < (solutions/previous); k++) {
          combinations[j][i] = vector[i][l];
          j++
        }
      }
    }
  }

  for (var i = 0; i < solutions; i++) {
    console.log(combinations[i].join(" "));
  }
}

comboMaker([['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']]);
</code>```

答:
You can consider combination of items as number in mixed radix numeric system.
Radix for every position is equal to number of items in corresponding array (here {2,3,2}). Overall number of combination M is product of all radixes.

You can generate combination either

by making for-loop with counter in range 0..M-1 and separating every digit from this counter and getting corresponding item. Pseudocode

```<code> M = ProductOfLengthsOfArrays
 for c = 0..M-1
     t = c
     combination = {}
     for i = 0..NumOfArrays-1
         d = t %% Array[i].Length   //modulo operation
         t = t / Array[i].Length    //integer division
         combination.add(Array[i][d])
     output combination
</code>```

by counting in mixed radix from 0 to M-1

```<code>  if item is last in the array, get first item and increment the next array
  else get the next item in the same array
</code>```

Body:
I have found this code written online(not by me), and was hoping to get an answer on what the mathematical formula or concept is that makes this function work. I am curious as to how this person designed this. First, I will explain the requirements that the function must produce, then I will supply the code, and a link to a working code pen for further hacking. P.S. The problem uses the word "vector", but since this is Javascript, vector just means array.

Function Requirements

Given a vector of vectors of words, ex.
[['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']].

Write a function that prints all combinations of one word from the first vector, one word from the second vector, etc.
The solution may not use recursion. The number of vectors and number of elements within each vector may vary.

Example output: 'quick, brown, dog', 'lazy black fox' etc.

My Current Level Of Understanding
I am already aware that by using the principle of multiplication, to find the number of possible combinations available in this scenario is to just multiply the lengths of each inner vector by each other. For this specific example, we get a total of 12(2x3x2) different possible combinations. Where I fall off however, is inside the 4 nested for loops section of the program.

Whoever wrote the code, clearly understands some concept or formula that I do not. Just two examples, are the "previous" variable used inside the loops, and the strategic placement of where they decide to increment the j variable. It seems to me that they might be aware of some mathematical formula.

Code
Below is the code without comments. If you however go to this codepen, I have included the same code with plenty of comments that explain how the program works, so you don't have to trace everything out from scratch. You can also test the output in the built-in console.

function comboMaker(vector) {

  var length = vector.length;

  var solutions = 1;
  for (var i = 0; i < length; i++) {
    solutions *= vector[i].length;
  }

  var combinations = [];
  for (var i = 0; i < solutions; i++) {
    combinations[i] = [];
  }

  var previous = 1;

  for (var i = 0; i < length; i++) {

    for (var j = 0; j < solutions;) {

      var wordCount = vector[i].length;
      previous *= vector[i].length;

      for (var l = 0; l < wordCount; l++) {

        for (var k = 0; k < (solutions/previous); k++) {
          combinations[j][i] = vector[i][l];
          j++
        }
      }
    }
  }

  for (var i = 0; i < solutions; i++) {
    console.log(combinations[i].join(" "));
  }
}

comboMaker([['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']]);

Body:
You can consider combination of items as number in mixed radix numeric system.
Radix for every position is equal to number of items in corresponding array (here {2,3,2}). Overall number of combination M is product of all radixes.

You can generate combination either

by making for-loop with counter in range 0..M-1 and separating every digit from this counter and getting corresponding item. Pseudocode

 M = ProductOfLengthsOfArrays
 for c = 0..M-1
     t = c
     combination = {}
     for i = 0..NumOfArrays-1
         d = t %% Array[i].Length   //modulo operation
         t = t / Array[i].Length    //integer division
         combination.add(Array[i][d])
     output combination

by counting in mixed radix from 0 to M-1

  if item is last in the array, get first item and increment the next array
  else get the next item in the same array


问:
Aspectj doesn't work with kotlin
i want to use aspectj aop in kotlin,here is my code:

my annotation in annotation.lazy_list:

Kotlin:

```<code> package anotation

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class lazy_list
</code>```

my aspectj aop class:

```<code>@Aspect
class ActiveListAop{

    @Pointcut("execution(@annotation.lazy_list * *(..))")
    fun profile() {

    }

    @Before("profile()")
    fun testModeOnly(joinPoint: JoinPoint) {
        println("123")
    }

}
</code>```

my usage:

```<code> @lazy_list
    fun all():List<T>{
        return lazy_obj?.all() as List<T>
    }
</code>```

when i call all() function , no error,but wont't print "123", why?

答:
For annotation process in Kotlin, you must enable and use KAPT.  Without this being added via Gradle or Maven plugin, nothing is going to work for annotation processing in Kotlin code.

The Kotlin plugin supports annotation processors like Dagger or DBFlow. In order for them to work with Kotlin classes, apply the kotlin-kapt plugin.

See also:

Pushing the limits of Kotlin annotation processing

kapt: Annotation Processing for Kotlin

Better Annotation Processing: Supporting Stubs in kapt

Title: Aspectj doesn't work with kotlin

Body:
i want to use aspectj aop in kotlin,here is my code:

my annotation in annotation.lazy_list:

Kotlin:

 package anotation

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class lazy_list

my aspectj aop class:

@Aspect
class ActiveListAop{

    @Pointcut("execution(@annotation.lazy_list * *(..))")
    fun profile() {

    }

    @Before("profile()")
    fun testModeOnly(joinPoint: JoinPoint) {
        println("123")
    }

}

my usage:

 @lazy_list
    fun all():List<T>{
        return lazy_obj?.all() as List<T>
    }

when i call all() function , no error,but wont't print "123", why?


问:
can't set constraint layout with scrollView
I am trying since 2 days ago to create this simple layout:  it is not exactly equal, but it is near that what I want.

When I try to set the scrollView on my constraint layout I get always this messy

even if I constraint all my elements, I don't know how to organize the things at the moment, I am really confused about this.

here is my xml:

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".PhotosForPlant">

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.afcosta.inesctec.pt.android.PhotosForPlant"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">

        <ImageView
            android:id="@+id/plantImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/color_cursor_white"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="41dp" />

        <TextView
            android:id="@+id/descricaoTit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Descrição"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="582dp" />

        <TextView
            android:id="@+id/specieDescription"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="622dp" />

        <TextView
            android:id="@+id/Family"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Familia"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="458dp" />

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Genre"
            tools:layout_editor_absoluteX="24dp"
            tools:layout_editor_absoluteY="389dp" />

        <TextView
            android:id="@+id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Espécie"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="309dp" />

        <TextView
            android:id="@+id/FamilyName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="458dp" />

        <TextView
            android:id="@+id/GenreName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="389dp" />

        <TextView
            android:id="@+id/SpecieName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="309dp" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/gallery"
            android:layout_width="408dp"
            android:layout_height="111dp"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="141dp" />
    </android.support.constraint.ConstraintLayout>
</ScrollView>
</code>```

答:
As per your requirement i created sample layout so you can design same according to that i used nestedscrollview rather than scrollview and also applied constraint for all views

```<code>   <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.afcosta.inesctec.pt.android.PhotosForPlant"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">

        <ImageView
            android:id="@+id/plantImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/smile"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintHorizontal_bias="0.573"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/toolbar2" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViLeft"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/plantImage"
            android:layout_marginStart="8dp" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail1"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="20dp"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            android:layout_marginStart="8dp" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail2"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView13" />

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail3"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView14" />

        <TextView
            android:id="@+id/textView12"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/plantImage"
            android:layout_marginEnd="8dp" />

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold1"
            android:textStyle="bold"
            android:layout_marginTop="20dp"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintLeft_toRightOf="@+id/textView5"
            android:layout_marginStart="20dp" />

        <TextView
            android:id="@+id/textView14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold2"
            android:textStyle="bold"
            app:layout_constraintLeft_toRightOf="@+id/textView6"
            android:layout_marginStart="20dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView13" />

        <TextView
            android:id="@+id/textView15"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold3"
            app:layout_constraintLeft_toRightOf="@+id/textView7"
            android:textStyle="bold"
            android:layout_marginStart="20dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView14" />

        <TextView
            android:id="@+id/textView16"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="TextView TextView TextView TextView TextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextView"

            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintHorizontal_bias="0.0"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView15" />

        <android.support.v7.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:id="@+id/recyclerview"
            app:layout_constraintTop_toBottomOf="@+id/textView16"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:layout_editor_absoluteX="8dp" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

    </android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

here is design and blue print

NOTE: You are using RecyclerView in ScrollView which is not recommended.

Body:
I am trying since 2 days ago to create this simple layout:  it is not exactly equal, but it is near that what I want.

When I try to set the scrollView on my constraint layout I get always this messy

even if I constraint all my elements, I don't know how to organize the things at the moment, I am really confused about this.

here is my xml:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".PhotosForPlant">

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.afcosta.inesctec.pt.android.PhotosForPlant"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">

        <ImageView
            android:id="@+id/plantImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/color_cursor_white"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="41dp" />

        <TextView
            android:id="@+id/descricaoTit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Descrição"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="582dp" />

        <TextView
            android:id="@+id/specieDescription"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="622dp" />

        <TextView
            android:id="@+id/Family"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Familia"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="458dp" />

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Genre"
            tools:layout_editor_absoluteX="24dp"
            tools:layout_editor_absoluteY="389dp" />

        <TextView
            android:id="@+id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Espécie"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="309dp" />

        <TextView
            android:id="@+id/FamilyName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="458dp" />

        <TextView
            android:id="@+id/GenreName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="389dp" />

        <TextView
            android:id="@+id/SpecieName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="96dp"
            tools:layout_editor_absoluteY="309dp" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/gallery"
            android:layout_width="408dp"
            android:layout_height="111dp"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="141dp" />
    </android.support.constraint.ConstraintLayout>
</ScrollView>

Body:
As per your requirement i created sample layout so you can design same according to that i used nestedscrollview rather than scrollview and also applied constraint for all views

   <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.afcosta.inesctec.pt.android.PhotosForPlant"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp">

        <ImageView
            android:id="@+id/plantImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/smile"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintHorizontal_bias="0.573"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/toolbar2" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViLeft"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/plantImage"
            android:layout_marginStart="8dp" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail1"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="20dp"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            android:layout_marginStart="8dp" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail2"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView13" />

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewDetail3"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView14" />

        <TextView
            android:id="@+id/textView12"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/plantImage"
            android:layout_marginEnd="8dp" />

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold1"
            android:textStyle="bold"
            android:layout_marginTop="20dp"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintLeft_toRightOf="@+id/textView5"
            android:layout_marginStart="20dp" />

        <TextView
            android:id="@+id/textView14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold2"
            android:textStyle="bold"
            app:layout_constraintLeft_toRightOf="@+id/textView6"
            android:layout_marginStart="20dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView13" />

        <TextView
            android:id="@+id/textView15"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextViewBold3"
            app:layout_constraintLeft_toRightOf="@+id/textView7"
            android:textStyle="bold"
            android:layout_marginStart="20dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView14" />

        <TextView
            android:id="@+id/textView16"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="TextView TextView TextView TextView TextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextView"

            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintHorizontal_bias="0.0"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/textView15" />

        <android.support.v7.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:id="@+id/recyclerview"
            app:layout_constraintTop_toBottomOf="@+id/textView16"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:layout_editor_absoluteX="8dp" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

    </android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>

here is design and blue print

NOTE: You are using RecyclerView in ScrollView which is not recommended.


问:
msdeploy getting ERROR_CERTIFICATE_VALIDATION_FAILED, allowUntrusted being ignored
I am using msdeploy to push out website code to 4 different servers (test and production servers). Works fine on the first 3, but the 4th is giving me an ERROR_CERTIFICATE_VALIDATION_FAILED error. I am using the -allowUntrusted option.

```<code>"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:iisApp="E:\workspace\testDeploy\outproject\_PublishedWebsites\<webfolder>" -dest:iisApp="mycompany.com",ComputerName="https://<hostip>:8172/MsDeploy.axd",UserName="<userid>",Password="****",AuthType="Basic" -allowUntrusted -enableRule:AppOffline -skip:objectName=filePath,absolutePath="^.*<webfolder>\\web.*\.config$|^.*mycompany\.com\\web.*\.config"

Error Code: ERROR_CERTIFICATE_VALIDATION_FAILED
More Infenter code hereormation: Connected to the remote computer ("<hostip>") using the specified process ("Web Management Service"), but could not verify the server's certificate. If you trust the server, connect again and allow untrusted certificates.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_CERTIFICATE_VALIDATION_FAILED.
Error: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Error: The remote certificate is invalid according to the validation procedure.
</code>```

Any idea what I am missing?

答:
I notice you used the IP address for the deployment server:

```<code>-dest:iisApp="mycompany.com",ComputerName="https://<hostip>:8172/MsDeploy.axd"
</code>```

This caused the certificate validation error for me because the SSL certificate was issued for the domain name, not the IP address. Changing to domain name instead of IP address fixed it.

Body:
I am using msdeploy to push out website code to 4 different servers (test and production servers). Works fine on the first 3, but the 4th is giving me an ERROR_CERTIFICATE_VALIDATION_FAILED error. I am using the -allowUntrusted option.

"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:iisApp="E:\workspace\testDeploy\outproject\_PublishedWebsites\<webfolder>" -dest:iisApp="mycompany.com",ComputerName="https://<hostip>:8172/MsDeploy.axd",UserName="<userid>",Password="****",AuthType="Basic" -allowUntrusted -enableRule:AppOffline -skip:objectName=filePath,absolutePath="^.*<webfolder>\\web.*\.config$|^.*mycompany\.com\\web.*\.config"

Error Code: ERROR_CERTIFICATE_VALIDATION_FAILED
More Infenter code hereormation: Connected to the remote computer ("<hostip>") using the specified process ("Web Management Service"), but could not verify the server's certificate. If you trust the server, connect again and allow untrusted certificates.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_CERTIFICATE_VALIDATION_FAILED.
Error: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Error: The remote certificate is invalid according to the validation procedure.

Any idea what I am missing?

Body:
I notice you used the IP address for the deployment server:

-dest:iisApp="mycompany.com",ComputerName="https://<hostip>:8172/MsDeploy.axd"

This caused the certificate validation error for me because the SSL certificate was issued for the domain name, not the IP address. Changing to domain name instead of IP address fixed it.


问:
Jersey: Get binary data from post request
I am trying to build a Java server using Jersey, which accepts POST requests with binary data.

Here is a sample request it should accept:

```<code>curl -XPOST --data-binary @/path/to/some/file "localhost:<port>/myServer/processMyData"
</code>```

I implemented something that currently doesn't work:

```<code>@Path("/myServer")
class MyServer {

    @POST
    @Path("/processMyData")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    String processMyData(byte[] payload) {
        return "Sanity check string";
    }
}
</code>```

When I run the curl command (see above) at the first time, I get the error:

```<code>curl: (56) Recv failure: Connection reset by peer
</code>```

Then, curl prints nothing when I call it again, and exits with status 0, while the server ignores everything.

What am I doing wrong?

Note: When I remove the --data-binary @/path/to/some/file clause from the curl command, the request is accepted on the server. How can I accept the binary data in Jersey?

答:
Answering myself...

It is very simple, the removal of @Consumes(MediaType.APPLICATION_OCTET_STREAM) solved the problem

Body:
I am trying to build a Java server using Jersey, which accepts POST requests with binary data.

Here is a sample request it should accept:

curl -XPOST --data-binary @/path/to/some/file "localhost:<port>/myServer/processMyData"

I implemented something that currently doesn't work:

@Path("/myServer")
class MyServer {

    @POST
    @Path("/processMyData")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    String processMyData(byte[] payload) {
        return "Sanity check string";
    }
}

When I run the curl command (see above) at the first time, I get the error:

curl: (56) Recv failure: Connection reset by peer

Then, curl prints nothing when I call it again, and exits with status 0, while the server ignores everything.

What am I doing wrong?

Note: When I remove the --data-binary @/path/to/some/file clause from the curl command, the request is accepted on the server. How can I accept the binary data in Jersey?


问:
CSS transition effect makes image blurry / moves image 1px, in Chrome?
I have some CSS that on hover, a CSS transition effect will moves a div.

The problem, as you can see in the example, is that the translate transition has the horrible side effect of making the image in the div move by 1px down/right (and possibly resize ever so slightly?) so that it appears out of place and out of focus...

The glitch seems to apply the whole time the hover effect is applied, and from a process of trial and error I can safely say only seems to occur when the translate transition moves the div (box shadow and opacity are also applied but make no difference to the error when removed).

The problem only seems to happen when the page has scrollbars. So the example with just one instance of the div is fine, but once more identical divs are added and the page therefore requires a scrollbar the problem strikes again...

答:
Try filter: blur(0);

It worked for me

Body:
Try filter: blur(0);

It worked for me


问:
How Can I Monitor Which Window Currently Has Keyboard Focus
Is there a way to track which window currently has keyboard focus. I could handle WM_SETFOCUS for every window but I'm wondering if there's an alternative, simpler method (i.e. a single message handler somewhere).

I could use OnIdle() in MFC and call GetFocus() but that seems a little hacky.

答:
Well, this may not be very graceful... but you can retrieve the current focused control pretty easily.  So you might consider setting up a timer that asks every 1/2 second or so "Where is the current focus?"... Then you can observe changes.  Example Delphi code is below; it should be pretty easy to adapt, since the real work is in the Windows API calls.

```<code><snip>

function TForm1.GetCurrentHandle: integer;
var
  activeWinHandle: HWND;
  focusedThreadID : DWORD;
begin
  //return the Windows handle of the currently focused control
  Result := 0;
  activeWinHandle := GetForegroundWindow;
  focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);
  if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin
    try
      Result := GetFocus;
    finally
      AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);
    end;
  end;  //if attached
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  //give notification if the handle changed
  //(this code gets fired by a timer)
  CurrentHandle := GetCurrentHandle;
  if CurrentHandle <> PreviousHandle then begin
    Label1.Caption := 'Last focus change occurred @ ' + DateTimeToStr(Now);
  end;
  PreviousHandle := CurrentHandle;
end;

<snip>
</code>```

Body:
Well, this may not be very graceful... but you can retrieve the current focused control pretty easily.  So you might consider setting up a timer that asks every 1/2 second or so "Where is the current focus?"... Then you can observe changes.  Example Delphi code is below; it should be pretty easy to adapt, since the real work is in the Windows API calls.

<snip>

function TForm1.GetCurrentHandle: integer;
var
  activeWinHandle: HWND;
  focusedThreadID : DWORD;
begin
  //return the Windows handle of the currently focused control
  Result := 0;
  activeWinHandle := GetForegroundWindow;
  focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);
  if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin
    try
      Result := GetFocus;
    finally
      AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);
    end;
  end;  //if attached
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  //give notification if the handle changed
  //(this code gets fired by a timer)
  CurrentHandle := GetCurrentHandle;
  if CurrentHandle <> PreviousHandle then begin
    Label1.Caption := 'Last focus change occurred @ ' + DateTimeToStr(Now);
  end;
  PreviousHandle := CurrentHandle;
end;

<snip>

OwnerDisplayName: kogus

LastEditorDisplayName: kogus


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答:
I'd say C and python are the best integrated languages with linux.

You'll need:

A text editor (I won't suggest one
as I don't want to cause a
(/another) religious debate).

gcc to compile C or cpython to run python programs.

Some knowledge of a
shell (like bash).

For more complicated C programs, knowledge of a build system like make/scons/cmake/etc

For debugging there is gdb for C and pdb for python.

For version control there's git/mercurial/svn/etc.

Title: Tools used for programming in Linux


问:
C# Combobox item text change?
I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?

This is my code:

```<code>        private void getAdr()
    {
        string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();

        SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
        SqlParameter parUserID = new SqlParameter("@userID", Login.id);
        getAdr.Parameters.Add(parUserID);
        getAdr.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(getAdr);
        DataTable dt = new DataTable();
        da.Fill(dt);

        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "adressID";
        comboBox1.ValueMember = "adressID";

        textBox5.DataBindings.Add("Text", dt, "adress");
        textBox6.DataBindings.Add("Text", dt, "floor");
        textBox7.DataBindings.Add("Text", dt, "city");
        textBox8.DataBindings.Add("Text", dt, "state");
        textBox9.DataBindings.Add("Text", dt, "country");
        textBox10.DataBindings.Add("Text", dt, "zipcode");

        comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";

    }
</code>```

答:
When you set datasource property what you must change is that property and automatically your changes are visible in the combo.

For doing that i recommend you to use BindingSource object like this:

```<code> BindingSource Adresses = new BindingSource();
 Adresses.DataSource = dt;

 comboBox1.DataSource = Adresses;
 comboBox1.DisplayMember = "adressID";
 comboBox1.ValueMember = "adressID";
</code>```

When you change some data in dt object you should call:

```<code>Adresses.ResetBindings(true);
</code>```

To updtate combo's data.

Title: C# Combobox item text change?

Body:
I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?

This is my code:

        private void getAdr()
    {
        string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();

        SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
        SqlParameter parUserID = new SqlParameter("@userID", Login.id);
        getAdr.Parameters.Add(parUserID);
        getAdr.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(getAdr);
        DataTable dt = new DataTable();
        da.Fill(dt);

        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "adressID";
        comboBox1.ValueMember = "adressID";

        textBox5.DataBindings.Add("Text", dt, "adress");
        textBox6.DataBindings.Add("Text", dt, "floor");
        textBox7.DataBindings.Add("Text", dt, "city");
        textBox8.DataBindings.Add("Text", dt, "state");
        textBox9.DataBindings.Add("Text", dt, "country");
        textBox10.DataBindings.Add("Text", dt, "zipcode");

        comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";

    }

Body:
When you set datasource property what you must change is that property and automatically your changes are visible in the combo.

For doing that i recommend you to use BindingSource object like this:

 BindingSource Adresses = new BindingSource();
 Adresses.DataSource = dt;

 comboBox1.DataSource = Adresses;
 comboBox1.DisplayMember = "adressID";
 comboBox1.ValueMember = "adressID";

When you change some data in dt object you should call:

Adresses.ResetBindings(true);

To updtate combo's data.


问:
DoJo AMD any realworld applications out there?
I am new to DoJo and  Iam experienced with other JS tools such as AngularJS NodeJA, Knockout etc. But I am not able to find any full application such as ToDo or Contacts etc in the AMD or DoJo 1.7 or later. All the one exist or pre 1.7 version and I cannot use them in my project.

I know this is a well seasoned and mature product, so may be my search is not right I been searching using DoJo AMD 1.7 Ajax Application and all possible combinations.

I see Modern Hello World, seriously,  I know how to do that now. How do I get beyond that?

Appreciate if anyone could point me to a useful DoJo app tutorial using AMD.

Thank you

答:
Several useful resource here:

To do simple app:
http://todomvc.com/examples/dojo/

Custom widget tutorial, show how to set up a simple app like card name:
https://dojotoolkit.org/documentation/tutorials/1.10/recipes/custom_widget/

Learn by looking at how dojo team write their test cases, so you can see how they initiate and use their widget (select Browse tests > [popular]):

http://archive.dojotoolkit.org/dojo-2017-02-01/

Link to DOJO API so you can read details for each dojo module.

http://dojotoolkit.org/api/

Dojo Boilerplate a set of files to help you rapidly get up and running/ It illustrates some basic best practices when working with Dojo (it is very useful IMO).
https://github.com/csnover/dojo-boilerplate

I hope it helps as a starting point.


问:
Is there any way to store the trained neural network into memory in MATLAB?
I try to create a speaker recognition system. The training time is so long so I wonder if there is a way I can store the model and load it from the memory when the GUI launchs?</p>

答:
You can save your trained network with

```<code>save net
</code>```

this will save the network called net as net.mat, you can then load it to the workspace with

```<code>load net
</code>```

To do your prediction, you can use

sim(net, inputs)

Type

```<code>doc sim
</code>```

for detailed help

(more details on this can be easily found on MATLAB central)

Body:
You can save your trained network with

save net

this will save the network called net as net.mat, you can then load it to the workspace with

load net

To do your prediction, you can use

sim(net, inputs)

Type

doc sim

for detailed help

(more details on this can be easily found on MATLAB central)


问:
how to delete a substring and get another part from that string
I have some string that have a type like this

```<code>NSString *string1 = @"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";
</code>```

if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"

i have implement a code like this :

```<code>NSString *subString1;
int count = [string1 length];
NSLog(@"count : %d", count);
subString1 = [string1 substringFromIndex:121];
</code>```

but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"

how can i do to fix it??

答:
you can use stringWithRange method of NSString.
subString1 = [string1 stringWithRange:NSMakeRange(startPos,yourLengthToSelect)];

or you can use componentSeparetedByString and break string using @"/". it will return array of string. get your desired string using array index.

Body:
I have some string that have a type like this

NSString *string1 = @"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";

if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"

i have implement a code like this :

NSString *subString1;
int count = [string1 length];
NSLog(@"count : %d", count);
subString1 = [string1 substringFromIndex:121];

but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"

how can i do to fix it??


问:
What is wrong with my code? (selecting all from DB not working)
Long time that i dont program php.

i made a function for the  cliente profile,so the cliente can see his logo

this is the cliente code

```<code>function display_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE email=?");
    $stmt->bind_param("s", $em);
    $em = $_SESSION['useremail'];
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];
    echo '<img style="    margin-top: -14;
    object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

This code works fine for the  cliente profile.
But  now i am trying to display all users in my admin painel.

This way ...

```<code>function display_all_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT * LogoImage FROM usuarios");

    // $stmt = $conn->prepare("SELECT  LogoImage FROM usuarios WHERE nome=?");
    // $stmt->bind_param("s", $em);
    // $em = $_SESSION['userName'];
    $stmt->execute();
    $stmt->bind_result($LogoImage);

     while($stmt->fetch()) {
        $tmp = array();
        $tmp["LogoImage"] = $LogoImage;

        array_push($LogoImage, $tmp);
    }

    $img =$rows['LogoImage'];

echo '<img style="    margin-top: -14;
object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

i know that i'm doing something wrong, please someone help, long time that i don't program php.

Fixed

```<code>function display_all_logo($user_logo){
    global $conn;

     $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE  logoImage = ?  ");

    $stmt->bind_param("s", $em);
    $em = $user_logo;
    $stmt->execute();

    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];

return '<img style="    margin-top: -14;
object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

答:
Your should select the column name </p>

```<code> $stmt = $conn->prepare("SELECT LogoImage FROM usuarios");
</code>```

Body:
Long time that i dont program php.

i made a function for the  cliente profile,so the cliente can see his logo

this is the cliente code

function display_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE email=?");
    $stmt->bind_param("s", $em);
    $em = $_SESSION['useremail'];
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];
    echo '';

}

This code works fine for the  cliente profile.
But  now i am trying to display all users in my admin painel.

This way ...

function display_all_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT * LogoImage FROM usuarios");

    // $stmt = $conn->prepare("SELECT  LogoImage FROM usuarios WHERE nome=?");
    // $stmt->bind_param("s", $em);
    // $em = $_SESSION['userName'];
    $stmt->execute();
    $stmt->bind_result($LogoImage);

     while($stmt->fetch()) {
        $tmp = array();
        $tmp["LogoImage"] = $LogoImage;

        array_push($LogoImage, $tmp);
    }

    $img =$rows['LogoImage'];

echo '';

}

i know that i'm doing something wrong, please someone help, long time that i don't program php.

Fixed

function display_all_logo($user_logo){
    global $conn;

     $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE  logoImage = ?  ");

    $stmt->bind_param("s", $em);
    $em = $user_logo;
    $stmt->execute();

    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];

return '';

}

Body:
Your should select the column name

 $stmt = $conn->prepare("SELECT LogoImage FROM usuarios");


问:
ReactJS How to add a show more/show less button
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

```<code>class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return <div className="container">
     <h3>Click show more to see more data</h3>
     <div className="row">
       <h3>List of Cars</h3>
       <ul>
         {this.cars.slice(0,3).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
       </ul>
     </div>
     <p>
      <a className="btn btn-primary" onClick={this.showMore()}>Show more</a>.
     </p>
   </div>;
  }
}

React.render(<Application />, document.getElementById('app'));
</code>```

Here is a JSBin with the code in action

Can someone help me out?

答:
class Application extends React.Component {
  constructor() {
    super()
    this.state = {
      loadMore: false
    }
    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
   this.setState({loadMore: true})
  }

  render() {
    const loadCount = this.state.loadMore ? this.cars.length : 3;
    return (

Click show more to see more data

List of Cars

         {this.cars.slice(0,loadCount).map((car, i) =>
{car.name} - {car.country}
)}

       className="btn btn-primary" onClick={this.showMore()}>Show more

   );
  }
}

React.render(<Application />, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" /></code>```

use this.setState() to reRender the component!

Body:
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return

Click show more to see more data

List of Cars

         {this.cars.slice(0,3).map((car, i) =>
{car.name} - {car.country}
)}

      Show more.

;
  }
}

React.render(<Application />, document.getElementById('app'));

Here is a JSBin with the code in action

Can someone help me out?

Body:
class Application extends React.Component {
  constructor() {
    super()
    this.state = {
      loadMore: false
    }
    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
   this.setState({loadMore: true})
  }

  render() {
    const loadCount = this.state.loadMore ? this.cars.length : 3;
    return (
    <div className="container">
     <h3>Click show more to see more data</h3>
     <div className="row">
       <h3>List of Cars</h3>
       <ul>
         {this.cars.slice(0,loadCount).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
       </ul>
     </div>
     <p>
      <a> className="btn btn-primary" onClick={this.showMore()}>Show more</a>
     </p>
   </div>
   );
  }
}

React.render(<Application />, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />

use this.setState() to reRender the component!


问:
How to Iterate through arithmetic operators across a static, excecutable formula in Python?
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

```<code>1
1,2
1,3
2,3
1,2,3
</code>```

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

```<code>1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...
</code>```

arises and gives results of the equation.

How might I go about doing this?

答:
Here is how I would approach it:

```<code>import itertools
import operator
</code>```

First make the list of all possible combinations:

```<code>funcs = [operator.add, operator.sub, operator.mul, operator.div]

combos = list(itertools.product(funcs, repeat=2))

>>[(<function operator.add>, <function operator.add>),
 (<function operator.add>, <function operator.sub>),
 (<function operator.add>, <function operator.mul>),
 (<function operator.add>, <function operator.div>),
 (<function operator.sub>, <function operator.add>),
 (<function operator.sub>, <function operator.sub>),
 (<function operator.sub>, <function operator.mul>),
 (<function operator.sub>, <function operator.div>),
 (<function operator.mul>, <function operator.add>),
 (<function operator.mul>, <function operator.sub>),
 (<function operator.mul>, <function operator.mul>),
 (<function operator.mul>, <function operator.div>),
 (<function operator.div>, <function operator.add>),
 (<function operator.div>, <function operator.sub>),
 (<function operator.div>, <function operator.mul>),
 (<function operator.div>, <function operator.div>)]
</code>```

Then we will iterate through this list solving every possible outcome:

```<code>for fn in combos:
    print 'This combo {} yielded this result {}'.format(fn, fn[1](fn[0](*seq[:2]), seq[-1]))

This combo (<built-in function add>, <built-in function add>) yielded this result 6
This combo (<built-in function add>, <built-in function sub>) yielded this result 0
This combo (<built-in function add>, <built-in function mul>) yielded this result 9
This combo (<built-in function add>, <built-in function div>) yielded this result 1
This combo (<built-in function sub>, <built-in function add>) yielded this result 2
This combo (<built-in function sub>, <built-in function sub>) yielded this result -4
This combo (<built-in function sub>, <built-in function mul>) yielded this result -3
This combo (<built-in function sub>, <built-in function div>) yielded this result -1
This combo (<built-in function mul>, <built-in function add>) yielded this result 5
This combo (<built-in function mul>, <built-in function sub>) yielded this result -1
This combo (<built-in function mul>, <built-in function mul>) yielded this result 6
This combo (<built-in function mul>, <built-in function div>) yielded this result 0
This combo (<built-in function div>, <built-in function add>) yielded this result 3
This combo (<built-in function div>, <built-in function sub>) yielded this result -3
This combo (<built-in function div>, <built-in function mul>) yielded this result 0
This combo (<built-in function div>, <built-in function div>) yielded this result 0
</code>```

Edit: Here is a way that follows the rules of operations

```<code>ops = ['+','-','*','/']

combos = list(itertools.product(ops, repeat=2))

for tup in list(itertools.product(combos, [seq])):
    print 'These operations {} evaluate to this ---> {}'.format(tup[0],eval(''.join(*zip(seq[0],tup[0][0],seq[1],tup[0][1],seq[-1]))))

These operations ('+', '+') evaluate to this ---> 6
These operations ('+', '-') evaluate to this ---> 0
These operations ('+', '*') evaluate to this ---> 7
These operations ('+', '/') evaluate to this ---> 1
These operations ('-', '+') evaluate to this ---> 2
These operations ('-', '-') evaluate to this ---> -4
These operations ('-', '*') evaluate to this ---> -5
These operations ('-', '/') evaluate to this ---> 1
These operations ('*', '+') evaluate to this ---> 5
These operations ('*', '-') evaluate to this ---> -1
These operations ('*', '*') evaluate to this ---> 6
These operations ('*', '/') evaluate to this ---> 0
These operations ('/', '+') evaluate to this ---> 3
These operations ('/', '-') evaluate to this ---> -3
These operations ('/', '*') evaluate to this ---> 0
These operations ('/', '/') evaluate to this ---> 0
</code>```

Body:
I'm trying to use itertools to iterate through mathematical operators.
Typically with an array of [1, 2, 3], using combinations I can get the results:

1
1,2
1,3
2,3
1,2,3

etc.

I want to use this on an array of [1, 2, 3] in such a way that:

1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...

arises and gives results of the equation.

How might I go about doing this?

Body:
Here is how I would approach it:

import itertools
import operator

First make the list of all possible combinations:

funcs = [operator.add, operator.sub, operator.mul, operator.div]

combos = list(itertools.product(funcs, repeat=2))

>>[(<function operator.add>, <function operator.add>),
 (<function operator.add>, <function operator.sub>),
 (<function operator.add>, <function operator.mul>),
 (<function operator.add>, <function operator.div>),
 (<function operator.sub>, <function operator.add>),
 (<function operator.sub>, <function operator.sub>),
 (<function operator.sub>, <function operator.mul>),
 (<function operator.sub>, <function operator.div>),
 (<function operator.mul>, <function operator.add>),
 (<function operator.mul>, <function operator.sub>),
 (<function operator.mul>, <function operator.mul>),
 (<function operator.mul>, <function operator.div>),
 (<function operator.div>, <function operator.add>),
 (<function operator.div>, <function operator.sub>),
 (<function operator.div>, <function operator.mul>),
 (<function operator.div>, <function operator.div>)]

Then we will iterate through this list solving every possible outcome:

for fn in combos:
    print 'This combo {} yielded this result {}'.format(fn, fn[1](fn[0](*seq[:2]), seq[-1]))

This combo (<built-in function add>, <built-in function add>) yielded this result 6
This combo (<built-in function add>, <built-in function sub>) yielded this result 0
This combo (<built-in function add>, <built-in function mul>) yielded this result 9
This combo (<built-in function add>, <built-in function div>) yielded this result 1
This combo (<built-in function sub>, <built-in function add>) yielded this result 2
This combo (<built-in function sub>, <built-in function sub>) yielded this result -4
This combo (<built-in function sub>, <built-in function mul>) yielded this result -3
This combo (<built-in function sub>, <built-in function div>) yielded this result -1
This combo (<built-in function mul>, <built-in function add>) yielded this result 5
This combo (<built-in function mul>, <built-in function sub>) yielded this result -1
This combo (<built-in function mul>, <built-in function mul>) yielded this result 6
This combo (<built-in function mul>, <built-in function div>) yielded this result 0
This combo (<built-in function div>, <built-in function add>) yielded this result 3
This combo (<built-in function div>, <built-in function sub>) yielded this result -3
This combo (<built-in function div>, <built-in function mul>) yielded this result 0
This combo (<built-in function div>, <built-in function div>) yielded this result 0

Edit: Here is a way that follows the rules of operations

ops = ['+','-','*','/']

combos = list(itertools.product(ops, repeat=2))

for tup in list(itertools.product(combos, [seq])):
    print 'These operations {} evaluate to this ---> {}'.format(tup[0],eval(''.join(*zip(seq[0],tup[0][0],seq[1],tup[0][1],seq[-1]))))

These operations ('+', '+') evaluate to this ---> 6
These operations ('+', '-') evaluate to this ---> 0
These operations ('+', '*') evaluate to this ---> 7
These operations ('+', '/') evaluate to this ---> 1
These operations ('-', '+') evaluate to this ---> 2
These operations ('-', '-') evaluate to this ---> -4
These operations ('-', '*') evaluate to this ---> -5
These operations ('-', '/') evaluate to this ---> 1
These operations ('*', '+') evaluate to this ---> 5
These operations ('*', '-') evaluate to this ---> -1
These operations ('*', '*') evaluate to this ---> 6
These operations ('*', '/') evaluate to this ---> 0
These operations ('/', '+') evaluate to this ---> 3
These operations ('/', '-') evaluate to this ---> -3
These operations ('/', '*') evaluate to this ---> 0
These operations ('/', '/') evaluate to this ---> 0


问:
Python function equivalent to R's `pretty()`?
I'm replicating some R code in Python.

I've tripped up on R's pretty().

All I need is pretty(x), where x is some numeric.

Roughly, the function "computes pretty breakpoints" as a sequence of several "round" values. I'm not sure there is a Python equivalent and I'm not having much luck with Google.

Edit: More specifically, this is the Description entry in he help page for pretty:

Description: Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

I looked into R's pretty.default() to see what exactly R is doing with the function but it eventually uses .Internal() -- which usually leads to dark R magic. I thought I'd ask around before diving in.

Does anyone know if Python has something equivalent to R's pretty()?

答:
It's not that elegant as in R but you still can use numpy:

```<code>import numpy as np
np.linspace(a,b,n,dtype=int)
</code>```

where a is the beginning of the range, b is the end and n is the number of values, while the output type is int.

For example:

```<code>np.linspace(0,10,11,dtype=int)
</code>```

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Of course if you want it to be more elegant you can wrap it:

```<code>pretty = lambda x: np.linspace(0,x,11,dtype=int)
pretty(10)
</code>```

Body:
It's not that elegant as in R but you still can use numpy:

import numpy as np
np.linspace(a,b,n,dtype=int)

where a is the beginning of the range, b is the end and n is the number of values, while the output type is int.

For example:

np.linspace(0,10,11,dtype=int)

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Of course if you want it to be more elegant you can wrap it:

pretty = lambda x: np.linspace(0,x,11,dtype=int)
pretty(10)


问:
Sql query with datetime and BETWEEN clause
I have room slot available from '2017-06-13 00:00:00' to '2017-06-13 23:00:00'

I ran two queries:

1.

```<code>SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-12 22:00:00' AND  '2017-06-13 21:00:00'
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 02:00:00' AND  '2017-06-14 01:00:00'
</code>```

2.

```<code>SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00'
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'
</code>```

First query fetches the slot and second one is supposed to fetch the slot right? I am not getting why the second query is not fetching the result.

Edit: This is the record

答:
Because in the second query, your need the from to be in range:

```<code>BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00'
</code>```

and it's 2017-06-13 00:00:00, so its not in the range (the data is in hour 0 and you need it greater than 3), so it doesn't match
The same with the to, you need it

```<code>BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'
</code>```

and you have it at 23 ('2017-06-13 23:00:00')that it's not in the range. The data is 23 and the range it's from 07-12

So the second query is working right, it doesn have to fetch the data

Body:
I have room slot available from '2017-06-13 00:00:00' to '2017-06-13 23:00:00'

I ran two queries:

1.

SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-12 22:00:00' AND  '2017-06-13 21:00:00'
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 02:00:00' AND  '2017-06-14 01:00:00'

2.

SELECT * FROM hs_room_slots_tbl
WHERE hs_room_slots_tbl.from BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00'
   OR  hs_room_slots_tbl.to BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'

First query fetches the slot and second one is supposed to fetch the slot right? I am not getting why the second query is not fetching the result.

Edit: This is the record

Body:
Because in the second query, your need the from to be in range:

BETWEEN '2017-06-13 03:00:00' AND  '2017-06-13 08:00:00'

and it's 2017-06-13 00:00:00, so its not in the range (the data is in hour 0 and you need it greater than 3), so it doesn't match
The same with the to, you need it

BETWEEN '2017-06-13 07:00:00' AND  '2017-06-13 12:00:00'

and you have it at 23 ('2017-06-13 23:00:00')that it's not in the range. The data is 23 and the range it's from 07-12

So the second query is working right, it doesn have to fetch the data


问:
Remove carriage return and space from a string
I want to remove carriage return and space from a string
for exemple:

```<code>var t ="     \n \n    aaa \n bbb \n ccc \n";
</code>```

I want to have as result:

```<code>t = "aaa bbb ccc"
</code>```

I use this one, it removes carriage return but I still have spaces

```<code>t.replace(/[\n\r]/g, '');
</code>```

Please someone help me.

答:
I would suggest

to clear carriage return => space

to replace multiple spaces by a single one

to clear leading and trailing spaces (same as jQuery trim())

Thus

```<code>t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'')
</code>```

Body:
I want to remove carriage return and space from a string
for exemple:

var t ="     \n \n    aaa \n bbb \n ccc \n";

I want to have as result:

t = "aaa bbb ccc"

I use this one, it removes carriage return but I still have spaces

t.replace(/[\n\r]/g, '');

Please someone help me.

Body:
I would suggest

to clear carriage return => space

to replace multiple spaces by a single one

to clear leading and trailing spaces (same as jQuery trim())

Thus

t.replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/,'')


问:
How to properly read in text data
I am just getting started with text analysis in r. By reading in some example text data I get the following result.

```<code>sms_raw <- read.csv("sms_spam.csv", stringsAsFactors = FALSE)
> str(sms_raw)
'data.frame':   5559 obs. of  2 variables:
$ type         : chr  "ham" "ham" "ham" "spam,\"complimentary 4 STAR Ibiza
Holiday or Â£10,000 cash needs your URGENT collection. 09066364349 NOW from
Landline not to l"| __truncated__ ...
$ text.........: chr  "Hope you are having a good week. Just checking
in;;;;;;;;;" "K..give back my thanks.;;;;;;;;;" "Am also doing in cbe only.
But have to pay.;;;;;;;;;" "" ...
</code>```

It seems to me as if the variables are not getting seperated properly. Further analyzing the data with the head function I get the following result:

```<code>head(sms_raw)

type
1
ham
2
ham
3
ham
4 spam,"complimentary 4 STAR Ibiza Holiday or Â£10,000 cash needs your
URGENT collection. 09066364349 NOW from Landline not to lose out!
Box434SK38WP150PPM18+";;;;;;;;;
5
spam
6
ham

text.........
1
Hope you are having a good week. Just checking in;;;;;;;;;
2
K..give back my thanks.;;;;;;;;;
3
Am also doing in cbe only. But have to pay.;;;;;;;;;
</code>```

Does anybody have suggestions how to resolve this?

答:
Try data.table::fread("sms_spam.csv", stringsAsFactors = FALSE,sep=";")

EDIT

you can try:
input_file<-readLines("/path/of/sms_spam.csv")

Title: How to properly read in text data

Body:
I am just getting started with text analysis in r. By reading in some example text data I get the following result.

sms_raw <- read.csv("sms_spam.csv", stringsAsFactors = FALSE)
> str(sms_raw)
'data.frame':   5559 obs. of  2 variables:
$ type         : chr  "ham" "ham" "ham" "spam,\"complimentary 4 STAR Ibiza
Holiday or Â£10,000 cash needs your URGENT collection. 09066364349 NOW from
Landline not to l"| __truncated__ ...
$ text.........: chr  "Hope you are having a good week. Just checking
in;;;;;;;;;" "K..give back my thanks.;;;;;;;;;" "Am also doing in cbe only.
But have to pay.;;;;;;;;;" "" ...

It seems to me as if the variables are not getting seperated properly. Further analyzing the data with the head function I get the following result:

head(sms_raw)

type
1
ham
2
ham
3
ham
4 spam,"complimentary 4 STAR Ibiza Holiday or Â£10,000 cash needs your
URGENT collection. 09066364349 NOW from Landline not to lose out!
Box434SK38WP150PPM18+";;;;;;;;;
5
spam
6
ham

text.........
1
Hope you are having a good week. Just checking in;;;;;;;;;
2
K..give back my thanks.;;;;;;;;;
3
Am also doing in cbe only. But have to pay.;;;;;;;;;

Does anybody have suggestions how to resolve this?


问:
Second argument to std::vector
Looking at vector, I realized that I have never used the second argument when creating vectors.

```<code>std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?
</code>```

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

答:
The default allocator, std::allocator<>, will handle all allocations made by std::vector<> (and others). It will make new allocations from the heap each time a new allocation is needed.

By providing a custom allocator, you can for instance allocate a big chunk of memory up front and then slice it up and hand out smaller pieces when separate allocations are needed. This will increase the allocation speed dramatically, which is good for example in games, at the cost of increased complexity as compared to the default allocator.

Some std type implementations have internal stack-based storage for small amounts of data. For instance, std::basic_string<> might use what is called a small string optimization, where only strings longer than some fixed length, say 16 characters (just an example!), gets an allocation from the allocator, otherwise an internal array is used.

Title: Second argument to std::vector

Body:
Looking at vector, I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?