问:
Liferay CE: Is there any way to set access permissions to a single user to a single resource?
I'm trying to set user based permissions in Liferay CE 7, but the interface doesn't let me select access permissions to a single user, but rather to groups.

We would like that a document uploaded to the documents and media content could only be seen by a single user and the administrators, not the whole group.

Any tips on how to do that?

答:
Liferay permissions always go through a role our it's little sister, a team. Any individual user handled in permissions would just not scale.

It used to be implemented in ancient versions (pre 5.x I believe) but was removed for performance reasons looooong time ago


来源: stackexchange

问:
Trying to use urllib with headers but I keep on getting this error: TypeError: a float is required. I'm using python 3.4
I have been trying to send requests using custom headers but python keeps on giving this error message, what am I getting wrong?
Here is my code together with the full response from python:

Code

```<code>import urllib.request
import urllib.parse

url = 'https://nytimes.com/'

user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Kromanion Krank', 'location': 'Finland', 'language': 'Python'}
headers = {'User-Agent': user_agent}
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
html_str = urllib.request.urlopen(url, data, headers)
html_txt = html_str.text
print(html_txt)
</code>```

Output error

```<code>Traceback (most recent call last):
  File "C:/Users/fpt84/PycharmProjects/WebC/TEST.py", line 11, in <module>
    html_str = urllib.request.urlopen(url, data, headers)
  File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python34\lib\urllib\request.py", line 464, in open
    response = self._open(req, data)
  File "C:\Python34\lib\urllib\request.py", line 482, in _open
    '_open', req)
  File "C:\Python34\lib\urllib\request.py", line 442, in _call_chain
    result = func(*args)
  File "C:\Python34\lib\urllib\request.py", line 1226, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "C:\Python34\lib\urllib\request.py", line 1183, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "C:\Python34\lib\http\client.py", line 1137, in request
    self._send_request(method, url, body, headers)
  File "C:\Python34\lib\http\client.py", line 1182, in _send_request
    self.endheaders(body)
  File "C:\Python34\lib\http\client.py", line 1133, in endheaders
    self._send_output(message_body)
  File "C:\Python34\lib\http\client.py", line 963, in _send_output
    self.send(msg)
  File "C:\Python34\lib\http\client.py", line 898, in send
    self.connect()
  File "C:\Python34\lib\http\client.py", line 1279, in connect
    super().connect()
  File "C:\Python34\lib\http\client.py", line 871, in connect
    self.timeout, self.source_address)
  File "C:\Python34\lib\socket.py", line 504, in create_connection
    sock.settimeout(timeout)
TypeError: a float is required
</code>```

答:
The signature of urllib.request.urlopen (from https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) is:

```<code>urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
</code>```

Your third "headers" argument is getting passed into the timeout argument of urlopen

You'll need to use a Request object to do what you want:

```<code>req = urllib.request.Request(url, data, headers)
resp = urllib.request.urlopen(req)
</code>```

From your code example (I also had to modify the usage of the response)

```<code>import urllib.request
import urllib.parse

url = 'https://nytimes.com/'

user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Kromanion Krank', 'location': 'Finland', 'language': 'Python'}
headers = {'User-Agent': user_agent}
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
request = urllib.request.Request(url, data, headers)
resp = urllib.request.urlopen(request)
html_txt = resp.read().decode('UTF-8')
print(html_txt)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to send requests using custom headers but python keeps on giving this error message, what am I getting wrong?
Here is my code together with the full response from python:

Code

import urllib.request
import urllib.parse

url = 'https://nytimes.com/'

user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Kromanion Krank', 'location': 'Finland', 'language': 'Python'}
headers = {'User-Agent': user_agent}
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
html_str = urllib.request.urlopen(url, data, headers)
html_txt = html_str.text
print(html_txt)

Output error

Traceback (most recent call last):
  File "C:/Users/fpt84/PycharmProjects/WebC/TEST.py", line 11, in <module>
    html_str = urllib.request.urlopen(url, data, headers)
  File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python34\lib\urllib\request.py", line 464, in open
    response = self._open(req, data)
  File "C:\Python34\lib\urllib\request.py", line 482, in _open
    '_open', req)
  File "C:\Python34\lib\urllib\request.py", line 442, in _call_chain
    result = func(*args)
  File "C:\Python34\lib\urllib\request.py", line 1226, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "C:\Python34\lib\urllib\request.py", line 1183, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "C:\Python34\lib\http\client.py", line 1137, in request
    self._send_request(method, url, body, headers)
  File "C:\Python34\lib\http\client.py", line 1182, in _send_request
    self.endheaders(body)
  File "C:\Python34\lib\http\client.py", line 1133, in endheaders
    self._send_output(message_body)
  File "C:\Python34\lib\http\client.py", line 963, in _send_output
    self.send(msg)
  File "C:\Python34\lib\http\client.py", line 898, in send
    self.connect()
  File "C:\Python34\lib\http\client.py", line 1279, in connect
    super().connect()
  File "C:\Python34\lib\http\client.py", line 871, in connect
    self.timeout, self.source_address)
  File "C:\Python34\lib\socket.py", line 504, in create_connection
    sock.settimeout(timeout)
TypeError: a float is required

Body:
The signature of urllib.request.urlopen (from https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) is:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

Your third "headers" argument is getting passed into the timeout argument of urlopen

You'll need to use a Request object to do what you want:

req = urllib.request.Request(url, data, headers)
resp = urllib.request.urlopen(req)

From your code example (I also had to modify the usage of the response)

import urllib.request
import urllib.parse

url = 'https://nytimes.com/'

user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Kromanion Krank', 'location': 'Finland', 'language': 'Python'}
headers = {'User-Agent': user_agent}
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
request = urllib.request.Request(url, data, headers)
resp = urllib.request.urlopen(request)
html_txt = resp.read().decode('UTF-8')
print(html_txt)


问:
Always 10 bars on a bar graph even if data runs out at a number indivisible by 10?
I'm in a bit of a pickle.  I've made a bar graph with d3.js that loads 10 rows of data at a time, each time you click "next" it loads the next 10 rows, and so on.  However, the sets of data I'm working with don't always have a row count divisible by 10, so then I end up with a remainder 2 or 3 bars with odd widths, trying to make up for the missing values.  I want it to load the bars the same width every time, without moving their position, but I also want the x axis to be relative to the amount of data I put in there in case I ever want to change it to load more than 10.

Here's my current code.

```<code>var x = d3.scale.ordinal()
    .rangeRoundBands([5, 525], .6)
    .domain(charges);

var y = d3.scale.linear()
    .range([150, 0])
    .domain([0, d3.max(swappedData) + ((d3.max(swappedData) / 10) + 10)]);

var rect = g.selectAll('.bar').data(data.slice(a,b));
rect.enter().append('rect');
rect.exit().remove('rect');
rect.attr('class', 'bar')
    .transition().duration(250)
    .attr('width', x.rangeBand())
    .attr('height', function(d) { return 150 - y(d.QuantityCharged) + 2})
    .attr('x', function(d) { return x(d.unslicedCharge) })
    .attr('y', function(d) { return y(d.QuantityCharged) });
</code>```

答:
There are several different approaches to deal with this (so, this question is maybe too broad).

In this approach, I'm merging the current data array with an array made of placeholders:

```<code>var merged = d3.merge([data,
    d3.range(10 - data.length).map(function(d, i) {
        return {
            name: "bar" + i,
            value: 0
        };
    })
]);
</code>```

Here, the placeholders have a name property which start with bar and a zero value (since you didn't shared your data structure, I had to create a dummy one).

That merge function will simply complete the data array, until it's length is 10, with our placeholder objects. If the data has already 10 objects, no placeholder will be created. If the data has 4 objects, 6 placeholders will be created, and so on...

Then, it's just a matter of getting rid of the placeholders in the axis generator.

Here is a demo, there are 4 datasets, they are all drawn using the same function:

var data = [
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:30},{name: "foo4", value:10}],
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:40},{name: "foo4", value:90},{name: "foo5", value:10},{name: "foo6", value:70}],
  [{name: "foo", value:50}],
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:40},{name: "foo4", value:90},{name: "foo5", value:10},{name: "foo6", value:70},{name: "foo7", value:10},{name: "foo8", value:40},{name: "foo9", value:30},{name: "foo10", value:10}]
];

data.forEach(function(d) {
  draw(d);
});

function draw(data) {

  var svg = d3.select("body")
    .append("svg")
    .attr("width", 500)
    .attr("height", 100);

  var merged = d3.merge([data, d3.range(10 - data.length).map(function(d, i) {
    return {
      name: "bar" + i,
      value: 0
    };
  })]);

  var xScale = d3.scale.ordinal()
    .rangeRoundBands([20, 480], .6)
    .domain(merged.map(function(d) {
      return d.name
    }));

  var yScale = d3.scale.linear()
    .domain([0, 100])
    .range([80, 10]);

  var rects = svg.selectAll("foo")
    .data(merged)
    .enter()
    .append("rect")
    .attr("x", function(d) {
      return xScale(d.name)
    })
    .attr("y", function(d) {
      return yScale(d.value)
    })
    .attr("width", xScale.rangeBand())
    .attr("height", function(d) {
      return 80 - yScale(d.value)
    })
    .attr("fill", "teal");

  var xAxis = d3.svg.axis()
    .orient("bottom")
    .scale(xScale)
    .tickValues(xScale.domain().filter(function(d) {
      return d.substring(0, 3) != "bar"
    }));

  var gX = svg.append("g")
    .attr("transform", "translate(0,80)")
    .call(xAxis);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>line,
path {
  fill: none;
  stroke: black;
}</code>```

```

Body:
I'm in a bit of a pickle.  I've made a bar graph with d3.js that loads 10 rows of data at a time, each time you click "next" it loads the next 10 rows, and so on.  However, the sets of data I'm working with don't always have a row count divisible by 10, so then I end up with a remainder 2 or 3 bars with odd widths, trying to make up for the missing values.  I want it to load the bars the same width every time, without moving their position, but I also want the x axis to be relative to the amount of data I put in there in case I ever want to change it to load more than 10.

Here's my current code.

var x = d3.scale.ordinal()
    .rangeRoundBands([5, 525], .6)
    .domain(charges);

var y = d3.scale.linear()
    .range([150, 0])
    .domain([0, d3.max(swappedData) + ((d3.max(swappedData) / 10) + 10)]);

var rect = g.selectAll('.bar').data(data.slice(a,b));
rect.enter().append('rect');
rect.exit().remove('rect');
rect.attr('class', 'bar')
    .transition().duration(250)
    .attr('width', x.rangeBand())
    .attr('height', function(d) { return 150 - y(d.QuantityCharged) + 2})
    .attr('x', function(d) { return x(d.unslicedCharge) })
    .attr('y', function(d) { return y(d.QuantityCharged) });

Body:
There are several different approaches to deal with this (so, this question is maybe too broad).

In this approach, I'm merging the current data array with an array made of placeholders:

var merged = d3.merge([data,
    d3.range(10 - data.length).map(function(d, i) {
        return {
            name: "bar" + i,
            value: 0
        };
    })
]);

Here, the placeholders have a name property which start with bar and a zero value (since you didn't shared your data structure, I had to create a dummy one).

That merge function will simply complete the data array, until it's length is 10, with our placeholder objects. If the data has already 10 objects, no placeholder will be created. If the data has 4 objects, 6 placeholders will be created, and so on...

Then, it's just a matter of getting rid of the placeholders in the axis generator.

Here is a demo, there are 4 datasets, they are all drawn using the same function:

var data = [
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:30},{name: "foo4", value:10}],
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:40},{name: "foo4", value:90},{name: "foo5", value:10},{name: "foo6", value:70}],
  [{name: "foo", value:50}],
  [{name: "foo", value:10},{name: "foo2", value:40},{name: "foo3", value:40},{name: "foo4", value:90},{name: "foo5", value:10},{name: "foo6", value:70},{name: "foo7", value:10},{name: "foo8", value:40},{name: "foo9", value:30},{name: "foo10", value:10}]
];

data.forEach(function(d) {
  draw(d);
});

function draw(data) {

  var svg = d3.select("body")
    .append("svg")
    .attr("width", 500)
    .attr("height", 100);

  var merged = d3.merge([data, d3.range(10 - data.length).map(function(d, i) {
    return {
      name: "bar" + i,
      value: 0
    };
  })]);

  var xScale = d3.scale.ordinal()
    .rangeRoundBands([20, 480], .6)
    .domain(merged.map(function(d) {
      return d.name
    }));

  var yScale = d3.scale.linear()
    .domain([0, 100])
    .range([80, 10]);

  var rects = svg.selectAll("foo")
    .data(merged)
    .enter()
    .append("rect")
    .attr("x", function(d) {
      return xScale(d.name)
    })
    .attr("y", function(d) {
      return yScale(d.value)
    })
    .attr("width", xScale.rangeBand())
    .attr("height", function(d) {
      return 80 - yScale(d.value)
    })
    .attr("fill", "teal");

  var xAxis = d3.svg.axis()
    .orient("bottom")
    .scale(xScale)
    .tickValues(xScale.domain().filter(function(d) {
      return d.substring(0, 3) != "bar"
    }));

  var gX = svg.append("g")
    .attr("transform", "translate(0,80)")
    .call(xAxis);

}

line,
path {
  fill: none;
  stroke: black;
}

<script src="https://d3js.org/d3.v3.min.js"></script>


问:
Put values from arrays into input value separated by commas
I have multiple date arrays, I need to put these in input type hidden field value.

```<code>["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
["26/2/2017"]
</code>```

I want to make it like this:

```<code><input type="hidden" value="5/3/2017, 12/3/2017, 19/3/2017, 26/3/2017, 26/2/2017">
</code>```

I tried with merge, join() but I managed to get just one value to the input and I think its the last value. Any ideas ?

Here is part of the code where I try to do this:

```<code>        var dayAll = sundayData['date'];
        var monthAll = sundayData['month'];
        var yearAll = sundayData['year'];

        var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;

        var sundayDate = [];

        sundayDate.push(sundayDatesAll);

        $('input').val(sundayDate);
</code>```

I get the arrays from sundayDate

答:
Try this :

Note : Replace the code of portions according to your requirement

var dateArray = [];

var dayAll = "5,12,19,26,26";
var monthAll = "3,3,3,3,2";
var yearAll = "2017,2017,2017,2017,2017";

var dayArray = dayAll.split(",");
var monthArray = monthAll.split(",");
var yearArray = yearAll.split(",");

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

    var sundayDate = dayArray[i] + '/' + monthArray[i] + '/' + yearArray[i];
    dateArray.push(sundayDate);
}

var dateString = dateArray.join();
console.log(dateString);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have multiple date arrays, I need to put these in input type hidden field value.

["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
["26/2/2017"]

I want to make it like this:

<input type="hidden" value="5/3/2017, 12/3/2017, 19/3/2017, 26/3/2017, 26/2/2017">

I tried with merge, join() but I managed to get just one value to the input and I think its the last value. Any ideas ?

Here is part of the code where I try to do this:

        var dayAll = sundayData['date'];
        var monthAll = sundayData['month'];
        var yearAll = sundayData['year'];

        var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;

        var sundayDate = [];

        sundayDate.push(sundayDatesAll);

        $('input').val(sundayDate);

I get the arrays from sundayDate

Body:
Try this :

Note : Replace the code of portions according to your requirement

var dateArray = [];

var dayAll = "5,12,19,26,26";
var monthAll = "3,3,3,3,2";
var yearAll = "2017,2017,2017,2017,2017";

var dayArray = dayAll.split(",");
var monthArray = monthAll.split(",");
var yearArray = yearAll.split(",");

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

    var sundayDate = dayArray[i] + '/' + monthArray[i] + '/' + yearArray[i];
    dateArray.push(sundayDate);
}

var dateString = dateArray.join();
console.log(dateString);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Best way to share ActiveRecord models and data between different Rails Apps?
I have several rails applications that will use the same core set of Models and data, for example:

Apps

Developers

Categories

Each app builds on top of this core data and uses it in different ways. For example, I might have something like this in another app:

Activity

Users

Apps (shared)

Developers (shared)

Categories (shared)

What is the best way to share the Models and data between them? The Apps, Developers and Category data will all be the same for every app so I would rather not have to duplicate the data in every app's database.

EDIT: I'm thinking through a couple of possible solutions:

Rails engines (would solve the duplicate Models in different apps problem, but not the shared data issue)

Using ActiveResource to access the core data (solves the shared data, but not the shared model issue)

答: I'm using a shared database to solve the shared data problem between heroku and a server on EC2 which does some background processing I can't do on heroku.  In my case I'm using the same application, but really all I'm doing is using delayed_job on the EC2, so I'm only using the models from the app there.  If I were going to use them in another application, I would probably go through the trouble of creating a gem to use between them.</p>

ContentLicense: CC BY-SA 2.5


问:
Query with parameter returns different resultsets
I have the following query returning different resultsets each time it runs. Sometimes the second query returns data and sometimes it doesn't.

```<code>DECLARE @MinSentDateKey DATE =
(
SELECT
    MIN([SentDateKey])
FROM
    [dbo].[factEmail] [e]
WHERE
    [DeliveredStatus] = 0
)

SELECT
    [e].[EmailId],
    [e].[SentDateKey]
FROM
    #Email e
WHERE EXISTS
(
    SELECT 1
    FROM
        [dbo].[factEmail] [o]
    WHERE
        [o].[MessageKey] = [e].[MessageKey]
    AND
        [o].[EmailKey] = [e].[EmailKey]
    AND
        [o].[SentDateKey] >= @MinSentDateKey
)
</code>```

I've isolated the issue to the following line

```<code>[o].[SentDateKey] >= @MinSentDateKey
</code>```

as replacing the variable with the actual hard-coded value always returns the correct resultset. [o].[SentDateKey] is a DATE datetype and @MinSentDateKey never changes it's value. I've also noticed that this always returns the correct resultset:

```<code> [o].[SentDateKey] >= DATEADD(DAY,0, @MinSentDateKey)
</code>```

I have a feeling that this is caused by parameter sniffing and so far have tried  OPTION (RECOMPILE) with no luck.

EDIT: The data in  [dbo].[factEmail] and #Email is static and it does not change at any point.

答:
Instead of separate selects, why not combine them?

```<code>SELECT
    [e].[EmailId],
    [e].[SentDateKey]
FROM
    #Email e
WHERE EXISTS
(
    SELECT 1
    FROM
        [dbo].[factEmail] [o]
    WHERE
        [o].[MessageKey] = [e].[MessageKey]
    AND
        [o].[EmailKey] = [e].[EmailKey]
    AND
        [o].[SentDateKey] >=
        (
        SELECT
            MIN([SentDateKey])
        FROM
            [dbo].[factEmail]
        WHERE
            [DeliveredStatus] = 0
        )
)
</code>```

This assumes that the MIN([SentDateKey]) it is selecting has the right value.

The other thing to do is not type @MinSentDateKey as a DATE but as a DateTime or maybe as a Date2 - whatever the table column actually is.

Body:
I have the following query returning different resultsets each time it runs. Sometimes the second query returns data and sometimes it doesn't.

DECLARE @MinSentDateKey DATE =
(
SELECT
    MIN([SentDateKey])
FROM
    [dbo].[factEmail] [e]
WHERE
    [DeliveredStatus] = 0
)

SELECT
    [e].[EmailId],
    [e].[SentDateKey]
FROM
    #Email e
WHERE EXISTS
(
    SELECT 1
    FROM
        [dbo].[factEmail] [o]
    WHERE
        [o].[MessageKey] = [e].[MessageKey]
    AND
        [o].[EmailKey] = [e].[EmailKey]
    AND
        [o].[SentDateKey] >= @MinSentDateKey
)

I've isolated the issue to the following line

[o].[SentDateKey] >= @MinSentDateKey

as replacing the variable with the actual hard-coded value always returns the correct resultset. [o].[SentDateKey] is a DATE datetype and @MinSentDateKey never changes it's value. I've also noticed that this always returns the correct resultset:

 [o].[SentDateKey] >= DATEADD(DAY,0, @MinSentDateKey)

I have a feeling that this is caused by parameter sniffing and so far have tried  OPTION (RECOMPILE) with no luck.

EDIT: The data in  [dbo].[factEmail] and #Email is static and it does not change at any point.

Body:
Instead of separate selects, why not combine them?

SELECT
    [e].[EmailId],
    [e].[SentDateKey]
FROM
    #Email e
WHERE EXISTS
(
    SELECT 1
    FROM
        [dbo].[factEmail] [o]
    WHERE
        [o].[MessageKey] = [e].[MessageKey]
    AND
        [o].[EmailKey] = [e].[EmailKey]
    AND
        [o].[SentDateKey] >=
        (
        SELECT
            MIN([SentDateKey])
        FROM
            [dbo].[factEmail]
        WHERE
            [DeliveredStatus] = 0
        )
)

This assumes that the MIN([SentDateKey]) it is selecting has the right value.

The other thing to do is not type @MinSentDateKey as a DATE but as a DateTime or maybe as a Date2 - whatever the table column actually is.


问:
Resolved versions for app (22.0.0) and test app (21.0.3) differ
After upgrading to API 22 and support lib revision 22 I'm getting the following warning:

Warning:Conflict with dependency
  'com.android.support:support-annotations'. Resolved versions for app
  (22.0.0) and test app (21.0.3) differ.

Gradle itself is more forgiving, but Android Studio, not so much.

I have no dependencies declared with 21.0.3 ... is one of the dependent libraries using 21.0.3 and Google forgot to update it with the rest of the batch?

My build.gradle with the extras cut out

```<code>android {
  compileSdkVersion 22
  buildToolsVersion '22'

  defaultConfig {
    applicationId "com.REDACTED.android"
    minSdkVersion 14
    targetSdkVersion 22
    renderscriptSupportModeEnabled true
    versionName '1.0.0'
    versionCode 100
  }

  buildTypes {
    release {
      minifyEnabled true
      zipAlignEnabled true
      signingConfig signingConfigs.release
    }

    debug {
      minifyEnabled false
      zipAlignEnabled true
      signingConfig signingConfigs.debug
    }
  }

  dependencies {
    provided 'org.projectlombok:lombok:1.16.2'
    googleCompile 'com.google.android.gms:play-services-base:6.5.87'
    compile 'com.android.support:support-v4:22.0.0'
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support:support-v13:22.0.0'
    compile 'com.android.support:cardview-v7:22.0.0'
    compile 'com.android.support:palette-v7:22.0.0'
    compile 'com.android.support:support-annotations:22.0.0'
    compile 'com.github.chrisbanes.photoview:library:1.2.3'
    compile 'org.apache.commons:commons-lang3:3.3.2'
    compile 'commons-io:commons-io:2.4'
    compile 'commons-codec:commons-codec:1.10'
    compile 'com.jakewharton:butterknife:6.1.0'
    compile 'com.jakewharton:disklrucache:2.0.2'
    compile 'com.squareup:otto:1.3.6'
    compile 'com.squareup.picasso:picasso:2.5.0'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.2.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    compile 'com.squareup.okio:okio:1.2.0'
    compile 'com.flaviofaria:kenburnsview:1.0.6'
    compile 'com.edmodo:cropper:1.0.1'
    compile 'com.getbase:floatingactionbutton:1.8.0'
    compile 'com.nispok:snackbar:2.10.2'
    compile 'com.github.ksoichiro:android-observablescrollview:1.5.0'
    compile 'in.srain.cube:grid-view-with-header-footer:1.0.9'
    compile 'de.hdodenhof:circleimageview:1.2.2'
    compile fileTree(dir: 'libs', include: '*.jar')
    // Test Only Dependencies
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.0'
  }
</code>```

Update: (Thanks Mark)

Looks like it's espresso-contrib

```<code>+--- com.android.support.test:testing-support-lib:0.1 (*)
\--- com.android.support.test.espresso:espresso-contrib:2.0
     +--- com.android.support:recyclerview-v7:21.0.3
     |    +--- com.android.support:support-annotations:21.0.3
     |    \--- com.android.support:support-v4:21.0.3
     |         \--- com.android.support:support-annotations:21.0.3
     +--- com.android.support:support-v4:21.0.3 (*)
     \--- com.android.support.test.espresso:espresso-core:2.0 (*)
</code>```

答:
This is common issue in instrumentation test as stated here and can be resolved simply by adding the dependencies for androidTestCompile inside the build.gradle. In my case conflict arised in appcompat, recyclerview and design dependencies. And resolved by adding following lines</p>

```<code>    androidTestCompile 'com.android.support:appcompat-v7:23.4.0'
    androidTestCompile 'com.android.support:recyclerview-v7:23.4.0'
    androidTestCompile 'com.android.support:design:23.4.0'
</code>```

Body:
After upgrading to API 22 and support lib revision 22 I'm getting the following warning:

Warning:Conflict with dependency
  'com.android.support:support-annotations'. Resolved versions for app
  (22.0.0) and test app (21.0.3) differ.

Gradle itself is more forgiving, but Android Studio, not so much.

I have no dependencies declared with 21.0.3 ... is one of the dependent libraries using 21.0.3 and Google forgot to update it with the rest of the batch?

My build.gradle with the extras cut out

android {
  compileSdkVersion 22
  buildToolsVersion '22'

  defaultConfig {
    applicationId "com.REDACTED.android"
    minSdkVersion 14
    targetSdkVersion 22
    renderscriptSupportModeEnabled true
    versionName '1.0.0'
    versionCode 100
  }

  buildTypes {
    release {
      minifyEnabled true
      zipAlignEnabled true
      signingConfig signingConfigs.release
    }

    debug {
      minifyEnabled false
      zipAlignEnabled true
      signingConfig signingConfigs.debug
    }
  }

  dependencies {
    provided 'org.projectlombok:lombok:1.16.2'
    googleCompile 'com.google.android.gms:play-services-base:6.5.87'
    compile 'com.android.support:support-v4:22.0.0'
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support:support-v13:22.0.0'
    compile 'com.android.support:cardview-v7:22.0.0'
    compile 'com.android.support:palette-v7:22.0.0'
    compile 'com.android.support:support-annotations:22.0.0'
    compile 'com.github.chrisbanes.photoview:library:1.2.3'
    compile 'org.apache.commons:commons-lang3:3.3.2'
    compile 'commons-io:commons-io:2.4'
    compile 'commons-codec:commons-codec:1.10'
    compile 'com.jakewharton:butterknife:6.1.0'
    compile 'com.jakewharton:disklrucache:2.0.2'
    compile 'com.squareup:otto:1.3.6'
    compile 'com.squareup.picasso:picasso:2.5.0'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.2.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    compile 'com.squareup.okio:okio:1.2.0'
    compile 'com.flaviofaria:kenburnsview:1.0.6'
    compile 'com.edmodo:cropper:1.0.1'
    compile 'com.getbase:floatingactionbutton:1.8.0'
    compile 'com.nispok:snackbar:2.10.2'
    compile 'com.github.ksoichiro:android-observablescrollview:1.5.0'
    compile 'in.srain.cube:grid-view-with-header-footer:1.0.9'
    compile 'de.hdodenhof:circleimageview:1.2.2'
    compile fileTree(dir: 'libs', include: '*.jar')
    // Test Only Dependencies
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.0'
  }

Update: (Thanks Mark)

Looks like it's espresso-contrib

+--- com.android.support.test:testing-support-lib:0.1 (*)
\--- com.android.support.test.espresso:espresso-contrib:2.0
     +--- com.android.support:recyclerview-v7:21.0.3
     |    +--- com.android.support:support-annotations:21.0.3
     |    \--- com.android.support:support-v4:21.0.3
     |         \--- com.android.support:support-annotations:21.0.3
     +--- com.android.support:support-v4:21.0.3 (*)
     \--- com.android.support.test.espresso:espresso-core:2.0 (*)

Body:
This is common issue in instrumentation test as stated here and can be resolved simply by adding the dependencies for androidTestCompile inside the build.gradle. In my case conflict arised in appcompat, recyclerview and design dependencies. And resolved by adding following lines

    androidTestCompile 'com.android.support:appcompat-v7:23.4.0'
    androidTestCompile 'com.android.support:recyclerview-v7:23.4.0'
    androidTestCompile 'com.android.support:design:23.4.0'


问:
cloudinary javascript image uploads a blank file
i am using javascript to upload an image using the unsigned mode. the resultant image is a blank image or i can say an image filled with black color. not sure what is wrong. the code looks like follow:

```<code>var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");

xhttp.onreadystatechange = function() { //Call a function when the state changes.
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    alert(xhttp.responseText);
  } else {
    alert("Error dude: " + xhttp.statusText);
  }
}

var parameters = {
  "file": imgData,
  "upload_preset": "mycode"
};

xhttp.send(JSON.stringify(parameters));
</code>```

resultant image is:

```<code>http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg
</code>```

Please note that imgData is  base64 encoded

答:
You need to use FormData for uploading the file:

```<code>const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';

// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');

// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
  var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  var xhr = new XMLHttpRequest();
  var fd = new FormData();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

  xhr.onreadystatechange = function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // File uploaded successfully
      var response = JSON.parse(xhr.responseText);
      // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
      var url = response.secure_url;
      // Create a thumbnail of the uploaded image, with 150px width
      var tokens = url.split('/');
      tokens.splice(-2, 0, 'w_150,c_scale');
      var img = new Image(); // HTML5 Constructor
      img.src = tokens.join('/');
      img.alt = response.public_id;
      document.body.appendChild(img);
    }
  };

  fd.append('upload_preset', unsignedUploadPreset);
  fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
  fd.append('file', file);
  xhr.send(fd);
}
</code>```

See full example here. It will upload a small Michael Jordan jumpman image to your account.

Body:
i am using javascript to upload an image using the unsigned mode. the resultant image is a blank image or i can say an image filled with black color. not sure what is wrong. the code looks like follow:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");

xhttp.onreadystatechange = function() { //Call a function when the state changes.
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    alert(xhttp.responseText);
  } else {
    alert("Error dude: " + xhttp.statusText);
  }
}

var parameters = {
  "file": imgData,
  "upload_preset": "mycode"
};

xhttp.send(JSON.stringify(parameters));

resultant image is:

http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg

Please note that imgData is  base64 encoded

Body:
You need to use FormData for uploading the file:

const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';

// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');

// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
  var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
  var xhr = new XMLHttpRequest();
  var fd = new FormData();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

  xhr.onreadystatechange = function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // File uploaded successfully
      var response = JSON.parse(xhr.responseText);
      // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
      var url = response.secure_url;
      // Create a thumbnail of the uploaded image, with 150px width
      var tokens = url.split('/');
      tokens.splice(-2, 0, 'w_150,c_scale');
      var img = new Image(); // HTML5 Constructor
      img.src = tokens.join('/');
      img.alt = response.public_id;
      document.body.appendChild(img);
    }
  };

  fd.append('upload_preset', unsignedUploadPreset);
  fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
  fd.append('file', file);
  xhr.send(fd);
}

See full example here. It will upload a small Michael Jordan jumpman image to your account.


问:
Redux-orm not calling mapStateToProps after adding data
I am playing around with redux-orm and after adding an entity my selector is not updating with the new objects in mapStateToProps, hence resulting in render() not being called again. I've been through the tutorials but cannot see what I am doing wrong:

Another component is calling the BookReducer, so I know 100% the reducer is being called.

Here is my reducer:

```<code>export default function BookReducer(state = initialState, action) {

    const session = orm.session(state);

    switch (action.type) {

        case 'newBook':

            session.Book.create({ id: 0, type: 'novel' });

            //I can see verify that the object has been added  to the ORM
            console.log(session.Book.all().toRefArray())
     }

     return session.state;
}
</code>```

Here is my selector:

```<code>import orm from './orm';

const BookSelector = createSelector(orm, state => state.orm, session => {
    return session.Book.all().toRefArray()
});
</code>```

Here is my component:

```<code>class Main extends React.Component {

  constructor(props) {
      super(props);
  }

  render() {

    console.log("debug")
    console.log(this.props.books)

    return (
       <div>
           {this.props.books}
       </div>
    )

    function mapStateToProps(state) {

       return {
          isOpen: true,
          books: BookSelector(state)
       };
    }
}
</code>```

答:
You don't seem to have connected the Main compnent with mapStateToProps . USe connect like export default connect(mapStateToProps)(Main); and define it outside the Main component

```<code>import connect from 'react-redux';

class Main extends React.Component {

  constructor(props) {
      super(props);
  }

  render() {

    console.log("debug")
    console.log(this.props.books)

    return (
       <div>
           {this.props.books}
       </div>
    )

}

  function mapStateToProps(state) {

       return {
          isOpen: true,
          books: BookSelector(state)
       };
    }
export default connect(mapStateToProps)(Main);
</code>```

Also you need to export and import the BookSelector

```<code>import orm from './orm';

const BookSelector = createSelector(orm, state => state.orm, session => {
    return session.Book.all().toRefArray()
});
export default BookSelector;
</code>```

Body:
I am playing around with redux-orm and after adding an entity my selector is not updating with the new objects in mapStateToProps, hence resulting in render() not being called again. I've been through the tutorials but cannot see what I am doing wrong:

Another component is calling the BookReducer, so I know 100% the reducer is being called.

Here is my reducer:

export default function BookReducer(state = initialState, action) {

    const session = orm.session(state);

    switch (action.type) {

        case 'newBook':

            session.Book.create({ id: 0, type: 'novel' });

            //I can see verify that the object has been added  to the ORM
            console.log(session.Book.all().toRefArray())
     }

     return session.state;
}

Here is my selector:

import orm from './orm';

const BookSelector = createSelector(orm, state => state.orm, session => {
    return session.Book.all().toRefArray()
});

Here is my component:

class Main extends React.Component {

  constructor(props) {
      super(props);
  }

  render() {

    console.log("debug")
    console.log(this.props.books)

    return (

           {this.props.books}

    )

    function mapStateToProps(state) {

       return {
          isOpen: true,
          books: BookSelector(state)
       };
    }
}

Body:
You don't seem to have connected the Main compnent with mapStateToProps . USe connect like export default connect(mapStateToProps)(Main); and define it outside the Main component

import connect from 'react-redux';

class Main extends React.Component {

  constructor(props) {
      super(props);
  }

  render() {

    console.log("debug")
    console.log(this.props.books)

    return (
       <div>
           {this.props.books}
       </div>
    )

}

  function mapStateToProps(state) {

       return {
          isOpen: true,
          books: BookSelector(state)
       };
    }
export default connect(mapStateToProps)(Main);

Also you need to export and import the BookSelector

import orm from './orm';

const BookSelector = createSelector(orm, state => state.orm, session => {
    return session.Book.all().toRefArray()
});
export default BookSelector;


问:
What's the difference between passing by reference vs. passing by value?
What is the difference between

a parameter passed by reference

a parameter passed by value?

Could you give me some examples, please?

答:
First and foremost, the "pass by value vs. pass by reference" distinction as defined in the CS theory is now obsolete because the technique originally defined as "pass by reference" has since fallen out of favor and is seldom used now.1

Newer languages2 tend to use a different (but similar) pair of techniques to achieve the same effects (see below) which is the primary source of confusion.

A secondary source of confusion is the fact that in "pass by reference", "reference" has a narrower meaning than the general term "reference" (because the phrase predates it).

Now, the authentic definition is:

When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.

When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.

Things to note in this definition are:

"Variable" here means the caller's (local or global) variable itself -- i.e. if I pass a local variable by reference and assign to it, I'll change the caller's variable itself, not e.g. whatever it is pointing to if it's a pointer.

This is now considered bad practice (as an implicit dependency). As such, virtually all newer languages are exclusively, or almost exclusively pass-by-value. Pass-by-reference is now chiefly used in the form of "output/inout arguments" in languages where a function cannot return more than one value.

The meaning of "reference" in "pass by reference". The difference with the general "reference" term is that this "reference" is temporary and implicit. What the callee gets is a "variable" that is somehow "the same" as the original one. How specifically this effect is achieved is irrelevant (e.g. the language may also expose some implementation details -- addresses, pointers, dereferencing -- this is all irrelevant; if the net effect is this, it's pass-by-reference).

Now, in modern languages, variables tend to be of "reference types" (another concept invented later than "pass by reference" and inspired by it), i.e. the actual object data is stored separately somewhere (usually, on the heap), and only "references" to it are ever held in variables and passed as parameters.3

Passing such a reference falls under pass-by-value because a variable's value is technically the reference itself, not the referred object. However, the net effect on the program can be the same as either pass-by-value or pass-by-reference:

If a reference is just taken from a caller's variable and passed as an argument, this has the same effect as pass-by-reference: if the referred object is mutated in the callee, the caller will see the change.

However, if a variable holding this reference is reassigned, it will stop pointing to that object, so any further operations on this variable will instead affect whatever it is pointing to now.

To have the same effect as pass-by-value, a copy of the object is made at some point. Options include:

The caller can just make a private copy before the call and give the callee a reference to that instead.

In some languages, some object types are "immutable": any operation on them that seems to alter the value creates a completely new object without affecting the original one. So, passing an object of such a type as an argument always has the effect of pass-by-value: a copy for the callee will be made automatically if and when it needs a change, and the caller's object will never be affected.

In functional languages, all objects are immutable.

As you may see, this pair of techniques is almost the same as those in the definition, only with a level of indirection: just replace "variable" with "referenced object".

There's no agreed-upon name for them, which leads to contorted explanations like "call by value where the value is a reference". In 1975, Barbara Liskov suggested the term "call-by-object-sharing" (or sometimes just "call-by-sharing") though it never quite caught on. Moreover, neither of these phrases draws a parallel with the original pair. No wonder the old terms ended up being reused in the absence of anything better, leading to confusion.4

(I would use the terms "new" or "indirect" pass-by-value/pass-by-reference for the new techniques.)

NOTE: For a long time, this answer used to say:

Say I want to share a web page with you. If I tell you the URL, I'm
passing by reference. You can use that URL to see the same web page I
can see. If that page is changed, we both see the changes. If you
delete the URL, all you're doing is destroying your reference to that
page - you're not deleting the actual page itself.

If I print out the page and give you the printout, I'm passing by
value. Your page is a disconnected copy of the original. You won't see
any subsequent changes, and any changes that you make (e.g. scribbling
on your printout) will not show up on the original page. If you
destroy the printout, you have destroyed your copy of the
object - but the original web page remains intact.

This is mostly correct except the narrower meaning of "reference" -- it being both temporary and implicit (it doesn't have to, but being explicit and/or persistent are additional features, not a part of the pass-by-reference semantic, as explained above). A closer analogy would be giving you a copy of a document vs inviting you to work on the original.

1Unless you are programming in Fortran or Visual Basic, it's not the default behavior, and in most languages in modern use, true call-by-reference is not even possible.

2A fair amount of older ones support it, too

3In several modern languages, all types are reference types. This approach was pioneered by the language CLU in 1975 and has since been adopted by many other languages, including Python and Ruby. And many more languages use a hybrid approach, where some types are "value types" and others are "reference types" -- among them are C#, Java, and JavaScript.

4There's nothing bad with recycling a fitting old term per se, but one has to somehow make it clear which meaning is used each time. Not doing that is exactly what keeps confusing.

OwnerDisplayName: ritu

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Dylan Beattie

ContentLicense: CC BY-SA 4.0


问:
A bug because of the accuracy of double type in C++
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

```<code>class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}
</code>```

But when I test my code,it happened that:

```<code>a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen
</code>```

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?

答:
I would recommend this read:
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

For a more in depth treatment of the subject, I recommend:
"What Every Computer Scientist Should Know About Floating-Point Arithmetic"

Body:
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}

But when I test my code,it happened that:

a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?


问:
How to remove common objects from two lists with linq

Both lists have Objects with ID and Name properties.

List1({1, apple}, {2, orange}, {3, banana}, {4, potato}, {5, tomato})

List2({1, apple}, {2, orange}, {3, banana})

Final output List3({4, potato}, {5, tomato})

答:
You're looking for a symmetric difference

```<code>Dictionary<int, string> fruit = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" }, { 4, "potato" }, { 5, "tomato" } };
Dictionary<int, string> fruit2 = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" } };
var result = fruit.Values.Concat(fruit2.Values).Except(fruit.Values.Intersect(fruit2.Values));
</code>```

I'm not sure if it makes sense to to keep up the ID
because there could also be the case

List1({1, apple} and List2({1, potato}

Body:
You're looking for a symmetric difference

Dictionary<int, string> fruit = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" }, { 4, "potato" }, { 5, "tomato" } };
Dictionary<int, string> fruit2 = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" } };
var result = fruit.Values.Concat(fruit2.Values).Except(fruit.Values.Intersect(fruit2.Values));

I'm not sure if it makes sense to to keep up the ID
because there could also be the case

List1({1, apple} and List2({1, potato}


问:
How can I define global constants in NuSMV?
I don't know how to declare global constants in NuSMV, in a way that is similar to

```<code>#define n 5
</code>```

in C.

How can I do that in NuSMV?

答:
According to paragraph 2.3.2 (page 27) of NuSMV 2.6 Manual:

In order to make descriptions more concise, a symbol can be associated with a common expression, and a DEFINE declaration introduces such a symbol. The syntax for this kind of declaration is:

```<code>define_declaration :: DEFINE define_body

define_body :: identifier := simple_expr ;
             | define_body identifier := simple_expr ;
</code>```

DEFINE associates an identifier on the left hand side of the := with an expression on the right side. A define statement can be considered as a macro. Whenever a define identifier occurs in an expression, the identifier is syntactically replaced by the expression it is associated with. The associated expression is always evaluated in the context of
  the statement where the identifier is declared (see Section 2.3.16 [Context], page 36 for an explanation of contexts). Forward references to defined symbols are allowed but circular definitions are not, and result in an error. The difference between defined symbols and variables is that
  while variables are statically typed, definitions are not.

Therefore, this should work:

```<code>DEFINE n := 5 ;
</code>```

You can only put this definition within one module, because
it must belong to some context.

However, you can "simulate" a global scope by having one special module acting as a container for all global definitions. e.g.:

```<code>MODULE global
DEFINE
  n := 5;

MODULE pippo(global)
VAR
  pluto : {0, 1, 2, 3, 4, 5};
ASSIGN
  init(pluto) := global.n;

MODULE main()
VAR
  global : global();
  pippo  : pippo(global);
</code>```

You can test the example like this:

```<code>~$ NuSMV -int
NuSMV > reset; read_model -i example.smv; go; pick_state -i -v

***************  AVAILABLE STATES  *************

================= State =================
0) -------------------------
  global.n = 5
  pippo.pluto = 5
</code>```

Body:
I don't know how to declare global constants in NuSMV, in a way that is similar to

#define n 5

in C.

How can I do that in NuSMV?

Body:
According to paragraph 2.3.2 (page 27) of NuSMV 2.6 Manual:

In order to make descriptions more concise, a symbol can be associated with a common expression, and a DEFINE declaration introduces such a symbol. The syntax for this kind of declaration is:

define_declaration :: DEFINE define_body

define_body :: identifier := simple_expr ;
             | define_body identifier := simple_expr ;

DEFINE associates an identifier on the left hand side of the := with an expression on the right side. A define statement can be considered as a macro. Whenever a define identifier occurs in an expression, the identifier is syntactically replaced by the expression it is associated with. The associated expression is always evaluated in the context of
  the statement where the identifier is declared (see Section 2.3.16 [Context], page 36 for an explanation of contexts). Forward references to defined symbols are allowed but circular definitions are not, and result in an error. The difference between defined symbols and variables is that
  while variables are statically typed, definitions are not.

Therefore, this should work:

DEFINE n := 5 ;

You can only put this definition within one module, because
it must belong to some context.

However, you can "simulate" a global scope by having one special module acting as a container for all global definitions. e.g.:

MODULE global
DEFINE
  n := 5;

MODULE pippo(global)
VAR
  pluto : {0, 1, 2, 3, 4, 5};
ASSIGN
  init(pluto) := global.n;

MODULE main()
VAR
  global : global();
  pippo  : pippo(global);

You can test the example like this:

~$ NuSMV -int
NuSMV > reset; read_model -i example.smv; go; pick_state -i -v

***************  AVAILABLE STATES  *************

================= State =================
0) -------------------------
  global.n = 5
  pippo.pluto = 5


问:
Tweets classification
I'm trying to get into machine learning and so I wanted to try out text classification on tweets. I collected a small sample of tweets, but for me to perform any supervised learning I need to hand label some of the tweets I collected. This is an arduous task when I scale up my data.

Is there any way to perform classification without me hand labeling a large number of tweets?
Or are unsupervised learning better for this task?

答:
Tweets are short text. You should try a classifier tailored for short-text classification such as LibShortText: https://www.csie.ntu.edu.tw/~cjlin/libshorttext/

This article explains certain properties of short text (title) vs full-text classification : https://www.csie.ntu.edu.tw/~cjlin/papers/title.pdf

Classification will always involved labeled data (active learning techniques help with labeling datasets) but you can take advantage of new emerging techniques such as Snorkel (data programming) to alleviate some of the issues: https://github.com/HazyResearch/snorkel

Title: Tweets classification


问:
Unsupported Oracle data type 101 encountered
```<code>OracleDataAdapter oAdp = new OracleDataAdapter("select * from " + TABLE_NAME, SourceConnStr);
oAdp.Fill(dtTable);
</code>```

On execution of this code I get the error:

```<code>Unsupported Oracle data type 101 encountered.
</code>```

So I searched about the same and turns out .NET currently doesn't support or identify binary float/double and one of the columns in the table it is referring to; is of the datatype binary double. Please suggest a way to identify if a column of the table is of the datatype binary float/double and cast it to a different datatype like number or varchar which ever is appropriate.

```<code>Name           Null     Type
-------------- -------- -------------
EMPID          NOT NULL VARCHAR2(20)
EMPNAME        NOT NULL VARCHAR2(50)
EMPTYPE        NOT NULL NUMBER(38)
EMPPHOTO                BINARY_DOUBLE
DATEOFJOINING           DATE
CONTACTNO               VARCHAR2(20)
</code>```

答: Which OracleDataAdapter you use ? I guess it's from System.Data.OracleClient.OracleDataAdapter , if you are working with Oracle DB, use ODAC ,  Oracle.DataAccess.Client.OracleDataAdapter, it works fine with oracle datatypes.

Body:
OracleDataAdapter oAdp = new OracleDataAdapter("select * from " + TABLE_NAME, SourceConnStr);
oAdp.Fill(dtTable);

On execution of this code I get the error:

Unsupported Oracle data type 101 encountered.

So I searched about the same and turns out .NET currently doesn't support or identify binary float/double and one of the columns in the table it is referring to; is of the datatype binary double. Please suggest a way to identify if a column of the table is of the datatype binary float/double and cast it to a different datatype like number or varchar which ever is appropriate.

Name           Null     Type
-------------- -------- -------------
EMPID          NOT NULL VARCHAR2(20)
EMPNAME        NOT NULL VARCHAR2(50)
EMPTYPE        NOT NULL NUMBER(38)
EMPPHOTO                BINARY_DOUBLE
DATEOFJOINING           DATE
CONTACTNO               VARCHAR2(20)


问:
How to understand browser location is block or allowd?
Both of Google Chrome and Fire Fox has setting for permission,

Google Chrome has security connection setting. you can see this setting when press the (i) button at the beginning of the address bar ( for https websites click on green lock at the beginning of the address bar ), then you can see location , camera and etc.

Fire Fox has security connection setting too. you must press Alt+T+i , press permission tab and see Access your Location , Load Images and etc.

Now my question: how I can understand browser location is block or allow with JavaScript or jQuery ?

答:
When getting the location, you provide an error callback.  If getting the location is successful you will have it, if they decline then you will not.  I do not believe there is a way to know advance.

```<code>navigator.geolocation.getCurrentPosition(success, error);
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

Body:
When getting the location, you provide an error callback.  If getting the location is successful you will have it, if they decline then you will not.  I do not believe there is a way to know advance.

navigator.geolocation.getCurrentPosition(success, error);

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation


问:
WSO2IS - XACML Policy with custom attributes is returning "Couldn't find AttributeDesignator"
I've created the following policy in the WSO2IS:

<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="check-blacklist-users-in-login" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable" Version="1.0">
<Target>
    <AnyOf>
        <AllOf>
            <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">login</AttributeValue>
                <AttributeDesignator AttributeId="urn:custom:company:1.0:operation:login-id"
                                     Category="urn:custom:company:1.0:attribute-category:operation"
                                     DataType="http://www.w3.org/2001/XMLSchema#string"
                                     MustBePresent="true"/>
            </Match>
        </AllOf>
    </AnyOf>
</Target>
<Rule Effect="Permit" RuleId="permit-blacklisted-users-with-step-up">
    <Target>
        <AnyOf>
            <AllOf>
                <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vip</AttributeValue>
                    <AttributeDesignator AttributeId="urn:custom:company:1.0:user-group:vip-id"
                                         Category="urn:custom:company:1.0:attribute-category:user-group"
                                         DataType="http://www.w3.org/2001/XMLSchema#string"
                                         MustBePresent="true"/>
                </Match>
            </AllOf>
        </AnyOf>
    </Target>
    <Condition>
        <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                <AttributeDesignator AttributeId="urn:custom:company:1.0:is-user-in-blacklist:is-user-in-blacklist-id"
                                     Category="urn:custom:company:1.0:attribute-category:is-user-in-blacklist"
                                     DataType="http://www.w3.org/2001/XMLSchema#string"
                                     MustBePresent="true"/>
            </Apply>
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">true</AttributeValue>
        </Apply>
    </Condition>
    <ObligationExpressions>
        <ObligationExpression FulfillOn="Permit" ObligationId="extra-email">
            <AttributeAssignmentExpression AttributeId="extra-email">
                <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">send-email</AttributeValue>
            </AttributeAssignmentExpression>
        </ObligationExpression>
    </ObligationExpressions>
</Rule>
</Policy>
```

<p>But when I send the following XACML request:</p>

<pre class="lang-xml prettyprint-override"><code><Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">

<Attributes Category="urn:custom:company:1.0:attribute-category:operation">
    <Attribute AttributeId="urn:custom:company:1.0:operation:login-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">login</AttributeValue>
    </Attribute>
</Attributes>

<Attributes Category="urn:custom:company:1.0:attribute-category:user-group">
    <Attribute AttributeId="urn:custom:company:1.0:user-group:vip-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vip</AttributeValue>
    </Attribute>
</Attributes>

<Attributes Category="urn:custom:company:1.0:attribute-category:is-user-in-blacklist">
        <Attribute AttributeId="urn:custom:company:1.0:users:user-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">userJon</AttributeValue>
    </Attribute>
</Attributes>
</Request>
</code>```

I'm always receiving an Indeterminate error regarding AttributeDesignator:

<Response xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17">
<Result>
    <Decision>Indeterminate</Decision>
    <Status>
        <StatusCode Value="urn:oasis:names:tc:xacml:1.0:status:processing-error"/>
        <StatusMessage>Couldn't find AttributeDesignator attribute</StatusMessage>
    </Status>
</Result>
</Response>
```

<p>I've created a custom PIPAttributeFinder with the following code:</p>

<pre class="lang-java prettyprint-override"><code>    public class DatabaseAttributeFinder extends LoginDBAttributeFinder {

    private DataSource dataSource;
    private Set<String> supportedAttributes = new HashSet<String>();
    private static Log log = LogFactory.getLog(DatabaseAttributeFinder.class);

    private static final String BLACKLISTED_USER_ID = "urn:custom:company:1.0:is-user-in-blacklist:is-user-in-blacklist-id";

    @Override
    public void init(Properties properties) throws Exception {
        String dataSourceName = (String) properties.get("DataSourceName");

        if(dataSourceName == null || dataSourceName.trim().length() == 0){
            throw new Exception("Data source name can not be null. Please configure it in the entitlement.properties file.");
        }

        dataSource = (DataSource) InitialContext.doLookup(dataSourceName);

        supportedAttributes.add(BLACKLISTED_USER_ID);
    }

... (other code)
</code>```

And the class LoginDBAttributeFinder, looks like this:

public abstract class LoginDBAttributeFinder implements PIPAttributeFinder {

    protected int tenantId;
    private boolean isAbstractAttributeCachingEnabled = false;
    private PIPAbstractAttributeCache abstractAttributeFinderCache = null;
    private static Log log = LogFactory.getLog(LoginDBAttributeFinder.class);

    public LoginDBAttributeFinder() {
    }

    public abstract Set<String> getAttributeValues(String blacklistUserId,
                                                   String attributeId,
                                                   String issuer) throws Exception;

    @Override
    public Set<String> getAttributeValues(URI attributeType, URI attributeId, URI category, String issuer, EvaluationCtx evaluationCtx) throws Exception {
        String blacklistUserId = null;
        Set attributeValues = null;
        this.tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();

        EvaluationResult blacklistUser = evaluationCtx.getAttribute(new URI("http://www.w3.org/2001/XMLSchema#string"), new URI("urn:custom:company:1.0:users:user-id"), issuer, new URI("urn:custom:company:1.0:attribute-category:is-user-in-blacklist"));

        attributeValues = this.getAttributeValues(blacklistUserId, attributeId.toString(), issuer);

        return attributeValues;

... (other code)
```

I have successfully registered the jar in WSO2IS (It shows in the admin console) and whenever I go to the TryIt option, and test the specific policy (check-blacklist-users-in-login) it returns Permit, but when I go to the side Menu "Tools" in the WSO2IS' Console, and use the general "TryIt" tool, it returns Indeterminate (Couldn't find AttributeDesignator).

It seems that it can't find a policy and therefore the AttributeDesignator related to the supported attributes of this policy.

I have also try using the REST API (https://WSO2ISIP:4443/api/identity/entitlement/decision/pdp), and also I get: Indeterminate (Couldn't find AttributeDesignator)

Any ideas on how to fix this?

答:
I've found a solution by doing the following steps:

Stop WSO2IS Server

Comment the class of your customAttributeFinder (in my case was DatabaseAttributeFinder) in the file:
<WSO2IS_HOME>/repository/conf/identity/entitlement.properties

Start WSO2IS Server

Go to the Admin console and check that there's no customAttributeFinder loaded in the Extension section of Entitlement.

Stop WSO2IS Server

Uncomment your customAttributeFinder in the file of step 2

Start WSO2IS

And by magic everything should work OK.

There's seem to be a bug in WSO2IS, whenever I modify anything of the Standard Policy Editor, the XACML Engine starts to behave in a very odd way.

I've seen several StackOverFlow answers where everything is fixed by only restarting the server.

If you don't want WSO2IS to start going slowly mad, stay away from the XACML Policy Editor.

If you want proof, check this Jira Issue (specially in the comments section): https://wso2.org/jira/browse/IDENTITY-5447

Body:
I've created the following policy in the WSO2IS:

<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="check-blacklist-users-in-login" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable" Version="1.0">
<Target>
    <AnyOf>
        <AllOf>
            <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">login</AttributeValue>
                <AttributeDesignator AttributeId="urn:custom:company:1.0:operation:login-id"
                                     Category="urn:custom:company:1.0:attribute-category:operation"
                                     DataType="http://www.w3.org/2001/XMLSchema#string"
                                     MustBePresent="true"/>
            </Match>
        </AllOf>
    </AnyOf>
</Target>
<Rule Effect="Permit" RuleId="permit-blacklisted-users-with-step-up">
    <Target>
        <AnyOf>
            <AllOf>
                <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                    <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vip</AttributeValue>
                    <AttributeDesignator AttributeId="urn:custom:company:1.0:user-group:vip-id"
                                         Category="urn:custom:company:1.0:attribute-category:user-group"
                                         DataType="http://www.w3.org/2001/XMLSchema#string"
                                         MustBePresent="true"/>
                </Match>
            </AllOf>
        </AnyOf>
    </Target>
    <Condition>
        <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
                <AttributeDesignator AttributeId="urn:custom:company:1.0:is-user-in-blacklist:is-user-in-blacklist-id"
                                     Category="urn:custom:company:1.0:attribute-category:is-user-in-blacklist"
                                     DataType="http://www.w3.org/2001/XMLSchema#string"
                                     MustBePresent="true"/>
            </Apply>
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">true</AttributeValue>
        </Apply>
    </Condition>
    <ObligationExpressions>
        <ObligationExpression FulfillOn="Permit" ObligationId="extra-email">
            <AttributeAssignmentExpression AttributeId="extra-email">
                <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">send-email</AttributeValue>
            </AttributeAssignmentExpression>
        </ObligationExpression>
    </ObligationExpressions>
</Rule>
</Policy>

But when I send the following XACML request:

<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">

<Attributes Category="urn:custom:company:1.0:attribute-category:operation">
    <Attribute AttributeId="urn:custom:company:1.0:operation:login-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">login</AttributeValue>
    </Attribute>
</Attributes>

<Attributes Category="urn:custom:company:1.0:attribute-category:user-group">
    <Attribute AttributeId="urn:custom:company:1.0:user-group:vip-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vip</AttributeValue>
    </Attribute>
</Attributes>

<Attributes Category="urn:custom:company:1.0:attribute-category:is-user-in-blacklist">
        <Attribute AttributeId="urn:custom:company:1.0:users:user-id" IncludeInResult="false">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">userJon</AttributeValue>
    </Attribute>
</Attributes>
</Request>

I'm always receiving an Indeterminate error regarding AttributeDesignator:

<Response xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17">
<Result>
    <Decision>Indeterminate</Decision>
    <Status>
        <StatusCode Value="urn:oasis:names:tc:xacml:1.0:status:processing-error"/>
        <StatusMessage>Couldn't find AttributeDesignator attribute</StatusMessage>
    </Status>
</Result>
</Response>

I've created a custom PIPAttributeFinder with the following code:

    public class DatabaseAttributeFinder extends LoginDBAttributeFinder {

    private DataSource dataSource;
    private Set<String> supportedAttributes = new HashSet<String>();
    private static Log log = LogFactory.getLog(DatabaseAttributeFinder.class);

    private static final String BLACKLISTED_USER_ID = "urn:custom:company:1.0:is-user-in-blacklist:is-user-in-blacklist-id";

    @Override
    public void init(Properties properties) throws Exception {
        String dataSourceName = (String) properties.get("DataSourceName");

        if(dataSourceName == null || dataSourceName.trim().length() == 0){
            throw new Exception("Data source name can not be null. Please configure it in the entitlement.properties file.");
        }

        dataSource = (DataSource) InitialContext.doLookup(dataSourceName);

        supportedAttributes.add(BLACKLISTED_USER_ID);
    }

... (other code)

And the class LoginDBAttributeFinder, looks like this:

public abstract class LoginDBAttributeFinder implements PIPAttributeFinder {

    protected int tenantId;
    private boolean isAbstractAttributeCachingEnabled = false;
    private PIPAbstractAttributeCache abstractAttributeFinderCache = null;
    private static Log log = LogFactory.getLog(LoginDBAttributeFinder.class);

    public LoginDBAttributeFinder() {
    }

    public abstract Set<String> getAttributeValues(String blacklistUserId,
                                                   String attributeId,
                                                   String issuer) throws Exception;

    @Override
    public Set<String> getAttributeValues(URI attributeType, URI attributeId, URI category, String issuer, EvaluationCtx evaluationCtx) throws Exception {
        String blacklistUserId = null;
        Set attributeValues = null;
        this.tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();

        EvaluationResult blacklistUser = evaluationCtx.getAttribute(new URI("http://www.w3.org/2001/XMLSchema#string"), new URI("urn:custom:company:1.0:users:user-id"), issuer, new URI("urn:custom:company:1.0:attribute-category:is-user-in-blacklist"));

        attributeValues = this.getAttributeValues(blacklistUserId, attributeId.toString(), issuer);

        return attributeValues;

... (other code)

I have successfully registered the jar in WSO2IS (It shows in the admin console) and whenever I go to the TryIt option, and test the specific policy (check-blacklist-users-in-login) it returns Permit, but when I go to the side Menu "Tools" in the WSO2IS' Console, and use the general "TryIt" tool, it returns Indeterminate (Couldn't find AttributeDesignator).

It seems that it can't find a policy and therefore the AttributeDesignator related to the supported attributes of this policy.

I have also try using the REST API (https://WSO2ISIP:4443/api/identity/entitlement/decision/pdp), and also I get: Indeterminate (Couldn't find AttributeDesignator)

Any ideas on how to fix this?


问:
static_assert failed "typex::value" failure while deserialising binary data using boost
The code below serialises and de serialises the class and structure's members.
The serialisation is working but i have encountered the below error while trying to deserialise it using oarch >> BOOST_SERIALIZATION_NVP(outObj);

Is there any big miss in the code that i have not realiased and not implemented .

In file included from main.cpp:1:
  In file included from /usr/local/include/boost/archive/binary_oarchive.hpp:21:
  In file included from /usr/local/include/boost/archive/binary_oarchive_impl.hpp:22:
  In file included from /usr/local/include/boost/archive/basic_binary_oarchive.hpp:33:
  In file included from /usr/local/include/boost/archive/detail/common_oarchive.hpp:22:
  In file included from /usr/local/include/boost/archive/detail/interface_oarchive.hpp:23:
  In file included from /usr/local/include/boost/archive/detail/oserializer.hpp:68:
  /usr/local/include/boost/archive/detail/check.hpp:162:5: error: static_assert failed "typex::value"
      BOOST_STATIC_ASSERT(typex::value);
      ^                   ~~~~~~~~~~~~
  /usr/local/include/boost/static_assert.hpp:70:41: note: expanded from macro 'BOOST_STATIC_ASSERT'

```<code>#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>

#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};

class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) const
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

int main()
{
    Myclass assetlist;

    auto os = std::ostringstream(std::ios::binary);

    boost::archive::binary_oarchive arch( os, boost::archive::no_header);

    arch << BOOST_SERIALIZATION_NVP(assetlist);

    std::string s1 = os.str();

    std::stringstream is( s1, std::ios_base::binary| std::ios_base::out| std::ios_base::in);

    Myclass outObj;

    boost::archive::binary_iarchive iarch (is , boost::archive::no_header );

    iarch >> BOOST_SERIALIZATION_NVP(outObj);

    return 0;
 }
</code>```

答:
Your static assert fails because of the extra 'const' in Myclass::serialize function.
It should look like:

```<code>template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    { ... }
</code>```

Conserning the BOOST_SERIALIZATION_NVP() usage see this question.

Body:
The code below serialises and de serialises the class and structure's members.
The serialisation is working but i have encountered the below error while trying to deserialise it using oarch >> BOOST_SERIALIZATION_NVP(outObj);

Is there any big miss in the code that i have not realiased and not implemented .

In file included from main.cpp:1:
  In file included from /usr/local/include/boost/archive/binary_oarchive.hpp:21:
  In file included from /usr/local/include/boost/archive/binary_oarchive_impl.hpp:22:
  In file included from /usr/local/include/boost/archive/basic_binary_oarchive.hpp:33:
  In file included from /usr/local/include/boost/archive/detail/common_oarchive.hpp:22:
  In file included from /usr/local/include/boost/archive/detail/interface_oarchive.hpp:23:
  In file included from /usr/local/include/boost/archive/detail/oserializer.hpp:68:
  /usr/local/include/boost/archive/detail/check.hpp:162:5: error: static_assert failed "typex::value"
      BOOST_STATIC_ASSERT(typex::value);
      ^                   ~~~~~~~~~~~~
  /usr/local/include/boost/static_assert.hpp:70:41: note: expanded from macro 'BOOST_STATIC_ASSERT'

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>

#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};

class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) const
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

int main()
{
    Myclass assetlist;

    auto os = std::ostringstream(std::ios::binary);

    boost::archive::binary_oarchive arch( os, boost::archive::no_header);

    arch << BOOST_SERIALIZATION_NVP(assetlist);

    std::string s1 = os.str();

    std::stringstream is( s1, std::ios_base::binary| std::ios_base::out| std::ios_base::in);

    Myclass outObj;

    boost::archive::binary_iarchive iarch (is , boost::archive::no_header );

    iarch >> BOOST_SERIALIZATION_NVP(outObj);

    return 0;
 }

Body:
Your static assert fails because of the extra 'const' in Myclass::serialize function.
It should look like:

template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    { ... }

Conserning the BOOST_SERIALIZATION_NVP() usage see this question.


问:
With angular component and ui-router, can a single controller have multiple templates?
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

```<code> - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;
</code>```

should I do :

components:

```<code>component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;
</code>```

and then routing:

```<code>url 1 --> component x
url 2 --> component y
url 3 --> component z
</code>```

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

答:
```<code>angular.module('', [])
  // Route handler touches this
  .component('route1', {
    template: `<shared-behaviour>
      <route-view-1></route-view-1>
    </shared-behaviour>`
  })
  // This is a purely visual component that links actions with the shared behaviour component
  .component('routeView1', {
    require: {
      shared: '^sharedBehaviour'
    },
    template: '<button ng-click="$ctrl.onClick()></button>',
    controller: class RouteView2Ctrl {
      onClick() {
        this.shared.onSharedClick()
      }
    }
  })
  // Contains the shared behaviour that is shared across the multiple routes
  .component('sharedBehaviour', {
    // Tell Angular to render children passed to this component
    transclude: true,
    template: '<div ng-transclude></div>',
    controller: class SharedBehaviourCtrl {
      onSharedClick() {
        /// do something
      }
    }
  })
  // Newest version of UI-Router
  .state('route1', {
    component: 'route1'
  })
</code>```

Further to our comments, you could use something like the above. It's pretty verbose, but that's Angular 1.5 for you. Haven't tested that it works, but it's a basic idea of how it might work.

The main take away being that you have the route1 component which only handles linking route stuff (like the url, resolves, etc) and passes that information to its children (of which there aren't any).

routeView1 just renders how the route would work, and uses require to talk to some parent API that is shared (you could also use one-way bindings for this if you wanted, but with lots of methods this leads to a messy template).

sharedBehaviour only contains the shared behaviour you want renders any child passed to it.

This is admittedly pretty messy and I would prefer that you instead used one-way bindings for route-view-1 and handled the linking in shared-behaviour, but this might be quite a bit of repetition. You could use some transclusion magic to solve that, but it's.. not really worth it.

I would really recommend against sharing controllers like other answerers have suggested. In Angular 2 and above, a controller is the component. You share behaviour there by doing something similar to what I have done (or by using one-way bindings with callbacks) and using composition.

BTW as mentioned in my answer, newer versions of UI-Router for Angular 1.5 allow you to specify a component to be rendered rather than a template. See here for more info.

Body:
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

 - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;

should I do :

components:

component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;

and then routing:

url 1 --> component x
url 2 --> component y
url 3 --> component z

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

Body:
angular.module('', [])
  // Route handler touches this
  .component('route1', {
    template: `<shared-behaviour>
      <route-view-1></route-view-1>
    </shared-behaviour>`
  })
  // This is a purely visual component that links actions with the shared behaviour component
  .component('routeView1', {
    require: {
      shared: '^sharedBehaviour'
    },
    template: '<button ng-click="$ctrl.onClick()></button>',
    controller: class RouteView2Ctrl {
      onClick() {
        this.shared.onSharedClick()
      }
    }
  })
  // Contains the shared behaviour that is shared across the multiple routes
  .component('sharedBehaviour', {
    // Tell Angular to render children passed to this component
    transclude: true,
    template: '<div ng-transclude></div>',
    controller: class SharedBehaviourCtrl {
      onSharedClick() {
        /// do something
      }
    }
  })
  // Newest version of UI-Router
  .state('route1', {
    component: 'route1'
  })

Further to our comments, you could use something like the above. It's pretty verbose, but that's Angular 1.5 for you. Haven't tested that it works, but it's a basic idea of how it might work.

The main take away being that you have the route1 component which only handles linking route stuff (like the url, resolves, etc) and passes that information to its children (of which there aren't any).

routeView1 just renders how the route would work, and uses require to talk to some parent API that is shared (you could also use one-way bindings for this if you wanted, but with lots of methods this leads to a messy template).

sharedBehaviour only contains the shared behaviour you want renders any child passed to it.

This is admittedly pretty messy and I would prefer that you instead used one-way bindings for route-view-1 and handled the linking in shared-behaviour, but this might be quite a bit of repetition. You could use some transclusion magic to solve that, but it's.. not really worth it.

I would really recommend against sharing controllers like other answerers have suggested. In Angular 2 and above, a controller is the component. You share behaviour there by doing something similar to what I have done (or by using one-way bindings with callbacks) and using composition.

BTW as mentioned in my answer, newer versions of UI-Router for Angular 1.5 allow you to specify a component to be rendered rather than a template. See here for more info.


问:
phonegap push notification works on android but not on ios
As the title says Push notification works fine on android but on IOS it does not. push.on(registration...) is never called. I have made sure that provisional profiles are valid for both development and distribution. I am using firebase for cloud messaging.I am looking for any sort of guidance on how to fix this.

Here is the console out put:

```<code>2017-03-23 16:15:49.741405 [342:34586] Push Plugin register called
2017-03-23 16:15:49.741515 [342:34586] PushPlugin.register: setting badge to false
2017-03-23 16:15:49.741559 [342:34586] PushPlugin.register: clear badge is set to 0
2017-03-23 16:15:49.752879 [342:33926] Push Plugin register success: <######## ######## ######## ######## ######## ######## ######## ########>
</code>```

.

```<code>          document.addEventListener("deviceready", function() {
                var push = PushNotification.init({
                     android: {
                        senderID: "############",
                        forceShow: true
                     },
                     ios: {
                        sound: true,
                        alert: true,
                        badge: true
                     }
                    });

                push.on('registration', function(data) {
                    console.log('GCM: ' + data.registrationId);

                    $rootScope.pushRegStatus = true;

                    $rootScope.registerPushOnServer(data.registrationId);
                });

                push.on('notification', function(data) {
                    // data.message,
                    // data.title,
                    // data.count,
                    // data.sound,
                    // data.image,
                    // data.additionalData
                    // console.log('notification' + data.toString());

                    // App started by clicking on push notification ..
                    // if(data.additionalData.coldstart === false || data.additionalData.coldstart === true) {
                        // $location.path('/pushLog/' + data.additionalData.push_log_id);
                    // }

                    // Got notification while app is in foreground ..
                    if(data.additionalData.foreground) {
                        //$rootScope.alert(data.title, data.message);
                    } else {
                        $rootScope.alert(data.title, data.message);
                        // $location.path('/pushLog/' + data.additionalData.push_log_id);
                        $rootScope.openPushLogFromNotification = true;
                        // setTimeout(function() {
                        //     $rootScope.openPushLogFromNotification = false;
                        // }, 3000);

                        $location.path('/pushLog');
                    }
                });

                push.on('error', function(e) {
                    // e.message
                    console.log(e);
                });

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

答: I fixed it by skiping firebase all together and going straight to APNS</p>

Body:
As the title says Push notification works fine on android but on IOS it does not. push.on(registration...) is never called. I have made sure that provisional profiles are valid for both development and distribution. I am using firebase for cloud messaging.I am looking for any sort of guidance on how to fix this.

Here is the console out put:

2017-03-23 16:15:49.741405 [342:34586] Push Plugin register called
2017-03-23 16:15:49.741515 [342:34586] PushPlugin.register: setting badge to false
2017-03-23 16:15:49.741559 [342:34586] PushPlugin.register: clear badge is set to 0
2017-03-23 16:15:49.752879 [342:33926] Push Plugin register success: <######## ######## ######## ######## ######## ######## ######## ########>

.

          document.addEventListener("deviceready", function() {
                var push = PushNotification.init({
                     android: {
                        senderID: "############",
                        forceShow: true
                     },
                     ios: {
                        sound: true,
                        alert: true,
                        badge: true
                     }
                    });

                push.on('registration', function(data) {
                    console.log('GCM: ' + data.registrationId);

                    $rootScope.pushRegStatus = true;

                    $rootScope.registerPushOnServer(data.registrationId);
                });

                push.on('notification', function(data) {
                    // data.message,
                    // data.title,
                    // data.count,
                    // data.sound,
                    // data.image,
                    // data.additionalData
                    // console.log('notification' + data.toString());

                    // App started by clicking on push notification ..
                    // if(data.additionalData.coldstart === false || data.additionalData.coldstart === true) {
                        // $location.path('/pushLog/' + data.additionalData.push_log_id);
                    // }

                    // Got notification while app is in foreground ..
                    if(data.additionalData.foreground) {
                        //$rootScope.alert(data.title, data.message);
                    } else {
                        $rootScope.alert(data.title, data.message);
                        // $location.path('/pushLog/' + data.additionalData.push_log_id);
                        $rootScope.openPushLogFromNotification = true;
                        // setTimeout(function() {
                        //     $rootScope.openPushLogFromNotification = false;
                        // }, 3000);

                        $location.path('/pushLog');
                    }
                });

                push.on('error', function(e) {
                    // e.message
                    console.log(e);
                });

              }, false);