问:
Compare each row of a matrix in Matlab with the remaining ones
I have a matrix A in Matlab of zeros and ones with dimension BxM.

Specifically, A contains all the possible dispositions of ones and zeros in M spaces considering also the order (hence, B=2^M).

The matrix is built such that, for any i=1,...,N, A(i,:)>A(j,:) or A(i,:)><A(j,:) for j=i+1,...,N.

Writing A(i,:)>=A(j,:) means that A(i,h)>=A(j,h) for h=1,...,M.

Writing A(i,:)>A(j,:) means that A(i,h)>=A(j,h) for h=1,...,M, with strict inequality for at least one h.

Writing A(i,:)><A(j,:) means that it is not possible to establish whether A(i,:)>=A(j,:) or viceversa.

For example when M=3

```<code>  A=[1 1 1;
     1 1 0;
     1 0 1;
     1 0 0;
     0 1 1;
     0 1 0;
     0 0 1;
     0 0 0];
</code>```

Consider

```<code>B=cell(2^M, 2^M);
</code>```

For any two comparable rows of A, A(i,:)>A(j,:), I want B{i,j} containing all rows A(k,:) such that A(j,:)<A(k,:)<A(i,:).

In the example above, the desired output would be

```<code>B{1,4}=[1 1 0; 1 0 1];
B{1,6}=[1 1 0; 0 1 1];
B{1,7}=[1 0 1; 0 1 1];
B{1,8}=[1 1 0; 1 0 1; 1 0 0; 0 1 1; 0 1 0; 0 0 1];
B{2,8}=[1 0 0; 0 1 0];
B{3,8}=[1 0 0; 0 0 1];
B{5,8}=[0 0 1; 0 1 0];
</code>```

This code does what I want

```<code>B=cell(2^M, 2^M);
  for j=1:size(A,1)
      for h=1:size(A,1)
          if  sum(A(j,:)==A(h,:))~=M && sum(A(j,:)>=A(h,:))==M %if A(j,:)>A(h,:) according to the meaning indicated above
              B{j,h}=A(any(bsxfun(@ne, A,A(j,:)),2) & any(bsxfun(@ne, A,A(h,:)),2) &...
              all((bsxfun(@le, A,A(j,:)) &  bsxfun(@ge, A,A(h,:))),2),:);
          end
      end
  end
</code>```

However, the code above is not feasible because in my actual case M=20. Do you have suggestions on whether it is possible to speed it up and, if yes, how?

One of the main problems of the code is that, for M=20, it requires to preallocate a cell (2^20)x(2^20) which, clearly, cannot be done.

On the other hand, at the end of the double loop, lots of cells are empty (because the if condition is not satisfied by many pairs of rows), and what I really need is to keep tracks of the content and of the coordinates only of the non-empty ones. Hence, maybe, a "sparse cell" could help me here.

Any suggestion would be really appreciated.

答:
easy math problem !

A:

```<code>Function out=A(row , number_of_bits)
        out=~bitget(row-1,number_of_bits:-1:1);
end

A(3,3)
ans =
     1     0     1 %which is identical with your A(3,:)
</code>```

B:

```<code>function [out]=B(n1,n2,number_of_bits)
   c1=A(n1,number_of_bits);
   c2=A(n2,number_of_bits);
   out=zeros(1,number_of_bits);
   out((c1==0)&(c2==1))=-1;
   if sum(out)>=0
      out=zeros(1,number_of_bits)+2;
      out(c1==0)=0;
      out(c2==1)=1;
      out=int8(out);
   else
      out=[];
   end

%example:
B(1,4,3)
ans =
     1     2     2 %number 2 serves as wildcard ("*") and means that element could be either 0 or 1, you should discard A(1,:) and A(4,:) from the results so the actual size_of_B is (2^ number_of_wildcards)-2
</code>```

example:

```<code>B(1,1000000,20)
ans =
  Columns 1 through 10
     2     2     2     2     1     2     1     1     1     1
  Columns 11 through 20
     2     1     1     1     2     2     2     2     2     2
  %which means that B(1,1000000) has (2^12)-2=4094 rows

B(1,2,20)
ans =
  Columns 1 through 10
     1     1     1     1     1     1     1     1     1     1
  Columns 11 through 20
     1     1     1     1     1     1     1     1     1     2
  %which means that B(1,2) has (2^1)-2=0 rows
</code>```

size_of_B:

```<code>function out=size_of_B(b)
     if numel(b)==0
        out=0;
     else
        b(~(b==2))=0;
        b(~(b==0))=1;
        out=(2^sum(b))-2;
     end
%example:
size_of_B(B(1,1000000,20))
ans =
        4094
</code>```

there is (2^19)*((2^20)-1)~= 5e11  pair of i, j for iteration
if you had a for loop which done nothing it gets about : 1100 seconds! so the amount of time for calculating all non-empty-B is huge(even if magically we know which element of B is non-empty before any calculation)

```<code>tic;
 for i=1:1:10^9
 end
 toc
Elapsed time is 2.218067 seconds.
tic;
 for i=1:1:10^10
 end
 toc
Elapsed time is 22.165445 seconds.
</code>```

```<code>%example:
 tic;
 M=10;
 n=1;
 for i=1:2^M
     for j=1:2^M
         if i<j
             c=B(i,j,M);
             if ~(size_of_B(c)==0)
                 d(n,:)=c;
                 n=n+1;
             end
         end
     end
 end
 toc
 [s,~]=size(d);
 s
Elapsed time is 10.095085 seconds.
s =
          52905 %for M=10 there is 52905 pair of i,j with non-empty-B values;
</code>```

for M=20 it takes about 10*4^10~=10M seconds ~= 121 days! (if the memory allows)

```<code>%script for plotting number of non-empty-B versus M
  d=[];
 for M=1:10
     tic;
     n=1;
     for i=1:2^M
         for j=1:2^M
             if i<j
                 c=B(i,j,M);
                 if ~(size_of_B(c)==0)
                     d(n,:)=c;
                     n=n+1;
                 end
             end
         end
     end
     toc
     [s,~]=size(d);
     d=[];
     h(M)=s;
 end
Elapsed time is 0.005418 seconds.
Elapsed time is 0.002238 seconds.
Elapsed time is 0.000933 seconds.
Elapsed time is 0.003058 seconds.
Elapsed time is 0.011650 seconds.
Elapsed time is 0.044217 seconds.
Elapsed time is 0.170286 seconds.
Elapsed time is 0.696161 seconds.
Elapsed time is 3.024212 seconds.
Elapsed time is 15.836280 seconds.
>> plot(h,'-o')
</code>```

and estimating from the plot we could find that for M=20 there is about ~3e9 non-empty-B values; (and at least needs about 20~60 GB of memory to store B values like wildcard style which i used and much much more if you want to write all of B without wildcard style)

finally i could mention that exact number of non-empty-B could be calculated with an easy algorithm !

Body:
I have a matrix A in Matlab of zeros and ones with dimension BxM.

Specifically, A contains all the possible dispositions of ones and zeros in M spaces considering also the order (hence, B=2^M).

The matrix is built such that, for any i=1,...,N, A(i,:)>A(j,:) or A(i,:)><A(j,:) for j=i+1,...,N.

Writing A(i,:)>=A(j,:) means that A(i,h)>=A(j,h) for h=1,...,M.

Writing A(i,:)>A(j,:) means that A(i,h)>=A(j,h) for h=1,...,M, with strict inequality for at least one h.

Writing A(i,:)><A(j,:) means that it is not possible to establish whether A(i,:)>=A(j,:) or viceversa.

For example when M=3

  A=[1 1 1;
     1 1 0;
     1 0 1;
     1 0 0;
     0 1 1;
     0 1 0;
     0 0 1;
     0 0 0];

Consider

B=cell(2^M, 2^M);

For any two comparable rows of A, A(i,:)>A(j,:), I want B{i,j} containing all rows A(k,:) such that A(j,:)<A(k,:)<A(i,:).

In the example above, the desired output would be

B{1,4}=[1 1 0; 1 0 1];
B{1,6}=[1 1 0; 0 1 1];
B{1,7}=[1 0 1; 0 1 1];
B{1,8}=[1 1 0; 1 0 1; 1 0 0; 0 1 1; 0 1 0; 0 0 1];
B{2,8}=[1 0 0; 0 1 0];
B{3,8}=[1 0 0; 0 0 1];
B{5,8}=[0 0 1; 0 1 0];

This code does what I want

B=cell(2^M, 2^M);
  for j=1:size(A,1)
      for h=1:size(A,1)
          if  sum(A(j,:)==A(h,:))~=M && sum(A(j,:)>=A(h,:))==M %if A(j,:)>A(h,:) according to the meaning indicated above
              B{j,h}=A(any(bsxfun(@ne, A,A(j,:)),2) & any(bsxfun(@ne, A,A(h,:)),2) &...
              all((bsxfun(@le, A,A(j,:)) &  bsxfun(@ge, A,A(h,:))),2),:);
          end
      end
  end

However, the code above is not feasible because in my actual case M=20. Do you have suggestions on whether it is possible to speed it up and, if yes, how?

One of the main problems of the code is that, for M=20, it requires to preallocate a cell (2^20)x(2^20) which, clearly, cannot be done.

On the other hand, at the end of the double loop, lots of cells are empty (because the if condition is not satisfied by many pairs of rows), and what I really need is to keep tracks of the content and of the coordinates only of the non-empty ones. Hence, maybe, a "sparse cell" could help me here.

Any suggestion would be really appreciated.

Body:
easy math problem !

A:

Function out=A(row , number_of_bits)
        out=~bitget(row-1,number_of_bits:-1:1);
end

A(3,3)
ans =
     1     0     1 %which is identical with your A(3,:)

B:

function [out]=B(n1,n2,number_of_bits)
   c1=A(n1,number_of_bits);
   c2=A(n2,number_of_bits);
   out=zeros(1,number_of_bits);
   out((c1==0)&(c2==1))=-1;
   if sum(out)>=0
      out=zeros(1,number_of_bits)+2;
      out(c1==0)=0;
      out(c2==1)=1;
      out=int8(out);
   else
      out=[];
   end

%example:
B(1,4,3)
ans =
     1     2     2 %number 2 serves as wildcard ("*") and means that element could be either 0 or 1, you should discard A(1,:) and A(4,:) from the results so the actual size_of_B is (2^ number_of_wildcards)-2

example:

B(1,1000000,20)
ans =
  Columns 1 through 10
     2     2     2     2     1     2     1     1     1     1
  Columns 11 through 20
     2     1     1     1     2     2     2     2     2     2
  %which means that B(1,1000000) has (2^12)-2=4094 rows

B(1,2,20)
ans =
  Columns 1 through 10
     1     1     1     1     1     1     1     1     1     1
  Columns 11 through 20
     1     1     1     1     1     1     1     1     1     2
  %which means that B(1,2) has (2^1)-2=0 rows

size_of_B:

function out=size_of_B(b)
     if numel(b)==0
        out=0;
     else
        b(~(b==2))=0;
        b(~(b==0))=1;
        out=(2^sum(b))-2;
     end
%example:
size_of_B(B(1,1000000,20))
ans =
        4094

there is (2^19)*((2^20)-1)~= 5e11  pair of i, j for iteration
if you had a for loop which done nothing it gets about : 1100 seconds! so the amount of time for calculating all non-empty-B is huge(even if magically we know which element of B is non-empty before any calculation)

tic;
 for i=1:1:10^9
 end
 toc
Elapsed time is 2.218067 seconds.
tic;
 for i=1:1:10^10
 end
 toc
Elapsed time is 22.165445 seconds.

%example:
 tic;
 M=10;
 n=1;
 for i=1:2^M
     for j=1:2^M
         if i<j
             c=B(i,j,M);
             if ~(size_of_B(c)==0)
                 d(n,:)=c;
                 n=n+1;
             end
         end
     end
 end
 toc
 [s,~]=size(d);
 s
Elapsed time is 10.095085 seconds.
s =
          52905 %for M=10 there is 52905 pair of i,j with non-empty-B values;

for M=20 it takes about 10*4^10~=10M seconds ~= 121 days! (if the memory allows)

%script for plotting number of non-empty-B versus M
  d=[];
 for M=1:10
     tic;
     n=1;
     for i=1:2^M
         for j=1:2^M
             if i<j
                 c=B(i,j,M);
                 if ~(size_of_B(c)==0)
                     d(n,:)=c;
                     n=n+1;
                 end
             end
         end
     end
     toc
     [s,~]=size(d);
     d=[];
     h(M)=s;
 end
Elapsed time is 0.005418 seconds.
Elapsed time is 0.002238 seconds.
Elapsed time is 0.000933 seconds.
Elapsed time is 0.003058 seconds.
Elapsed time is 0.011650 seconds.
Elapsed time is 0.044217 seconds.
Elapsed time is 0.170286 seconds.
Elapsed time is 0.696161 seconds.
Elapsed time is 3.024212 seconds.
Elapsed time is 15.836280 seconds.
>> plot(h,'-o')

and estimating from the plot we could find that for M=20 there is about ~3e9 non-empty-B values; (and at least needs about 20~60 GB of memory to store B values like wildcard style which i used and much much more if you want to write all of B without wildcard style)

finally i could mention that exact number of non-empty-B could be calculated with an easy algorithm !


来源: stackexchange

问:
orderBy number angular js
I have an array of objects...

```<code>var userObjects =[
{userName: bob,
 age: "25",
 gender: "m"
},
{userName: bill,
 age: "15",
 gender: "m"
},
{userName: jen,
 age: "45",
 gender: "f"
},
]
</code>```

Now I have an ng-repeat in my HTML to iterate over this array of objects.  I want it to sort the age:

```<code><tr ng-repeat="user in userObjects | orderBy:-age">
</code>```

In my JS I am converting my ages to intergers....

```<code>data.forEach(function(user){
   user.age= parseFloat(user.age);
}
</code>```

Angular will not sort by age, I would expect to see...

```<code>bill, 15
bob, 25
jen, 45
</code>```

But instead they are all over the place. What am I doing wrong?

Thanks!

答:
Following will convert the 'age' into numeric and sort in ascending order.

| orderBy : 'age/1'

ContentLicense: CC BY-SA 3.0

Title: orderBy number angular js

Body:
I have an array of objects...

var userObjects =[
{userName: bob,
 age: "25",
 gender: "m"
},
{userName: bill,
 age: "15",
 gender: "m"
},
{userName: jen,
 age: "45",
 gender: "f"
},
]

Now I have an ng-repeat in my HTML to iterate over this array of objects.  I want it to sort the age:

In my JS I am converting my ages to intergers....

data.forEach(function(user){
   user.age= parseFloat(user.age);
}

Angular will not sort by age, I would expect to see...

bill, 15
bob, 25
jen, 45

But instead they are all over the place. What am I doing wrong?

Thanks!


问:
Updating chart.js bar graph in real time
I am using Chart.js to create a simple bar chart with only two rows and 2 sets of data. I am new to using the library and after reading the examples, I feel comfortable with most of the things there. Here is what I have so far

JS code for graph:

```<code>var helpers = Chart.helpers;
var canvas = document.getElementById('bar');

var barChartData = {
    labels: ["IBM", "Microsoft"],
    datasets: [{
      label: "Product A",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",

      data: [25, 75]
    }, {
      label: "Product B",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",

      data: [75, 25]
    }]

  }
  //
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
  tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
  animation: false,
})

;
</code>```

Now, I was wondering if it is possible to update this graph if the data was changed in real time without refreshing the page. For instance if every second the data values keep swapping or something random happens the graph should reflect the changes. I have searched a lot but not found proper document or tutorial explaining this and I would highly appreciate it if someone can show me how to do this.

This is the FIDDLE I have created for work so far.

答:
this is the code

```<code>var canvas = document.getElementById('myChart');
var myBarChart = Chart.Bar(canvas,{
data:{
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
    {
        label: "My First dataset",
        data: [65, 59, 80, 81, 56, 55, 40],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],

           borderWidth: 1
        }
    ]
},
    options:{
    scales: {
    yAxes:[{
        stacked:true,
        gridLines: {
        display:true,
        color:"rgba(255,99,132,0.2)"
        }
    }],
    xAxes:[{
            gridLines: {
            display:false
         }
       }]
    }
  }
 });
</code>```

You can update doing this:

```<code>myBarChart.data.datasets[0].data[4] = 50;//this update the value of may
myBarChart.update();
</code>```

Body:
I am using Chart.js to create a simple bar chart with only two rows and 2 sets of data. I am new to using the library and after reading the examples, I feel comfortable with most of the things there. Here is what I have so far

JS code for graph:

var helpers = Chart.helpers;
var canvas = document.getElementById('bar');

var barChartData = {
    labels: ["IBM", "Microsoft"],
    datasets: [{
      label: "Product A",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",

      data: [25, 75]
    }, {
      label: "Product B",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",

      data: [75, 25]
    }]

  }
  //
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
  tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
  animation: false,
})

;

Now, I was wondering if it is possible to update this graph if the data was changed in real time without refreshing the page. For instance if every second the data values keep swapping or something random happens the graph should reflect the changes. I have searched a lot but not found proper document or tutorial explaining this and I would highly appreciate it if someone can show me how to do this.

This is the FIDDLE I have created for work so far.

Body:
this is the code

var canvas = document.getElementById('myChart');
var myBarChart = Chart.Bar(canvas,{
data:{
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
    {
        label: "My First dataset",
        data: [65, 59, 80, 81, 56, 55, 40],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],

           borderWidth: 1
        }
    ]
},
    options:{
    scales: {
    yAxes:[{
        stacked:true,
        gridLines: {
        display:true,
        color:"rgba(255,99,132,0.2)"
        }
    }],
    xAxes:[{
            gridLines: {
            display:false
         }
       }]
    }
  }
 });

You can update doing this:

myBarChart.data.datasets[0].data[4] = 50;//this update the value of may
myBarChart.update();

ContentLicense: CC BY-SA 4.0


问:
mondgo db does not save with large documents
I'm iterating over a an object with 10000 key/val pairs and creating 'gameItem' docs and adding them to my 'items' field as a hash object and then saving them to my mongo collection like so.

Here's my main collection

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var myItemDbSchema = new Schema({
    db_num: Number,
    last_updated: Number,
    items: {type: {}, default: {}}
}, { minimize: false });

module.exports = mongoose.model('myItemDb', myItemDbSchema);
</code>```

and then my logic

```<code>PartnerAPI.getItems(function(err, partnerItems){

    myItemDb.findOne({"db_num": 1}, function(myItemDB){

        for(var partnerItem in partnerItems){

            if(!myItemDB.items[partnerItem]){

                var newItem = new gameItem({
                    name: partnerItems[partnerItem].name
                });

                myItemDB.items[partnerItem] = newItem;
            }

            myItemDB.markModified('items');

            myItemDB.save(function(err){
                logger.info("Saved");
            });
        }

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

partner items looks like this

```<code>{
    'ballistic-weapon-1':{name:'bl1', value:'rare'}
},
{
    'ballistic-weapon-2':{name:'bl2', value:'rare'}
}
</code>```

This works fine if I only add no more than 300 to the items field and then mark items as modified and then save... but if I try to add all 10,000 and try to save - they don't. Is there a size limit for how many docs I can add to a field with a type {}?

Is there a better way to save these docs without having to write some logic to limit how many saves I do each iteration?

答:
There is 16mb document limit. So if your document (BSON) is larger than 16 mb, mongodb throws exception.

docs: https://docs.mongodb.com/manual/reference/limits/

Body:
I'm iterating over a an object with 10000 key/val pairs and creating 'gameItem' docs and adding them to my 'items' field as a hash object and then saving them to my mongo collection like so.

Here's my main collection

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var myItemDbSchema = new Schema({
    db_num: Number,
    last_updated: Number,
    items: {type: {}, default: {}}
}, { minimize: false });

module.exports = mongoose.model('myItemDb', myItemDbSchema);

and then my logic

PartnerAPI.getItems(function(err, partnerItems){

    myItemDb.findOne({"db_num": 1}, function(myItemDB){

        for(var partnerItem in partnerItems){

            if(!myItemDB.items[partnerItem]){

                var newItem = new gameItem({
                    name: partnerItems[partnerItem].name
                });

                myItemDB.items[partnerItem] = newItem;
            }

            myItemDB.markModified('items');

            myItemDB.save(function(err){
                logger.info("Saved");
            });
        }

    });
});

partner items looks like this

{
    'ballistic-weapon-1':{name:'bl1', value:'rare'}
},
{
    'ballistic-weapon-2':{name:'bl2', value:'rare'}
}

This works fine if I only add no more than 300 to the items field and then mark items as modified and then save... but if I try to add all 10,000 and try to save - they don't. Is there a size limit for how many docs I can add to a field with a type {}?

Is there a better way to save these docs without having to write some logic to limit how many saves I do each iteration?


问:
Sequelize error: Unhandled rejection TypeError: Cannot read property '_pseudo of undefined
I am cloned this app https://github.com/sequelize/express-example which appears to be the official sequelize express example but I get this error when I try to run it

Unhandled rejection TypeError: Cannot read property '_pseudo' of undefined
 at conformInclude (/Users/wasswasam/express-example-master/node_modules/sequelize/lib/model.js:277:14)

I am not sure what's going on.

答:
I'm not sure myself but I do encounter this problem before. And I managed to solve this by removing the include param for findAll function

```<code>models.User.findAll({
    include: [ models.Task ]
  })
</code>```

to

```<code>models.User.findAll()
</code>```

The only think I can think is that you does not have the model it need.
Hope this help.

Body:
I'm not sure myself but I do encounter this problem before. And I managed to solve this by removing the include param for findAll function

models.User.findAll({
    include: [ models.Task ]
  })

to

models.User.findAll()

The only think I can think is that you does not have the model it need.
Hope this help.


问:
jQuery reset star-rating.js
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

```<code> $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }
</code>```

Please help on how to reset these stars to zero or null.

Here is the full code.

```<code> $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});
</code>```

答:
I don't know if this is the best approach, since I'm not familiar with this library...

But I achieved a reset like this:

$(document).ready(function(){
  $('.rating').star_rating();

  $("#resetStars").on("click",function(){
    $(".rating").remove();
    $('.star-rating').replaceWith("0/10 stars");
    $(".rating").text("0/10").star_rating();
  });
});```
<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>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://danielupshaw.com/jquery-star-rating/jquery.star-rating.js"></script>

<h1>This is a good script!</h1>
<span class="rating">9.5/10 stars</span><br>
<br>
<br>
<button id="resetStars">Reset stars</button></code>```

Title: jQuery reset star-rating.js

Body:
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

 $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }

Please help on how to reset these stars to zero or null.

Here is the full code.

 $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});

Body:
I don't know if this is the best approach, since I'm not familiar with this library...

But I achieved a reset like this:

$(document).ready(function(){
  $('.rating').star_rating();

  $("#resetStars").on("click",function(){
    $(".rating").remove();
    $('.star-rating').replaceWith("<span class='rating'>0/10 stars</span>");
    $(".rating").text("0/10").star_rating();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://danielupshaw.com/jquery-star-rating/jquery.star-rating.js"></script>

<h1>This is a good script!</h1>
<span class="rating">9.5/10 stars</span><br>
<br>
<br>
<button id="resetStars">Reset stars</button>


问:
PHP 'illegal offset'
I have a simple PHP blackjack script that I seem to be getting errors in.

The part of code causing the problem is this;

```<code>function evaluateHand($hand) {
    global $faces;
    $value = 0;
    foreach ($hand as $card) {
        if ($value > 11 && $card['face'] == 'a') {
            $value = $value + 1;
        }
        else {
            $value = intval($value) + intval($faces[$card['face']]); <----- error
        }
    }
    return $value;
}
</code>```

The error is "Warning: Illegal offset 'face'" on the line I've pointed to above.

What's causing this? Or how I could fix it?

答: Illegal offset means you are requesting an array key that doesn't exist. In this case, the array in $card has no key face when the error is thrown.

Title: PHP 'illegal offset'

Body:
I have a simple PHP blackjack script that I seem to be getting errors in.

The part of code causing the problem is this;

function evaluateHand($hand) {
    global $faces;
    $value = 0;
    foreach ($hand as $card) {
        if ($value > 11 && $card['face'] == 'a') {
            $value = $value + 1;
        }
        else {
            $value = intval($value) + intval($faces[$card['face']]); <----- error
        }
    }
    return $value;
}

The error is "Warning: Illegal offset 'face'" on the line I've pointed to above.

What's causing this? Or how I could fix it?


问:
Convert date and time into Correct format to compare to current date
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

```<code>string date = "2017-03-29";
string time  = "09:30"
</code>```

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

答:
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.

```<code>string date = "2017-03-29";
string time  = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
</code>```

Body:
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

string date = "2017-03-29";
string time  = "09:30"

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

Body:
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.

string date = "2017-03-29";
string time  = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);


问:
Example of code which incorrectly tries to re-seat a reference
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

```<code>CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();
</code>```

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

答: You can't "reseat" a reference, because it's syntactically impossible.  The reference variable you use which refers to the object uses the same semantics as if it was an object (non-reference) variable.

ContentLicense: CC BY-SA 2.5

Body:
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?


问:
check if any duplicate words exist in a string using regex
Using regex in javascript, how to check for the condition when duplicate words are present in a string?
The words could be located any where in the string:

Given: "but boys run fast boys are strong" or

"boys boys"

expected result: true, since there are 2 repeats of the word "boys"

答:
You can count the occurrence of each matched word</p>

```<code>var str = "but boys run fast boys are strong";
var matches = str.split(/\s/);
var res = matches.map(function(match) {
            return str.match(new RegExp(match, "g")).length;
          });

var bool = res.some(function(len) {return len > 1}));

console.log(bool);

for (var i = 0; i < matches.length; i++) {
  if (res[i] > 1) console.log(matches[i], i);
}
</code>```

Body:
You can count the occurrence of each matched word

var str = "but boys run fast boys are strong";
var matches = str.split(/\s/);
var res = matches.map(function(match) {
            return str.match(new RegExp(match, "g")).length;
          });

var bool = res.some(function(len) {return len > 1}));

console.log(bool);

for (var i = 0; i < matches.length; i++) {
  if (res[i] > 1) console.log(matches[i], i);
}


问:
Why do I get different behavior inside and outside of function?
I get different result when executing this code in a function. What am I missing?

The code that works:

```<code>adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond)
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))
</code>```

The function:

```<code>cnvtNaAndOrder = function(df, colname)
{
  #
  # Change NA's to a "None" factor
  #
  df[,eval(quote(colname))] = as.character(df[,eval(quote(colname))])
  adf[is.na(df[,eval(quote(colname))]), eval(quote(colname))] = "None"
  df[,eval(quote(colname))] = as.factor(df[,eval(quote(colname))])
  df[,eval(quote(colname))] = ordered(df[,eval(quote(colname))], levels=c("None","Po","Fa","TA","Gd","Ex"))

  return(df)
}
</code>```

Direct execution of the code works as expected:

```<code>adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond)
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex
  81    7   35 1326    9    2

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...
</code>```

Execution of what appears to me to be equivalent code through the function results in a warning and different results:

```<code>adf = cnvtNaAndOrder(adf, "GarageCond")
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = c("None", "None", "None",  :
  invalid factor level, NA generated

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex NA's
   0    7   35 1326    9    2   81

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...
</code>```

It appears that the as.factor() is giving the warning and not converting "None" to a factor. Note that I have also tried the df[,"GarageCond"] form to select the column in the direct execution of the code and it works just fine.

What am I missing?  Why is there different behavior?

答: It was a simple typo that I could not see.</p>

Body:
I get different result when executing this code in a function. What am I missing?

The code that works:

adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond)
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))

The function:

cnvtNaAndOrder = function(df, colname)
{
  #
  # Change NA's to a "None" factor
  #
  df[,eval(quote(colname))] = as.character(df[,eval(quote(colname))])
  adf[is.na(df[,eval(quote(colname))]), eval(quote(colname))] = "None"
  df[,eval(quote(colname))] = as.factor(df[,eval(quote(colname))])
  df[,eval(quote(colname))] = ordered(df[,eval(quote(colname))], levels=c("None","Po","Fa","TA","Gd","Ex"))

  return(df)
}

Direct execution of the code works as expected:

adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond)
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex
  81    7   35 1326    9    2

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...

Execution of what appears to me to be equivalent code through the function results in a warning and different results:

adf = cnvtNaAndOrder(adf, "GarageCond")
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = c("None", "None", "None",  :
  invalid factor level, NA generated

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex NA's
   0    7   35 1326    9    2   81

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...

It appears that the as.factor() is giving the warning and not converting "None" to a factor. Note that I have also tried the df[,"GarageCond"] form to select the column in the direct execution of the code and it works just fine.

What am I missing?  Why is there different behavior?


答: If you know what word you're testing for duplicates you could use regular expressions like this str.match(/boys/g).length > 1 to test if that word shows up more than once (assuming your string is in the str variable).

Title: check if any duplicate words exist in a string using regex

Body:
Using regex in javascript, how to check for the condition when duplicate words are present in a string?
The words could be located any where in the string:

Given: "but boys run fast boys are strong" or

"boys boys"

expected result: true, since there are 2 repeats of the word "boys"


问:
segmenting vector with NaN´s
I have an index vector with NaN's such as:

```<code>index=[ 1 2 3 NaN NaN NaN 7 8 9 10 NaN 12 13 14 15 NaN NaN NaN 19 20]
</code>```

What I want is to obtain in a cell the segments between the NaN's.

So I would want:

```<code>segments_index={[1 2 3 ], [ 7 8 9 10], [12 13 14 15], [19 20]};
</code>```

How to automatically implement this operation?

答:
connected components is one way to do that:</p>

```<code>index=[ 1 2 3 NaN NaN NaN 7 8 9 10 NaN 12 13 14 15 NaN NaN NaN 19 20];
notnan = ~isnan(index);
cc = bwconncomp(notnan);
segments_index = cellfun(@(i) index(i),cc.PixelIdxList,'UniformOutput',0)
</code>```

Title: segmenting vector with NaN´s

Body:
I have an index vector with NaN's such as:

index=[ 1 2 3 NaN NaN NaN 7 8 9 10 NaN 12 13 14 15 NaN NaN NaN 19 20]

What I want is to obtain in a cell the segments between the NaN's.

So I would want:

segments_index={[1 2 3 ], [ 7 8 9 10], [12 13 14 15], [19 20]};

How to automatically implement this operation?

Body:
connected components is one way to do that:

index=[ 1 2 3 NaN NaN NaN 7 8 9 10 NaN 12 13 14 15 NaN NaN NaN 19 20];
notnan = ~isnan(index);
cc = bwconncomp(notnan);
segments_index = cellfun(@(i) index(i),cc.PixelIdxList,'UniformOutput',0)


问:
How Can One Use gcloud To Enable APIs
I'm not able to find a way to use the gcloud command line program to change a project's Enabled APIs. My hunch is that it's going to be in the billing "arena" but I've been trying to find this and having much luck.

答:
Edit: This has been deprecated. See gcloud services answer.

Check out the service-management surface. See gcloud help service-management for more help, as well as gcloud help service-management enable for help about enabling new services. Use gcloud service-management list to list available services so you can find the name of the service you want to enable.

Title: How Can One Use gcloud To Enable APIs


问:
String in list, into a function
```<code>myList = ['100', 'sin(x)', '0', '1']
</code>```

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

```<code>myList[1].replace("'", "")
</code>```

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

```<code>from math import sin
def f(x):
    return myList[1]
</code>```

Thus f(x) will give the computed value of sin(x) from this list.

答:
use dict and you archive it </p>

```<code>from math import sin
myList = ['100', 'sin(x)', '0', '1']
options = { 'sin(x)':sin }
options[myList[1]](1)
0.8414709848078965
</code>```

Title: String in list, into a function

Body:
myList = ['100', 'sin(x)', '0', '1']

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

myList[1].replace("'", "")

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

from math import sin
def f(x):
    return myList[1]

Thus f(x) will give the computed value of sin(x) from this list.

Body:
use dict and you archive it

from math import sin
myList = ['100', 'sin(x)', '0', '1']
options = { 'sin(x)':sin }
options[myList[1]](1)
0.8414709848078965


问:
Django Database Design - Null for
Say I have the following model:

```<code>class Person(models.Model):
    street_address = models.CharField(max_length=50, blank=True)
    suburb = models.CharField(max_length=30)
    postcode = models.IntegerField()
    state = models.CharField(max_length=3)
    email = models.EmailField()
    mobile_phone_number = models.IntegerField(max_length=12)
    home_phone_number = models.IntegerField(max_length=10, null=True, blank=True)
    work_phone_number = models.IntegerField(max_length=8, null=True, blank=True)
   spouse = models.ForeignKey('self', null=True, blank=True)
   children = models.ManyToManyField('self', null=True, blank=True)
</code>```

Several of the above fields are meant to be optional (e.g. street_address, home_phone_number and work_phone_number, as well as spouse/children).

In Django, for CharField fields, you can set "blank=True" and if the user leaves the form field blank, Django will store a empty string. That's fine.

However, for integer fields like home_phone_number and work_phone_number, this doesn't work - I've had to use "null=True" in order to deal with the case of people not submitting in those details. Is there a better way, model/database design wise to deal with this, and not have NULLs?

Finally, for optional foreign keys like spouse/children (a person may not be married, or may not have any kids), how should you handle those?

Cheers,
Victor

答:
(A) Phone numbers aren't actually integers, they are character strings, and should be stored in the database as such.

(B) Null is basically the correct way to optional foreign keys.

Title: Django Database Design - Null for

Body:
Say I have the following model:

class Person(models.Model):
    street_address = models.CharField(max_length=50, blank=True)
    suburb = models.CharField(max_length=30)
    postcode = models.IntegerField()
    state = models.CharField(max_length=3)
    email = models.EmailField()
    mobile_phone_number = models.IntegerField(max_length=12)
    home_phone_number = models.IntegerField(max_length=10, null=True, blank=True)
    work_phone_number = models.IntegerField(max_length=8, null=True, blank=True)
   spouse = models.ForeignKey('self', null=True, blank=True)
   children = models.ManyToManyField('self', null=True, blank=True)

Several of the above fields are meant to be optional (e.g. street_address, home_phone_number and work_phone_number, as well as spouse/children).

In Django, for CharField fields, you can set "blank=True" and if the user leaves the form field blank, Django will store a empty string. That's fine.

However, for integer fields like home_phone_number and work_phone_number, this doesn't work - I've had to use "null=True" in order to deal with the case of people not submitting in those details. Is there a better way, model/database design wise to deal with this, and not have NULLs?

Finally, for optional foreign keys like spouse/children (a person may not be married, or may not have any kids), how should you handle those?

Cheers,
Victor


答:
\b matches word boundaries

\w+ will match 1 or more word characters

( ... ) creates a group for matches

\1 will match the contents of matching group #1.

Putting this together, you want a regex containing \b(\w+)\b.*\b\1\b

Plus appropriate backslash quoting, etc.

@guest27134 pointed out the above is not the complete solution, since the OP wanted true/false, not just the regex:

```<code>var result = a_string.match(/\b(\w+)\b.*\b\1\b/g) !== null
</code>```

Or, even shorter, as suggested by O.P.:

```<code>var result = /\b(\w+)\b.*\b\1\b/g.test(myStr)
</code>```

Body:
\b matches word boundaries

\w+ will match 1 or more word characters

( ... ) creates a group for matches

\1 will match the contents of matching group #1.

Putting this together, you want a regex containing \b(\w+)\b.*\b\1\b

Plus appropriate backslash quoting, etc.

@guest27134 pointed out the above is not the complete solution, since the OP wanted true/false, not just the regex:

var result = a_string.match(/\b(\w+)\b.*\b\1\b/g) !== null

Or, even shorter, as suggested by O.P.:

var result = /\b(\w+)\b.*\b\1\b/g.test(myStr)


答:
You're confusing a string value with executable code.  Two basic points:

You can do this with the eval function, which evaluates a string as Python code.

Don't.  Really; eval is a loaded gun pointed at your foot, and usually indicates a poor system design.

What is it that you're trying to do overall?  If you want to trigger the trig functions with text input, you're better heeled to do it with enumerated checks, such as:

```<code>choice = myList[1]
if choice == "sin":
    return sin(x)
elif choice == "cos":
    return cos(x)
...
</code>```

Title: String in list, into a function

Body:
You're confusing a string value with executable code.  Two basic points:

You can do this with the eval function, which evaluates a string as Python code.

Don't.  Really; eval is a loaded gun pointed at your foot, and usually indicates a poor system design.

What is it that you're trying to do overall?  If you want to trigger the trig functions with text input, you're better heeled to do it with enumerated checks, such as:

choice = myList[1]
if choice == "sin":
    return sin(x)
elif choice == "cos":
    return cos(x)
...


问:
CSS - border not going over elements that float left
I have this code here:

```<code><div style="border:3px solid #808080;">
    <h1 style="text-transform: uppercase;font-size: 38px;color: #808080;text-align: center;">Lowell</h1>
    <div class="column-1">
         <img src="images/ruler-icon.png">
    </div>
    <div class="column-2">
         <img src="images/bed-icon.png">
    </div>
    <div class="column-3">
         <img src="images/bath-icon.png">
    </div>
</div>
</code>```

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

```<code>.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}
</code>```

答:
I realize you've already chosen an answer, but here is an alternative - using flexbox. I also separated all the CSS from the HTML (like it should be!)

.container {
  /* Important for columns */
  display: -webkit-flex;
  display: flex;
}

.item {
  /* Important for columns */
  flex-grow: 1;
  border: 3px solid #808080;
  border-top: none;
  height: 52px;
  padding: 10px;
}

.heading {
  border: 3px solid #808080;
  margin: 0;
  text-transform: uppercase;
  font-size: 38px;
  color: #808080;
  text-align: center;
}

/* Remove duplicate borders */
.item-2 {
  border-left: none;
  border-right: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="heading">Lowell</h1>
<div class="container">

  <div class="item item-1">
    <img src="images/ruler-icon.png">
  </div>

  <div class="item item-2">
    <img src="images/bed-icon.png">
  </div>

  <div class="item item-3">
    <img src="images/bath-icon.png">
  </div>
</div></code>```

Body:
I have this code here:

Lowell

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}

Body:
I realize you've already chosen an answer, but here is an alternative - using flexbox. I also separated all the CSS from the HTML (like it should be!)

.container {
  /* Important for columns */
  display: -webkit-flex;
  display: flex;
}

.item {
  /* Important for columns */
  flex-grow: 1;
  border: 3px solid #808080;
  border-top: none;
  height: 52px;
  padding: 10px;
}

.heading {
  border: 3px solid #808080;
  margin: 0;
  text-transform: uppercase;
  font-size: 38px;
  color: #808080;
  text-align: center;
}

/* Remove duplicate borders */
.item-2 {
  border-left: none;
  border-right: none;
}

<h1 class="heading">Lowell</h1>
<div class="container">

  <div class="item item-1">
    <img src="images/ruler-icon.png">
  </div>

  <div class="item item-2">
    <img src="images/bed-icon.png">
  </div>

  <div class="item item-3">
    <img src="images/bath-icon.png">
  </div>
</div>


问:
Purpose of "very efficient factories for elements" in p0083
Proposal
shows weird use of map API:

This makes possible  things like  very efficient factories  for
  elements

```<code>auto new_record()
{
  table_type table;
  table.emplace(...); // Create a record with some parameters.
  return table.extract(table.begin());
}
table.insert(new_record());
</code>```

Assuming record is movable(so returning it from function is not very expensive) is there a point to this code?

答:
It's just an example showing how to create an element and return it without copying (or moving), it's not meant to be production code doing something real.

If you can't see the point of the example, imagine that table is not a local variable but some global that might already contain some values:

```<code>table_type table;
auto insert_record_and_take_first(const Foo& foo, const Bar& bar, const Baz& baz)
{

  table.emplace(foo, bar, baz); // Create a record with some parameters.
  return table.extract(table.begin()); // Remove first
}
table.insert(insert_record_and_take_first());
</code>```

This wouldn't be possible if the record type is not movable. Even if it's movable it might still be more efficient to do it this way.

Assuming record is movable (so returning it from function is not very expensive) is there a point to this code?

Is a pair<const X, Y> movable? How do you move from a const key?

How do you move from a std::set element, when you can only get const iterators to the elements?

Body:
Proposal
shows weird use of map API:

This makes possible  things like  very efficient factories  for
  elements

auto new_record()
{
  table_type table;
  table.emplace(...); // Create a record with some parameters.
  return table.extract(table.begin());
}
table.insert(new_record());

Assuming record is movable(so returning it from function is not very expensive) is there a point to this code?

Body:
It's just an example showing how to create an element and return it without copying (or moving), it's not meant to be production code doing something real.

If you can't see the point of the example, imagine that table is not a local variable but some global that might already contain some values:

table_type table;
auto insert_record_and_take_first(const Foo& foo, const Bar& bar, const Baz& baz)
{

  table.emplace(foo, bar, baz); // Create a record with some parameters.
  return table.extract(table.begin()); // Remove first
}
table.insert(insert_record_and_take_first());

This wouldn't be possible if the record type is not movable. Even if it's movable it might still be more efficient to do it this way.

Assuming record is movable (so returning it from function is not very expensive) is there a point to this code?

Is a pair<const X, Y> movable? How do you move from a const key?

How do you move from a std::set element, when you can only get const iterators to the elements?


答:
Hello, here it is:

```<code>var temp = "but boys run fast boys are strong";
var count = (temp.match(/boys/g) || []).length;
console.log(count);
</code>```

I hope I have helped!

Body:
Hello, here it is:

var temp = "but boys run fast boys are strong";
var count = (temp.match(/boys/g) || []).length;
console.log(count);

I hope I have helped!


问:
Query Builder for Angular2
Is there any query builder out there for Angular2 apps? Something like the jQuery QueryBuilder, but a bit better integrated into the npm world. </p>

答:
I have done one with angular 2 and model form

https://github.com/tjhjqh/Angular2QueryBuilder

Title: Query Builder for Angular2


问:
Loading a JSON file to android device in Unity3D
I need to load my json file in my device. It is working perfectly fine in Unity Editor but when I transferred it to my device, json isn't there. Currently using this code for adding data in my json file:

```<code>TextAsset file = Resources.Load("Products") as TextAsset;
    string jsonString = file.ToString ();
    Debug.Log (jsonString);
    if (jsonString != null)
    {
        jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);

        data.products.Add(product);
        Debug.Log(data.products[1].code);

        jsonString = JsonUtility.ToJson(data);
        Debug.Log(jsonString);
    }
</code>```

And this for retrieving:

```<code>TextAsset file = Resources.Load("Products") as TextAsset;
    string json = file.ToString ();
    //string path = Application.streamingAssetsPath + "/Products.json";
    string path = Application.persistentDataPath + "/Resources/Products.json";
    string jsonString = File.ReadAllText (path);

    jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
</code>```

It can be use in Unity editor but not in my android device. What seems to be the problem? Very big thanks

答:
As explained here, you can't read file from the Resources folder with anything other than Resources.Load. You must use Resources.Load to read anything placed in the Resources folder.

It doesn't matter if it works in the Editor or not the code below that reads from the Resources folder should not work in any build:

```<code>string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);
</code>```

You don't seem to understand when the Resources folder should be used. This is used to store files that does not need to be changed during run-time. For example, your textures, sound, video files and prefabs. These are not meant to be modified during run-time Also, using it to store default value for a text file is fine.

What need to do is to read the file with Resources.Load("Products") then store it in a string. After you modify it, save to another directory with

Save:

```<code>string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
File.WriteAllBytes(tempPath, modifiedJson);.
</code>```

Load:

```<code>string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
jsonByte = File.ReadAllBytes(tempPath);
</code>```

I made a generic class in another question, to handle that easily so you that you don't even need to use the Resources folder or read the file manually. It handles all the errors too.

From your question, your data is stored in jsonParser class. You should rename that class to actually reflect what you are storing such as PlayerInfo or ProductInfo.

Grab the DataSaver class from here. With your current jsonParser data, you can save and load with the code sample below:

Save:

```<code>jsonParser products = new jsonParser();
DataSaver.saveData(products, "Products");
</code>```

Load:

```<code>jsonParser loadedProducts = DataSaver.loadData<jsonParser>("Products");
</code>```

Delete:

```<code>DataSaver.deleteData("Products");
</code>```

Very easy. That should work on any Platform.

Body:
I need to load my json file in my device. It is working perfectly fine in Unity Editor but when I transferred it to my device, json isn't there. Currently using this code for adding data in my json file:

TextAsset file = Resources.Load("Products") as TextAsset;
    string jsonString = file.ToString ();
    Debug.Log (jsonString);
    if (jsonString != null)
    {
        jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);

        data.products.Add(product);
        Debug.Log(data.products[1].code);

        jsonString = JsonUtility.ToJson(data);
        Debug.Log(jsonString);
    }

And this for retrieving:

TextAsset file = Resources.Load("Products") as TextAsset;
    string json = file.ToString ();
    //string path = Application.streamingAssetsPath + "/Products.json";
    string path = Application.persistentDataPath + "/Resources/Products.json";
    string jsonString = File.ReadAllText (path);

    jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);

It can be use in Unity editor but not in my android device. What seems to be the problem? Very big thanks

Body:
As explained here, you can't read file from the Resources folder with anything other than Resources.Load. You must use Resources.Load to read anything placed in the Resources folder.

It doesn't matter if it works in the Editor or not the code below that reads from the Resources folder should not work in any build:

string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);

You don't seem to understand when the Resources folder should be used. This is used to store files that does not need to be changed during run-time. For example, your textures, sound, video files and prefabs. These are not meant to be modified during run-time Also, using it to store default value for a text file is fine.

What need to do is to read the file with Resources.Load("Products") then store it in a string. After you modify it, save to another directory with

Save:

string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
File.WriteAllBytes(tempPath, modifiedJson);.

Load:

string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
jsonByte = File.ReadAllBytes(tempPath);

I made a generic class in another question, to handle that easily so you that you don't even need to use the Resources folder or read the file manually. It handles all the errors too.

From your question, your data is stored in jsonParser class. You should rename that class to actually reflect what you are storing such as PlayerInfo or ProductInfo.

Grab the DataSaver class from here. With your current jsonParser data, you can save and load with the code sample below:

Save:

jsonParser products = new jsonParser();
DataSaver.saveData(products, "Products");

Load:

jsonParser loadedProducts = DataSaver.loadData<jsonParser>("Products");

Delete:

DataSaver.deleteData("Products");

Very easy. That should work on any Platform.


问:
What Type of Random Number Generator is Used in the Casino Gaming Industry?
Given the extremely high requirements for unpredictability to prevent casinos from going bankrupt, what random number generation algorithm and seeding scheme is typically used in devices like slot machines, video poker machines, etc.?

EDIT: Related questions:

Do stateless random number generators exist?

True random number generator

Alternative Entropy Sources

答:
We've been using the Protego R210-USB TRNG (and the non-usb version before that) as random seed generators in casino applications, with java.security.SecureRandom
on top.  We had The Swedish National Laboratory of Forensic Science perform a separate audit of the R210, and it passed without a flaw.</p>

OwnerDisplayName: dsimcha

LastEditorDisplayName: strager


问:
how do you create a popdown menu like the one in fuzzyfinder?
When you launch FuzzyFinder, a 1 row window appears at the top along with a drop down list of matches, which you can go up and down with C-P and C-N. I know how to generate the 1-row mini-window, but how does one generate the drop down list with VimScript?

It looks like this type of drop down list is also used for code completions in Vim.

答:
This is a big and complex set of interrelated functionality in Vim, coming under umbrella of 'completion methods'.  I think FuzzyFinder uses mostly "completion functions".  In any case you can start reading about it in Vim help by doing:

```<code>:h complete-functions
</code>```

and/or

```<code>:h popupmenu-completion
</code>```

Body:
This is a big and complex set of interrelated functionality in Vim, coming under umbrella of 'completion methods'.  I think FuzzyFinder uses mostly "completion functions".  In any case you can start reading about it in Vim help by doing:

:h complete-functions

and/or

:h popupmenu-completion


问:
dc.js composite chart toggle chart
Is there a way to toggle charts on/off in a composite chart?

If I hover over Legend the respective chart is highlighted but it would be nice if we could choose which ones to display (hide/show with Legend, check boxes etc).

I did find reference to hideStack but I don't think this is what I need.

Any ideas?

(Current DC Version: 2.0.0-alpha.2)

答:
You're right, legend toggling is currently focused on stacks and not the subcharts of a composite chart.

It may be possible to hack the legend's toggling system, but here is a solution that just adds the toggling functionality as an extension.

We'll just wait until the chart is drawn with the pretransition event, then add our own click handler to each of the legend items. This will use the index of the legend item to create the selector for the corresponding subchart, then toggle its css visibility:

```<code>function drawLegendToggles(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .style('opacity', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
        return visible ? 1 : 0.2;
    });
}

function legendToggle(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .on('click.hideshow', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
      subchart.style('visibility', function() {
        return visible ? 'hidden' : 'visible';
      });
      drawLegendToggles(chart);
    })
  drawLegendToggles(chart);
}

composite
  .on('pretransition.hideshow', legendToggle);
</code>```

In addition, we'll set the legend item translucent to indicate that the item is hidden.

We want to do this for all items, instead of in response to the click event, because it's more reliable to separate actions from drawing, and draw based on data. In particular, this handles the case where something else (for example an external filtering or zooming event) causes the legend to redraw.

Title: dc.js composite chart toggle chart

Body:
You're right, legend toggling is currently focused on stacks and not the subcharts of a composite chart.

It may be possible to hack the legend's toggling system, but here is a solution that just adds the toggling functionality as an extension.

We'll just wait until the chart is drawn with the pretransition event, then add our own click handler to each of the legend items. This will use the index of the legend item to create the selector for the corresponding subchart, then toggle its css visibility:

function drawLegendToggles(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .style('opacity', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
        return visible ? 1 : 0.2;
    });
}

function legendToggle(chart) {
  chart.selectAll('g.dc-legend .dc-legend-item')
    .on('click.hideshow', function(d, i) {
      var subchart = chart.select('g.sub._' + i);
      var visible = subchart.style('visibility') !== 'hidden';
      subchart.style('visibility', function() {
        return visible ? 'hidden' : 'visible';
      });
      drawLegendToggles(chart);
    })
  drawLegendToggles(chart);
}

composite
  .on('pretransition.hideshow', legendToggle);

In addition, we'll set the legend item translucent to indicate that the item is hidden.

We want to do this for all items, instead of in response to the click event, because it's more reliable to separate actions from drawing, and draw based on data. In particular, this handles the case where something else (for example an external filtering or zooming event) causes the legend to redraw.


问:
Return value from local scope?
Bumped into some code like this in our code base... which made me worried.

```<code>int foo(int a); // Forward declaration.

int baz() {
    int result = {
         int a = dosomestuff();
         foo(a);
    } ? 0 : -1;
    return result;
}
</code>```

Is the behavior of this code well-defined?

Will it really work, that result variable gets loaded with 0 or -1 depending on the return value of foo(a)?

For interest: The code was not written like that originally - however, it is what I imagine this innocent-looking macro will roll out to...

```<code>int foo(int a); // Forward declaration.

#define BAR()  { int a = dosomestuff(); foo(a); }

int baz() {
    int result = BAR() ? 0 : -1;
    return result;
}
</code>```

答:
With C++11 you can get pretty close:</p>

```<code>int foo(int a); // Forward declaration.

int baz() {
    int result = []{
         int a = dosomestuff();
         return foo(a);
    }() ? 0 : -1;
    return result;
}
</code>```

Title: Return value from local scope?

Body:
Bumped into some code like this in our code base... which made me worried.

int foo(int a); // Forward declaration.

int baz() {
    int result = {
         int a = dosomestuff();
         foo(a);
    } ? 0 : -1;
    return result;
}

Is the behavior of this code well-defined?

Will it really work, that result variable gets loaded with 0 or -1 depending on the return value of foo(a)?

For interest: The code was not written like that originally - however, it is what I imagine this innocent-looking macro will roll out to...

int foo(int a); // Forward declaration.

#define BAR()  { int a = dosomestuff(); foo(a); }

int baz() {
    int result = BAR() ? 0 : -1;
    return result;
}

Body:
With C++11 you can get pretty close:

int foo(int a); // Forward declaration.

int baz() {
    int result = []{
         int a = dosomestuff();
         return foo(a);
    }() ? 0 : -1;
    return result;
}


问:
C programming: How to program for Unicode?
What prerequisites are needed to do strict Unicode programming?

Does this imply that my code should not use char types anywhere and that functions need to be used that can deal with wint_t and wchar_t?

And what is the role played by multibyte character sequences in this scenario?

答:
I wouldn't trust any standard library implementation.  Just roll your own unicode types.</p>

```<code>#include <windows.h>

typedef unsigned char utf8_t;
typedef unsigned short utf16_t;
typedef unsigned long utf32_t;

int main ( int argc, char *argv[] )
{
  int msgBoxId;
  utf16_t lpText[] = { 0x03B1, 0x0009, 0x03B2, 0x0009, 0x03B3, 0x0009, 0x03B4, 0x0000 };
  utf16_t lpCaption[] = L"Greek Characters";
  unsigned int uType = MB_OK;
  msgBoxId = MessageBoxW( NULL, lpText, lpCaption, uType );
  return 0;
}
</code>```

OwnerDisplayName: mixedpickles

LastEditorDisplayName: Jonathan Leffler

Body:
I wouldn't trust any standard library implementation.  Just roll your own unicode types.

#include <windows.h>

typedef unsigned char utf8_t;
typedef unsigned short utf16_t;
typedef unsigned long utf32_t;

int main ( int argc, char *argv[] )
{
  int msgBoxId;
  utf16_t lpText[] = { 0x03B1, 0x0009, 0x03B2, 0x0009, 0x03B3, 0x0009, 0x03B4, 0x0000 };
  utf16_t lpCaption[] = L"Greek Characters";
  unsigned int uType = MB_OK;
  msgBoxId = MessageBoxW( NULL, lpText, lpCaption, uType );
  return 0;
}


问:
How should I change my loss function in case of regression in tensorflow if I have network which is initially designed for classification?
I have a pre-trained alexnet designed for classification task.
Now I want to change that model for regression task.

What change should I make in the loss function in the below code in tensorflow? Now as it's regression, I don't have label but a vector of output.

```<code>with tf.name_scope("cross_ent"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = score, labels = y))
</code>```

Also, anything else I should take care of while converting the model?

答:
The last layer of a classification network is usually a softmax layer, coupled with a loss that works well with the types of outputs of a softmax (a vector of probabilities summing to 1).

To perform regression, you will want a linear activation function at the last layer; and you could try a MSE (mean squared error) loss function between your target and your prediction.

Body:
I have a pre-trained alexnet designed for classification task.
Now I want to change that model for regression task.

What change should I make in the loss function in the below code in tensorflow? Now as it's regression, I don't have label but a vector of output.

with tf.name_scope("cross_ent"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = score, labels = y))

Also, anything else I should take care of while converting the model?


问:
MySQL Different results from same query/data
I have two servers running MySQL. Both are on windows. One, is my local machime (Windows 7, MySQL 5.6.25, 32bit) and the other is my production webserver (Windows 2012, MySQL 5.7.11-log, 64bit (that's what show variables showed me).

The data is identical between the two. I backed the data up from the windows 7 (using MySQL Workbench) and restored it on the 2012 machine.

I am running a query on both machine but I am getting different results. I have two tables, projects and projectsnotes with a 1:m relationship between them related on projects.id to projectsnotes.idProject. Each note is marked with a date (dComment). The goal of the query is to retrieve project information and the latest comment only.

Here's the query:

```<code>select space(1) as cAction,
    p.id,
    p.iNum,
    p.cStatus,
    p.cName,
    p.cDesc,
    ifnull(pl.cNickName, 'UNASSIGNED') as cProjectLeader,
    IFNULL(concat (
            date_format(pn.dComment, '%Y-%m-%d'),
            ': ',
            pn.cComment
            ), '') as cComment,
    date_format(p.dRequested, '%Y-%m-%d') as dRequested,
    date_format(p.dRequired, '%Y-%m-%d') as dRequired,
    format(p.nPercentComplete, 2) as nPercentComplete,
    p.tLastUpdated,
    p.bCompleted,
    p.idProjectLeader
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (
    select idProject,
        dComment,
        cComment
    from projectnotes
    order by dComment desc,
        tLastUpdated desc
    ) pn on p.id = pn.idProject
where p.cInstallCode = 'ITM'
    and cStatus in ('Pending', 'Active', 'On Hold', 'Completed', 'Cancelled')
    and bCompleted = 0
group by iNum
order by iNum;
</code>```

Now, here's the weird part. When I run this on my Windows 7 machine, I get the right value for cComment. Specifically:

2017-03-28: Text from note replace

That is the latest note. When I run it on the 2012 server:

2016-05-17: Text from this note replaced too

If I run the subquery alone on the 2012 server, I get the right values (namely, a list of all the notes in the reverse order.

Oh, and this note is neither the first nor the last in the notes for this project.

So I am honestly wondering what is going on. Any thoughts on this would be greatly appreciated.

Thanks in advance.

答:
OK. I think I have a solution to this. Instead of doing it with a join I wrote a function that returned the value I needed as follows:

```<code>DROP FUNCTION if exists f_lastprojectnote;
DELIMITER $$

CREATE FUNCTION f_lastprojectnote(tidProject varchar(36))
RETURNS varchar(1000) DETERMINISTIC
BEGIN
    DECLARE cRetVal VARCHAR(1000);

    SELECT concat(date_format(pn.dComment, '%Y-%m-%d'), ': ', pn.cComment) INTO cRetVal
      FROM projectnotes pn
     WHERE idProject = tidProject
     ORDER BY dComment DESC, tLastUpdated DESC
     LIMIT 1;

    RETURN cRetVal;
END$$

DELIMITER ;
</code>```

It works...

Body:
I have two servers running MySQL. Both are on windows. One, is my local machime (Windows 7, MySQL 5.6.25, 32bit) and the other is my production webserver (Windows 2012, MySQL 5.7.11-log, 64bit (that's what show variables showed me).

The data is identical between the two. I backed the data up from the windows 7 (using MySQL Workbench) and restored it on the 2012 machine.

I am running a query on both machine but I am getting different results. I have two tables, projects and projectsnotes with a 1:m relationship between them related on projects.id to projectsnotes.idProject. Each note is marked with a date (dComment). The goal of the query is to retrieve project information and the latest comment only.

Here's the query:

select space(1) as cAction,
    p.id,
    p.iNum,
    p.cStatus,
    p.cName,
    p.cDesc,
    ifnull(pl.cNickName, 'UNASSIGNED') as cProjectLeader,
    IFNULL(concat (
            date_format(pn.dComment, '%Y-%m-%d'),
            ': ',
            pn.cComment
            ), '') as cComment,
    date_format(p.dRequested, '%Y-%m-%d') as dRequested,
    date_format(p.dRequired, '%Y-%m-%d') as dRequired,
    format(p.nPercentComplete, 2) as nPercentComplete,
    p.tLastUpdated,
    p.bCompleted,
    p.idProjectLeader
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (
    select idProject,
        dComment,
        cComment
    from projectnotes
    order by dComment desc,
        tLastUpdated desc
    ) pn on p.id = pn.idProject
where p.cInstallCode = 'ITM'
    and cStatus in ('Pending', 'Active', 'On Hold', 'Completed', 'Cancelled')
    and bCompleted = 0
group by iNum
order by iNum;

Now, here's the weird part. When I run this on my Windows 7 machine, I get the right value for cComment. Specifically:

2017-03-28: Text from note replace

That is the latest note. When I run it on the 2012 server:

2016-05-17: Text from this note replaced too

If I run the subquery alone on the 2012 server, I get the right values (namely, a list of all the notes in the reverse order.

Oh, and this note is neither the first nor the last in the notes for this project.

So I am honestly wondering what is going on. Any thoughts on this would be greatly appreciated.

Thanks in advance.

Body:
OK. I think I have a solution to this. Instead of doing it with a join I wrote a function that returned the value I needed as follows:

DROP FUNCTION if exists f_lastprojectnote;
DELIMITER $$

CREATE FUNCTION f_lastprojectnote(tidProject varchar(36))
RETURNS varchar(1000) DETERMINISTIC
BEGIN
    DECLARE cRetVal VARCHAR(1000);

    SELECT concat(date_format(pn.dComment, '%Y-%m-%d'), ': ', pn.cComment) INTO cRetVal
      FROM projectnotes pn
     WHERE idProject = tidProject
     ORDER BY dComment DESC, tLastUpdated DESC
     LIMIT 1;

    RETURN cRetVal;
END$$

DELIMITER ;

It works...


问:
Tracking remote uncommitted changes
I'm trying to track modified files on a live website with GIT, I have deployed a non-bare repository on the website, with a post-receive hook.

Is it possible to see what changes have been made in the remote's working copy without committing them?

I'll give an example to clarify things:

I have a live installation of Wordpress with a repository on its root.

I push changes from local repository, but Wordpress itself has made changes to remote's files, so the push won't affect these files since they have uncommitted changes.

I would like to see what changes has Wordpress made so I can stage them or not.

答: git fetch will do this for you. It gets the changes in the remote branches without changing your local copy. Look at What is the difference between 'git pull' and 'git fetch'? for more information.

Title: Tracking remote uncommitted changes


问:
All Node.js/Express routes returning 404 on hosted server
I recently began building an app with node.js. After some time I wanted to move it onto my hosting account to really test it.

First I installed nodejs from source.
Then I changed nothing to the code except for Database login. When I ran it, there were no error. Excitedly I tried it out. To my dismay, I got a 404 for every single route I had programed.

For example:

```<code>router.route('/new')
.post(function(req, res){
    //My Route Code
});

app.use('/api', router);
</code>```

Then I go to:

mywebsite.com/api/new

This returns a 404 Not Found Error from my apache server.

I would also like to note that I am using I am using Shared Hosting, and I have also thoroughly tested my code offline on my test server.

How can I fix it so that my code actually routes my request?

答:
It seems that it's not a problem with your Node app but with your Apache configuration.

If it is Express that is giving you 404 then you should see a 404 response with this in the body as plain text:

```<code>Cannot GET /api/new
</code>```

This is a standard Express message. If you don't see it then it is not Express that's giving you that answer but something else along the way - likely Apache.

Make sure that your Apache is correctly configured as a reverse proxy for that host name and port that you try to access from your browser, and that it passes the requests to the correct host and port where your Node app can be accessed.

See those tutorials:

https://gist.github.com/stagas/754303

https://atticuswhite.com/blog/apache-serving-nodejs/

http://blog.podrezo.com/making-node-js-work-with-apache/

Body:
I recently began building an app with node.js. After some time I wanted to move it onto my hosting account to really test it.

First I installed nodejs from source.
Then I changed nothing to the code except for Database login. When I ran it, there were no error. Excitedly I tried it out. To my dismay, I got a 404 for every single route I had programed.

For example:

router.route('/new')
.post(function(req, res){
    //My Route Code
});

app.use('/api', router);

Then I go to:

mywebsite.com/api/new

This returns a 404 Not Found Error from my apache server.

I would also like to note that I am using I am using Shared Hosting, and I have also thoroughly tested my code offline on my test server.

How can I fix it so that my code actually routes my request?

Body:
It seems that it's not a problem with your Node app but with your Apache configuration.

If it is Express that is giving you 404 then you should see a 404 response with this in the body as plain text:

Cannot GET /api/new

This is a standard Express message. If you don't see it then it is not Express that's giving you that answer but something else along the way - likely Apache.

Make sure that your Apache is correctly configured as a reverse proxy for that host name and port that you try to access from your browser, and that it passes the requests to the correct host and port where your Node app can be accessed.

See those tutorials:

https://gist.github.com/stagas/754303

https://atticuswhite.com/blog/apache-serving-nodejs/

http://blog.podrezo.com/making-node-js-work-with-apache/


问:
Meteor.js Cordova App Failing DOCTYPE
So, I'm building a cross-platform meteor app that uses the BarcodeScanner Plugin. I can build using:

```<code>    meteor build cordova --server localhost:3000
</code>```

But when I try to run using:

```<code>    meteor
</code>```

I get these errors

```<code>       cordova/android/project/assets/www/application/head.html:1:Expected one of: <body>, <head>, <template>
       cordova/android/project/assets/www/application/index.html:1:Can't set DOCTYPE here.  (Meteor sets <!DOCTYPE html> for you)
       cordova/android/project/build/outputs/lint-results-release-fatal.html:1: Can't set DOCTYPE here.  (Meteor sets <!DOCTYPE html>
</code>```

How can i fix this?

答:
It sounds like you did not provide an output directory when you did the cordova build and your meteor app folder is now populated with built js/html files.

To fix this, delete these files from your meteor app directory and next time you build use the --directory option to specify a path outside your app folder.

You might also find the Meteor Mobile Guide helpful if you are not already using it.

Title: Meteor.js Cordova App Failing DOCTYPE

Body:
So, I'm building a cross-platform meteor app that uses the BarcodeScanner Plugin. I can build using:

    meteor build cordova --server localhost:3000

But when I try to run using:

    meteor

I get these errors

       cordova/android/project/assets/www/application/head.html:1:Expected one of: , , <template>
       cordova/android/project/assets/www/application/index.html:1:Can't set DOCTYPE here.  (Meteor sets <!DOCTYPE html> for you)
       cordova/android/project/build/outputs/lint-results-release-fatal.html:1: Can't set DOCTYPE here.  (Meteor sets <!DOCTYPE html>

How can i fix this?


问:
Data manipulation in C# - Strings
I am trying to slightly modify some sample code for a USB device that reads serial data. The current way the data is displayed is very confusing. The device reads 30 bits worth of data. The following section of code is what I am trying to manipulate...

```<code>private string GetDataString()
        {
            string strTemp;

            strTemp = "";

            if ((m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_RTR) == TPCANMessageType.PCAN_MESSAGE_RTR)
                return "Remote Request";
            else
                // UNCOMMENT FOR DECIMAL
                for (int i = Form1.GetLengthFromDLC(m_Msg.DLC, (m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_FD) == 0) - 1; i >= 0; i--)
                    strTemp += string.Format("{0:000} ", m_Msg.DATA[i]);

                //// UNCOMMENT FOR HEX
                //for (int i = Form1.GetLengthFromDLC(m_Msg.DLC, (m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_FD) == 0) - 1; i >= 0; i--)
                //    strTemp += string.Format("{0:X2} ", m_Msg.DATA[i]);

            return strTemp;
        }
</code>```

The returned string is in one of two formats, depending upon which section I uncomment. Below is a sample read in each format:

"000 000 123 255 " (decimal)

"00 00 7B FF " (hex)

The problem is that there are two sections of information encoded here: the rightmost 12 bits of data (call these ST) and the next 18 bits (call these MT). Data is displayed in little-endian format (LSB to the right). I am trying to modify this section of code to display each section via its corresponding decimal value.

So the above examples would be displayed as:

"7 3071"

(MT) (ST)

Any recommendations on how to perform this conversion? I apologize in advance if this is a stupid question, but I am quite inexperienced in C# programming.

答:
You have to do some bitwise operations.  It would look something like this:</p>

```<code>    uint MT, ST;

    MT = (uint)((m_MSG.DATA[3] & 0x3F) << 12);
    MT |= (uint)(m_MSG.DATA[2] << 4);
    MT |= (uint)((m_MSG.DATA[1] & 0xF0) >> 4);

    ST = (uint)((m_MSG.DATA[1] & 0x0F) << 8);
    ST |= m_MSG.DATA[0];
</code>```

Title: Data manipulation in C# - Strings

Body:
I am trying to slightly modify some sample code for a USB device that reads serial data. The current way the data is displayed is very confusing. The device reads 30 bits worth of data. The following section of code is what I am trying to manipulate...

private string GetDataString()
        {
            string strTemp;

            strTemp = "";

            if ((m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_RTR) == TPCANMessageType.PCAN_MESSAGE_RTR)
                return "Remote Request";
            else
                // UNCOMMENT FOR DECIMAL
                for (int i = Form1.GetLengthFromDLC(m_Msg.DLC, (m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_FD) == 0) - 1; i >= 0; i--)
                    strTemp += string.Format("{0:000} ", m_Msg.DATA[i]);

                //// UNCOMMENT FOR HEX
                //for (int i = Form1.GetLengthFromDLC(m_Msg.DLC, (m_Msg.MSGTYPE & TPCANMessageType.PCAN_MESSAGE_FD) == 0) - 1; i >= 0; i--)
                //    strTemp += string.Format("{0:X2} ", m_Msg.DATA[i]);

            return strTemp;
        }

The returned string is in one of two formats, depending upon which section I uncomment. Below is a sample read in each format:

"000 000 123 255 " (decimal)

"00 00 7B FF " (hex)

The problem is that there are two sections of information encoded here: the rightmost 12 bits of data (call these ST) and the next 18 bits (call these MT). Data is displayed in little-endian format (LSB to the right). I am trying to modify this section of code to display each section via its corresponding decimal value.

So the above examples would be displayed as:

"7 3071"

(MT) (ST)

Any recommendations on how to perform this conversion? I apologize in advance if this is a stupid question, but I am quite inexperienced in C# programming.

Body:
You have to do some bitwise operations.  It would look something like this:

    uint MT, ST;

    MT = (uint)((m_MSG.DATA[3] & 0x3F) << 12);
    MT |= (uint)(m_MSG.DATA[2] << 4);
    MT |= (uint)((m_MSG.DATA[1] & 0xF0) >> 4);

    ST = (uint)((m_MSG.DATA[1] & 0x0F) << 8);
    ST |= m_MSG.DATA[0];


问:
Poor performance of long list rendering in Angular2
I have an application with a history stream, containing user actions. The history is displayed by days or whole weeks. During one day there is approximately around 400-2k of events to display.

There are few types of actions that may occur and each one is displayed differently (e.g. comment or object modification). Therefore there is some logic in each loop iteration to determinate the final structure of each element.

The problem is that it lots of time to render, ~1300 elements renders around 6s. For me it is pretty long time to wait for such thing. I have tried to optimise the code to do the required minimum, but still the best I could get is 6s for ~1300 elements.

The other bigger problem with that is freezed browser during the rendering which is not acceptable for such long time.

I'm not sure if I have done something wrong or I have found a week spot of Angular2 which is not possible to resolve. So any hint is welcome.
I'm not interested in advices like: use pagination or use infinite scroll, I'm am looking for a way to make it work faster and smother.

I will also add that previously the history was rendered on the servers side and putting the result into the DOM was super quick, no matter of the number of events. Further screenshots also shows that the real rendering time is just a very small part of the process.

I have prepared simplified version of the rendering code in the plunker which shows the problem:
http://plnkr.co/edit/QrYmYezmlV3MkQV5bOA8?p=preview

The main rendering parts:

Root ngFor element

```<code><div class="history-stream">
  <div *ngFor="let action of history"
       class="activity" [ngClass]="{'first-of-user': action.firstOfUser, 'last-of-user': action.lastOfUser}">
    <p class="date" *ngIf="action.firstOfDay">{{ action.date | date:'mediumDate' }}</p>
    <div class="user-entry" [ngSwitch]="action.type">
      <comment *ngSwitchCase="'comment'" [object]="action"></comment>
      <modified *ngSwitchCase="'modified'" [object]="action"></modified>
    </div>
  </div>
</div>
</code>```

Comment component:

```<code><div class="entry comment" [ngClass]="{'comment-resolved': object.extra.is_resolved}">
  <a href="{{ getDeleteUrl(object.extra.comment_id) }}" data-target="metabase-modal-ajax" class="comment-action">Delete</a>
  <a href="#" class="comment-action" *ngIf="!object.extra.is_resolved" (click)="resolveComment($event)">Mark as resolved</a>
  <a href="#" class="comment-action" *ngIf="object.extra.is_resolved" (click)="unResolveComment($event)">Unresolve</a>
  <p class="action" [innerHTML]="object.action"></p>
  <p>{{ object.comment }}</p>
  <small class="text-muted">{{ object.date | date:'shortTime' }} <span class="dot">·</span> {{ object.date | date:'shortTime' }}</small>
</div>
</code>```

Modified event component:

```<code><div class="entry modified">
  <p class="action" [innerHTML]="object.action"></p>
  <ul class="changes list-unstyled">
    <li *ngFor="let change of object.changes">
      <span class="attribute">{{ change.attribute }}:</span>
      <modified-value [change]="change.from"></modified-value>
      <span class="arrow">→</span>
      <modified-value [change]="change.to"></modified-value>
      <small class="time text-muted">{{ change.date | date:'shortTime' }} <span class="dot">·</span> {{ change.date | date:'shortTime' }}</small>
    </li>
  </ul>
</div>
</code>```

And modified-value component:

```<code><span [ngSwitch]="getChangeType()">
  <span *ngSwitchCase="'complex'">
    <span *ngFor="let item of change">
      <span class="badge">{{ item.tag }}</span>
      <span [ngSwitch]="isArray(item.value)">
        <span *ngSwitchCase="true">
          <span *ngFor="let valueItem of item.value" class="value tag">{{ valueItem }}</span>
          <span *ngIf="isEmpty(item.value)" class="value text-muted">None</span>
        </span>
        <span *ngSwitchCase="false">
          <span *ngIf="item.value" class="value">{{ item.value }}</span>
          <span *ngIf="!item.value" class="value text-muted">None</span>
        </span>
      </span>
    </span>
  </span>
  <span *ngSwitchDefault>
    <span *ngIf="change" class="value">{{ change }}</span>
    <span *ngIf="!change" class="value text-muted">None</span>
  </span>
</span>
</code>```

Also a few screenshots of profiles recording:

答: Angular 7 introduced virtual scroll feature. It can help dramatically increase render performance - only visible part of list is added to DOM. But it also add some restrictions, like fixed row size</p>

Body:
I have an application with a history stream, containing user actions. The history is displayed by days or whole weeks. During one day there is approximately around 400-2k of events to display.

There are few types of actions that may occur and each one is displayed differently (e.g. comment or object modification). Therefore there is some logic in each loop iteration to determinate the final structure of each element.

The problem is that it lots of time to render, ~1300 elements renders around 6s. For me it is pretty long time to wait for such thing. I have tried to optimise the code to do the required minimum, but still the best I could get is 6s for ~1300 elements.

The other bigger problem with that is freezed browser during the rendering which is not acceptable for such long time.

I'm not sure if I have done something wrong or I have found a week spot of Angular2 which is not possible to resolve. So any hint is welcome.
I'm not interested in advices like: use pagination or use infinite scroll, I'm am looking for a way to make it work faster and smother.

I will also add that previously the history was rendered on the servers side and putting the result into the DOM was super quick, no matter of the number of events. Further screenshots also shows that the real rendering time is just a very small part of the process.

I have prepared simplified version of the rendering code in the plunker which shows the problem:
http://plnkr.co/edit/QrYmYezmlV3MkQV5bOA8?p=preview

The main rendering parts:

Root ngFor element

{{ action.date | date:'mediumDate' }}

      <comment *ngSwitchCase="'comment'" [object]="action"></comment>
      <modified *ngSwitchCase="'modified'" [object]="action"></modified>

Comment component:

  Delete
  Mark as resolved
  Unresolve

{{ object.comment }}

  {{ object.date | date:'shortTime' }} · {{ object.date | date:'shortTime' }}

Modified event component:

      {{ change.attribute }}:
      <modified-value [change]="change.from"></modified-value>
      →
      <modified-value [change]="change.to"></modified-value>
      {{ change.date | date:'shortTime' }} · {{ change.date | date:'shortTime' }}

And modified-value component:

      {{ item.tag }}

          {{ valueItem }}
          None

          {{ item.value }}
          None

    {{ change }}
    None

Also a few screenshots of profiles recording:


问:
Xcode 8 Unit Test Error: Could Not Determine Bundle Identifier for TEST_HOST
I have an Xcode project that does not seem to want to compile my main app target to generate a product prior to attempting to use it as the application host when running unit tests. From Xcode, I am attempting to run unit tests with ⌘ + U.

I immediately get a dialog which states:

Could not determine bundle identifier for [app name] TEST_HOST

(Replace [app name] with the real application name)

This dialog also includes a path to my local derived data products directory:

"/Users/***/Library/Developer/Xcode/DerivedData/Lowes-aymgdtrbrarmcidtkxoqxeafmxmj/Build/Products/Debug-iphonesimulator/[app name]"

I have unit tests set up with the TEST_HOST setting pointing to $(BUILT_PRODUCTS_DIR)/[app name].app/[app name]. The unit test target has a target dependency on the main app target. The BUNDLE_LOADER setting is set to $(TEST_HOST). If I compile the main app target first by hitting ⌘ + B, the correct directory structure and app are created, and then hitting ⌘ + U bootstraps and runs the unit tests correctly. If I do a clean and try again it immediately fails. I have never run into this issue before, and it seems to have sprung up after the app was converted to Swift 3. This may or may not have any bearing on the problem, not really sure.

I have read through several answers here and tried a lot of the suggestions, but they don't seem to have the same root problem as me. For most people, it seems setting the host application to None and back to the main target fixes the issue. This is not the case for me.

Tests stop working under xcode 8 TEST_HOST error

Could not determine bundle identifier for xxxTest TEST_HOST

I've tried fresh checkouts, re-converting the app and test targets to Swift 3, and also the standard clean / clean build folder / wipe derived data. None of these seem to have any effect.

Has anyone else experienced this issue and figured out a solution?

答: Deleting the Test Host completely from the Build Settings of your test target would solve this issue


问:
problems with wordpress site after changing permalink structure
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>
</code>```

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.

答:
Delete .htaccess and regenerate it. Else use the following:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>
</code>```

Secondly, what you are trying to achieve has to be done in two steps.

1) In Settings > General, change the wordpress url in both fields to www.cob1.org
2) In your apache config, set www.cob1.org to point to /entwurf/cob1/

```<code><VirtualHost *:80>
    DocumentRoot "complete-absolute-path-to/entwurf/cob1/"
    ServerName cob1.org
    ServerAlias www.cob1.org
</VirtualHost>
</code>```

3) Verify that .htaccess is being read. This takes a little bit of experimentation. Eg. I'd place some random text in .htaccess to force a server error on purpose. If I see the error, that means that the .htaccess file is being read. If it's not being read, make sure "AllowOverride All" is set in the apache config. .htaccess files are only read by apache (and apache family servers.)
Restart apache. You're done.

Body:
My wordpress site lies in a folder called /entwurf/cob1 and since I wanted it to be shown by simply typing in www.cob1.org I changed the permalink to cob1.org and now nothing works. I tried changing the htacces to:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /entwurf/cob1/index.php [L]
</IfModule>

but this doesnt seem to work either. I want my files who lie in the entwurf/cob1/ folder to be shown when typing in the cob1.org website.
Currently nothing is seen.

Body:
Delete .htaccess and regenerate it. Else use the following:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /entwurf/cob1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

Secondly, what you are trying to achieve has to be done in two steps.

1) In Settings > General, change the wordpress url in both fields to www.cob1.org
2) In your apache config, set www.cob1.org to point to /entwurf/cob1/

<VirtualHost *:80>
    DocumentRoot "complete-absolute-path-to/entwurf/cob1/"
    ServerName cob1.org
    ServerAlias www.cob1.org
</VirtualHost>

3) Verify that .htaccess is being read. This takes a little bit of experimentation. Eg. I'd place some random text in .htaccess to force a server error on purpose. If I see the error, that means that the .htaccess file is being read. If it's not being read, make sure "AllowOverride All" is set in the apache config. .htaccess files are only read by apache (and apache family servers.)
Restart apache. You're done.