问:
L3 cpu cache java benchmark shows strange results
After reading this article I decided to check it on my laptop. The idea is create array with size [1..40] Mb, and then iterate over it 1024 times (e.g for array with size 1 step will be 1024, for array with 2 mb size step will be 2048 etc.). My code is:

```<code>public class L3CacheBenchmark {

    @State(Scope.Benchmark)
    public static class P {

        @Param({
                       "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                       "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                       "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
                       "31", "32", "33", "34", "35", "36", "37", "38", "39", "40",
               })
        public int size;
    }

    @State(Scope.Thread)
    public static class ThreadData {

        byte[] array;
        int    len;

        @Setup
        public void setup(P p) {
            array = new byte[p.size * 1024 * 1024];
            len = array.length;
        }
    }

    @Benchmark
    public byte[] testMethod(ThreadData data) {
        int step = (data.len / 1024) - 1;
        for (int k = 0; k < data.len; k += step) {
            data.array[k] = 1;
        }
        return data.array;
    }

}
</code>```

And results:

```<code>Benchmark                    (size)   Mode  Cnt       Score       Error  Units
L3CacheBenchmark.testMethod       1  thrpt  100  310521,031 ±  1124,590  ops/s
L3CacheBenchmark.testMethod       2  thrpt  100  331853,495 ±  1124,547  ops/s
L3CacheBenchmark.testMethod       3  thrpt  100  311499,659 ±   745,414  ops/s
L3CacheBenchmark.testMethod       4  thrpt  100  290270,382 ±  8501,690  ops/s
L3CacheBenchmark.testMethod       5  thrpt  100  212929,246 ± 14847,931  ops/s
L3CacheBenchmark.testMethod       6  thrpt  100  315968,138 ±  4454,210  ops/s
L3CacheBenchmark.testMethod       7  thrpt  100  209679,904 ± 26050,365  ops/s
L3CacheBenchmark.testMethod       8  thrpt  100   60409,187 ±   212,548  ops/s
L3CacheBenchmark.testMethod       9  thrpt  100  221290,756 ± 28970,586  ops/s
L3CacheBenchmark.testMethod      10  thrpt  100  322865,687 ±  1545,967  ops/s
L3CacheBenchmark.testMethod      11  thrpt  100  263153,747 ± 18497,624  ops/s
L3CacheBenchmark.testMethod      12  thrpt  100  298683,205 ±  1277,032  ops/s
L3CacheBenchmark.testMethod      13  thrpt  100  180984,220 ± 26611,649  ops/s
L3CacheBenchmark.testMethod      14  thrpt  100  324815,938 ±  1657,303  ops/s
L3CacheBenchmark.testMethod      15  thrpt  100  264965,412 ±  9335,923  ops/s
L3CacheBenchmark.testMethod      16  thrpt  100   58830,825 ±   291,412  ops/s
L3CacheBenchmark.testMethod      17  thrpt  100  255576,829 ±  7083,025  ops/s
L3CacheBenchmark.testMethod      18  thrpt  100  324174,133 ±  2247,157  ops/s
L3CacheBenchmark.testMethod      19  thrpt  100  212969,202 ± 18204,625  ops/s
L3CacheBenchmark.testMethod      20  thrpt  100  295246,470 ±  1224,817  ops/s
L3CacheBenchmark.testMethod      21  thrpt  100  251762,642 ± 23405,100  ops/s
L3CacheBenchmark.testMethod      22  thrpt  100  323196,428 ±  2245,465  ops/s
L3CacheBenchmark.testMethod      23  thrpt  100  254588,338 ± 23845,090  ops/s
L3CacheBenchmark.testMethod      24  thrpt  100   53373,580 ±   252,183  ops/s
L3CacheBenchmark.testMethod      25  thrpt  100  213220,459 ± 20440,716  ops/s
L3CacheBenchmark.testMethod      26  thrpt  100  322625,597 ±  2076,341  ops/s
L3CacheBenchmark.testMethod      27  thrpt  100  293643,720 ±  5260,010  ops/s
L3CacheBenchmark.testMethod      28  thrpt  100  297432,240 ±  1186,920  ops/s
L3CacheBenchmark.testMethod      29  thrpt  100  169277,701 ± 25040,239  ops/s
L3CacheBenchmark.testMethod      30  thrpt  100  324230,899 ±  1579,103  ops/s
L3CacheBenchmark.testMethod      31  thrpt  100  193981,979 ± 12478,424  ops/s
L3CacheBenchmark.testMethod      32  thrpt  100   53761,030 ±   259,888  ops/s
L3CacheBenchmark.testMethod      33  thrpt  100  213585,493 ± 23543,671  ops/s
L3CacheBenchmark.testMethod      34  thrpt  100  325214,062 ±  1758,479  ops/s
L3CacheBenchmark.testMethod      35  thrpt  100  306652,634 ±  2237,818  ops/s
L3CacheBenchmark.testMethod      36  thrpt  100  297992,930 ±  1019,248  ops/s
L3CacheBenchmark.testMethod      37  thrpt  100  181671,812 ± 21984,441  ops/s
L3CacheBenchmark.testMethod      38  thrpt  100  321929,616 ±  1798,747  ops/s
L3CacheBenchmark.testMethod      39  thrpt  100  251587,385 ± 12292,670  ops/s
L3CacheBenchmark.testMethod      40  thrpt  100   49777,196 ±   227,620  ops/s
</code>```

As you can see, throughput is different, and the most striking difference is for arrays with size multiple of 8: speed degradation is almost 4 times. Also, for example, speed for array with size 37 Mb is almost twice less than for 38 Mb. I did not find any logical explanation of my findings.

P.S. Cpu i7 4700mq 6 Mb cache: http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7-4700MQ%20Mobile%20processor.html

What causes this behaviour?

答:
You are observing the effect of cache associativity.

Your CPU has 256 KB 8-way set associative L2 cache per core. It can store up to 256 KB / 64 cache lines where no more than 8 lines can have the same index bits.

Your benchmark loop writes to 1025 different addresses. However, depending on the stride, these addresses may fall into the small number of sets, resulting in collisions and evictions from the cache. That's exactly what happens in your case when stride (step) = 8191, 16383, 24575, etc.

To verify this theory, rerun JMH benchmark with -prof perfnorm option.

Here are the stats for size = 8 and size = 9:

```<code>L3CacheBenchmark.testMethod:CPI                      8  thrpt      1.173  #/op
L3CacheBenchmark.testMethod:L1-dcache-load-misses    8  thrpt   1048.088  #/op
L3CacheBenchmark.testMethod:L1-dcache-loads          8  thrpt   1073.767  #/op
L3CacheBenchmark.testMethod:L1-dcache-store-misses   8  thrpt   1049.491  #/op
L3CacheBenchmark.testMethod:L1-dcache-stores         8  thrpt   1060.069  #/op
L3CacheBenchmark.testMethod:L1-icache-load-misses    8  thrpt      1.209  #/op
L3CacheBenchmark.testMethod:LLC-load-misses          8  thrpt      0.082  #/op
L3CacheBenchmark.testMethod:LLC-loads                8  thrpt      1.399  #/op
L3CacheBenchmark.testMethod:LLC-store-misses         8  thrpt      0.077  #/op
L3CacheBenchmark.testMethod:LLC-stores               8  thrpt   1035.877  #/op
L3CacheBenchmark.testMethod:branch-misses            8  thrpt      1.234  #/op
L3CacheBenchmark.testMethod:branches                 8  thrpt   2096.674  #/op
L3CacheBenchmark.testMethod:cycles                   8  thrpt  13520.964  #/op
L3CacheBenchmark.testMethod:dTLB-load-misses         8  thrpt      0.057  #/op
L3CacheBenchmark.testMethod:dTLB-loads               8  thrpt   1086.355  #/op
L3CacheBenchmark.testMethod:dTLB-store-misses        8  thrpt      0.020  #/op
L3CacheBenchmark.testMethod:dTLB-stores              8  thrpt   1068.579  #/op
L3CacheBenchmark.testMethod:iTLB-load-misses         8  thrpt      0.044  #/op
L3CacheBenchmark.testMethod:iTLB-loads               8  thrpt      0.018  #/op
L3CacheBenchmark.testMethod:instructions             8  thrpt  11530.742  #/op
L3CacheBenchmark.testMethod:stalled-cycles-backend   8  thrpt   8315.437  #/op
L3CacheBenchmark.testMethod:stalled-cycles-frontend  8  thrpt  10359.447  #/op

L3CacheBenchmark.testMethod:CPI                      9  thrpt      0.871  #/op
L3CacheBenchmark.testMethod:L1-dcache-load-misses    9  thrpt   1055.973  #/op
L3CacheBenchmark.testMethod:L1-dcache-loads          9  thrpt   1068.958  #/op
L3CacheBenchmark.testMethod:L1-dcache-store-misses   9  thrpt   1045.480  #/op
L3CacheBenchmark.testMethod:L1-dcache-stores         9  thrpt   1057.328  #/op
L3CacheBenchmark.testMethod:L1-icache-load-misses    9  thrpt      1.108  #/op
L3CacheBenchmark.testMethod:LLC-load-misses          9  thrpt      0.174  #/op
L3CacheBenchmark.testMethod:LLC-loads                9  thrpt      0.304  #/op
L3CacheBenchmark.testMethod:LLC-store-misses         9  thrpt      0.045  #/op
L3CacheBenchmark.testMethod:LLC-stores               9  thrpt      0.350  #/op
L3CacheBenchmark.testMethod:branch-misses            9  thrpt      1.072  #/op
L3CacheBenchmark.testMethod:branches                 9  thrpt   2099.846  #/op
L3CacheBenchmark.testMethod:cycles                   9  thrpt  10041.724  #/op
L3CacheBenchmark.testMethod:dTLB-load-misses         9  thrpt      0.086  #/op
L3CacheBenchmark.testMethod:dTLB-loads               9  thrpt   1073.633  #/op
L3CacheBenchmark.testMethod:dTLB-store-misses        9  thrpt      0.045  #/op
L3CacheBenchmark.testMethod:dTLB-stores              9  thrpt   1054.587  #/op
L3CacheBenchmark.testMethod:iTLB-load-misses         9  thrpt      0.044  #/op
L3CacheBenchmark.testMethod:iTLB-loads               9  thrpt      0.037  #/op
L3CacheBenchmark.testMethod:instructions             9  thrpt  11529.996  #/op
L3CacheBenchmark.testMethod:stalled-cycles-backend   9  thrpt   3439.278  #/op
L3CacheBenchmark.testMethod:stalled-cycles-frontend  9  thrpt   6888.714  #/op
</code>```

The most notable is the difference in LLC-stores: 1035 for size = 8 and almost none for size = 9. This means that the data being stored does not fit into L2 cache and goes to L3.

BTW, your benchmark cannot measure the effect of L3 cache, since it touches only small amount of data (about 64 KB). In order to make a fair test, you'll need to read and write the whole range of the allocated array.

Body:
After reading this article I decided to check it on my laptop. The idea is create array with size [1..40] Mb, and then iterate over it 1024 times (e.g for array with size 1 step will be 1024, for array with 2 mb size step will be 2048 etc.). My code is:

public class L3CacheBenchmark {

    @State(Scope.Benchmark)
    public static class P {

        @Param({
                       "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                       "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
                       "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
                       "31", "32", "33", "34", "35", "36", "37", "38", "39", "40",
               })
        public int size;
    }

    @State(Scope.Thread)
    public static class ThreadData {

        byte[] array;
        int    len;

        @Setup
        public void setup(P p) {
            array = new byte[p.size * 1024 * 1024];
            len = array.length;
        }
    }

    @Benchmark
    public byte[] testMethod(ThreadData data) {
        int step = (data.len / 1024) - 1;
        for (int k = 0; k < data.len; k += step) {
            data.array[k] = 1;
        }
        return data.array;
    }

}

And results:

Benchmark                    (size)   Mode  Cnt       Score       Error  Units
L3CacheBenchmark.testMethod       1  thrpt  100  310521,031 ±  1124,590  ops/s
L3CacheBenchmark.testMethod       2  thrpt  100  331853,495 ±  1124,547  ops/s
L3CacheBenchmark.testMethod       3  thrpt  100  311499,659 ±   745,414  ops/s
L3CacheBenchmark.testMethod       4  thrpt  100  290270,382 ±  8501,690  ops/s
L3CacheBenchmark.testMethod       5  thrpt  100  212929,246 ± 14847,931  ops/s
L3CacheBenchmark.testMethod       6  thrpt  100  315968,138 ±  4454,210  ops/s
L3CacheBenchmark.testMethod       7  thrpt  100  209679,904 ± 26050,365  ops/s
L3CacheBenchmark.testMethod       8  thrpt  100   60409,187 ±   212,548  ops/s
L3CacheBenchmark.testMethod       9  thrpt  100  221290,756 ± 28970,586  ops/s
L3CacheBenchmark.testMethod      10  thrpt  100  322865,687 ±  1545,967  ops/s
L3CacheBenchmark.testMethod      11  thrpt  100  263153,747 ± 18497,624  ops/s
L3CacheBenchmark.testMethod      12  thrpt  100  298683,205 ±  1277,032  ops/s
L3CacheBenchmark.testMethod      13  thrpt  100  180984,220 ± 26611,649  ops/s
L3CacheBenchmark.testMethod      14  thrpt  100  324815,938 ±  1657,303  ops/s
L3CacheBenchmark.testMethod      15  thrpt  100  264965,412 ±  9335,923  ops/s
L3CacheBenchmark.testMethod      16  thrpt  100   58830,825 ±   291,412  ops/s
L3CacheBenchmark.testMethod      17  thrpt  100  255576,829 ±  7083,025  ops/s
L3CacheBenchmark.testMethod      18  thrpt  100  324174,133 ±  2247,157  ops/s
L3CacheBenchmark.testMethod      19  thrpt  100  212969,202 ± 18204,625  ops/s
L3CacheBenchmark.testMethod      20  thrpt  100  295246,470 ±  1224,817  ops/s
L3CacheBenchmark.testMethod      21  thrpt  100  251762,642 ± 23405,100  ops/s
L3CacheBenchmark.testMethod      22  thrpt  100  323196,428 ±  2245,465  ops/s
L3CacheBenchmark.testMethod      23  thrpt  100  254588,338 ± 23845,090  ops/s
L3CacheBenchmark.testMethod      24  thrpt  100   53373,580 ±   252,183  ops/s
L3CacheBenchmark.testMethod      25  thrpt  100  213220,459 ± 20440,716  ops/s
L3CacheBenchmark.testMethod      26  thrpt  100  322625,597 ±  2076,341  ops/s
L3CacheBenchmark.testMethod      27  thrpt  100  293643,720 ±  5260,010  ops/s
L3CacheBenchmark.testMethod      28  thrpt  100  297432,240 ±  1186,920  ops/s
L3CacheBenchmark.testMethod      29  thrpt  100  169277,701 ± 25040,239  ops/s
L3CacheBenchmark.testMethod      30  thrpt  100  324230,899 ±  1579,103  ops/s
L3CacheBenchmark.testMethod      31  thrpt  100  193981,979 ± 12478,424  ops/s
L3CacheBenchmark.testMethod      32  thrpt  100   53761,030 ±   259,888  ops/s
L3CacheBenchmark.testMethod      33  thrpt  100  213585,493 ± 23543,671  ops/s
L3CacheBenchmark.testMethod      34  thrpt  100  325214,062 ±  1758,479  ops/s
L3CacheBenchmark.testMethod      35  thrpt  100  306652,634 ±  2237,818  ops/s
L3CacheBenchmark.testMethod      36  thrpt  100  297992,930 ±  1019,248  ops/s
L3CacheBenchmark.testMethod      37  thrpt  100  181671,812 ± 21984,441  ops/s
L3CacheBenchmark.testMethod      38  thrpt  100  321929,616 ±  1798,747  ops/s
L3CacheBenchmark.testMethod      39  thrpt  100  251587,385 ± 12292,670  ops/s
L3CacheBenchmark.testMethod      40  thrpt  100   49777,196 ±   227,620  ops/s

As you can see, throughput is different, and the most striking difference is for arrays with size multiple of 8: speed degradation is almost 4 times. Also, for example, speed for array with size 37 Mb is almost twice less than for 38 Mb. I did not find any logical explanation of my findings.

P.S. Cpu i7 4700mq 6 Mb cache: http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7-4700MQ%20Mobile%20processor.html

What causes this behaviour?

Body:
You are observing the effect of cache associativity.

Your CPU has 256 KB 8-way set associative L2 cache per core. It can store up to 256 KB / 64 cache lines where no more than 8 lines can have the same index bits.

Your benchmark loop writes to 1025 different addresses. However, depending on the stride, these addresses may fall into the small number of sets, resulting in collisions and evictions from the cache. That's exactly what happens in your case when stride (step) = 8191, 16383, 24575, etc.

To verify this theory, rerun JMH benchmark with -prof perfnorm option.

Here are the stats for size = 8 and size = 9:

L3CacheBenchmark.testMethod:CPI                      8  thrpt      1.173  #/op
L3CacheBenchmark.testMethod:L1-dcache-load-misses    8  thrpt   1048.088  #/op
L3CacheBenchmark.testMethod:L1-dcache-loads          8  thrpt   1073.767  #/op
L3CacheBenchmark.testMethod:L1-dcache-store-misses   8  thrpt   1049.491  #/op
L3CacheBenchmark.testMethod:L1-dcache-stores         8  thrpt   1060.069  #/op
L3CacheBenchmark.testMethod:L1-icache-load-misses    8  thrpt      1.209  #/op
L3CacheBenchmark.testMethod:LLC-load-misses          8  thrpt      0.082  #/op
L3CacheBenchmark.testMethod:LLC-loads                8  thrpt      1.399  #/op
L3CacheBenchmark.testMethod:LLC-store-misses         8  thrpt      0.077  #/op
L3CacheBenchmark.testMethod:LLC-stores               8  thrpt   1035.877  #/op
L3CacheBenchmark.testMethod:branch-misses            8  thrpt      1.234  #/op
L3CacheBenchmark.testMethod:branches                 8  thrpt   2096.674  #/op
L3CacheBenchmark.testMethod:cycles                   8  thrpt  13520.964  #/op
L3CacheBenchmark.testMethod:dTLB-load-misses         8  thrpt      0.057  #/op
L3CacheBenchmark.testMethod:dTLB-loads               8  thrpt   1086.355  #/op
L3CacheBenchmark.testMethod:dTLB-store-misses        8  thrpt      0.020  #/op
L3CacheBenchmark.testMethod:dTLB-stores              8  thrpt   1068.579  #/op
L3CacheBenchmark.testMethod:iTLB-load-misses         8  thrpt      0.044  #/op
L3CacheBenchmark.testMethod:iTLB-loads               8  thrpt      0.018  #/op
L3CacheBenchmark.testMethod:instructions             8  thrpt  11530.742  #/op
L3CacheBenchmark.testMethod:stalled-cycles-backend   8  thrpt   8315.437  #/op
L3CacheBenchmark.testMethod:stalled-cycles-frontend  8  thrpt  10359.447  #/op

L3CacheBenchmark.testMethod:CPI                      9  thrpt      0.871  #/op
L3CacheBenchmark.testMethod:L1-dcache-load-misses    9  thrpt   1055.973  #/op
L3CacheBenchmark.testMethod:L1-dcache-loads          9  thrpt   1068.958  #/op
L3CacheBenchmark.testMethod:L1-dcache-store-misses   9  thrpt   1045.480  #/op
L3CacheBenchmark.testMethod:L1-dcache-stores         9  thrpt   1057.328  #/op
L3CacheBenchmark.testMethod:L1-icache-load-misses    9  thrpt      1.108  #/op
L3CacheBenchmark.testMethod:LLC-load-misses          9  thrpt      0.174  #/op
L3CacheBenchmark.testMethod:LLC-loads                9  thrpt      0.304  #/op
L3CacheBenchmark.testMethod:LLC-store-misses         9  thrpt      0.045  #/op
L3CacheBenchmark.testMethod:LLC-stores               9  thrpt      0.350  #/op
L3CacheBenchmark.testMethod:branch-misses            9  thrpt      1.072  #/op
L3CacheBenchmark.testMethod:branches                 9  thrpt   2099.846  #/op
L3CacheBenchmark.testMethod:cycles                   9  thrpt  10041.724  #/op
L3CacheBenchmark.testMethod:dTLB-load-misses         9  thrpt      0.086  #/op
L3CacheBenchmark.testMethod:dTLB-loads               9  thrpt   1073.633  #/op
L3CacheBenchmark.testMethod:dTLB-store-misses        9  thrpt      0.045  #/op
L3CacheBenchmark.testMethod:dTLB-stores              9  thrpt   1054.587  #/op
L3CacheBenchmark.testMethod:iTLB-load-misses         9  thrpt      0.044  #/op
L3CacheBenchmark.testMethod:iTLB-loads               9  thrpt      0.037  #/op
L3CacheBenchmark.testMethod:instructions             9  thrpt  11529.996  #/op
L3CacheBenchmark.testMethod:stalled-cycles-backend   9  thrpt   3439.278  #/op
L3CacheBenchmark.testMethod:stalled-cycles-frontend  9  thrpt   6888.714  #/op

The most notable is the difference in LLC-stores: 1035 for size = 8 and almost none for size = 9. This means that the data being stored does not fit into L2 cache and goes to L3.

BTW, your benchmark cannot measure the effect of L3 cache, since it touches only small amount of data (about 64 KB). In order to make a fair test, you'll need to read and write the whole range of the allocated array.


来源: stackexchange

问:
Are cores divded in OpenMP in nested loops?
Let's suppose that we have this code:

```<code>for(size_t i=0; i<5; i++){
  //do something expensive here
  for(size_t i=0; i<5; i++){
    //do somehting expensive here too
  }
}
</code>```

Let's suppose we have at least 25 physical cores. How can we exploit all of them? A collapse would be not possible because the first expensive computation. What would be the most efficient solution in this case?

答:
Just decouple the loops.  If your current code is

```<code>#pragma omp parallel for
for(int i = 0; i < 5; ++i)
{
  expensive_1(i);
  for(int j = 0; j < 5; ++j)
  {
    expensive_2(j);
  }
}
</code>```

then make it into this, possibly saving the results of expensive_1 if they are needed in expensive_2.

```<code>#pragma omp parallel for
for(int i = 0; i < 5; ++i)
{
  expensive_1(i);
}

#pragma omp parallel for collapse(2)
for(int i = 0; i < 5; ++i)
{
  for(int j = 0; j < 5; ++j)
  {
    expensive_2(j);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's suppose that we have this code:

for(size_t i=0; i<5; i++){
  //do something expensive here
  for(size_t i=0; i<5; i++){
    //do somehting expensive here too
  }
}

Let's suppose we have at least 25 physical cores. How can we exploit all of them? A collapse would be not possible because the first expensive computation. What would be the most efficient solution in this case?

Body:
Just decouple the loops.  If your current code is

#pragma omp parallel for
for(int i = 0; i < 5; ++i)
{
  expensive_1(i);
  for(int j = 0; j < 5; ++j)
  {
    expensive_2(j);
  }
}

then make it into this, possibly saving the results of expensive_1 if they are needed in expensive_2.

#pragma omp parallel for
for(int i = 0; i < 5; ++i)
{
  expensive_1(i);
}

#pragma omp parallel for collapse(2)
for(int i = 0; i < 5; ++i)
{
  for(int j = 0; j < 5; ++j)
  {
    expensive_2(j);
  }
}


问:
grep a particular string and print one column before match
I need to print the value of one column left after matching Protectedfor52weeks  or Protectedfor365days. Below is my line

```<code>completed Protectedfor52weeks failed Protectedfor365days
</code>```

For above line desired output is as below

```<code>completed failed
</code>```

答:
grep with lookahead

```<code>grep -oP '\S+\s(?=Protectedfor(52weeks|365days))' file
</code>```

check either or both matches on all lines.

Body:
I need to print the value of one column left after matching Protectedfor52weeks  or Protectedfor365days. Below is my line

completed Protectedfor52weeks failed Protectedfor365days

For above line desired output is as below

completed failed

Body:
grep with lookahead

grep -oP '\S+\s(?=Protectedfor(52weeks|365days))' file

check either or both matches on all lines.


问:
Set Mongoose query condition based on document’s attribute
I currently have a Mongoose Event document which has startTime, endTime, and duration attributes. I am trying to perform a query in a node.js file that grabs all Events where the event's start time is before the current time stamp, and the event's end time is after the current time stamp plus the duration of the event. Therefore, my query depends on being able to perform a calculation that uses an attribute (duration) from the events it is querying. Something along the lines of this:

```<code>    const eventQuery = Event.find(query);
    eventQuery.where('startTime').lte(currentTimeStamp);
    eventQuery.where('endTime').gte(currentTimeStamp + event.duration);
</code>```

However, I'm not sure what I should write instead of event.duration, as the event has not yet been pulled at this point and rather I want to incorporate each candidate event's duration in the DB into the query somehow. Please let me know if this is possible somehow!

答:
You cannot directly compare two fields in $match. Instead you can use following query to get the desired results</p>

```<code>db.events.aggregate(
{$project: {startTime: 1, endTime: 1,matches:
    {$cond: [{$and:[
            {$lt: ['$startTime',new Date()]},
            {$gt: ['$endTime', {$add: [new Date(), '$duration']}]}
    ]},1,0]}}},
{$match: {matches:1}}
)
</code>```

Body:
I currently have a Mongoose Event document which has startTime, endTime, and duration attributes. I am trying to perform a query in a node.js file that grabs all Events where the event's start time is before the current time stamp, and the event's end time is after the current time stamp plus the duration of the event. Therefore, my query depends on being able to perform a calculation that uses an attribute (duration) from the events it is querying. Something along the lines of this:

    const eventQuery = Event.find(query);
    eventQuery.where('startTime').lte(currentTimeStamp);
    eventQuery.where('endTime').gte(currentTimeStamp + event.duration);

However, I'm not sure what I should write instead of event.duration, as the event has not yet been pulled at this point and rather I want to incorporate each candidate event's duration in the DB into the query somehow. Please let me know if this is possible somehow!

Body:
You cannot directly compare two fields in $match. Instead you can use following query to get the desired results

db.events.aggregate(
{$project: {startTime: 1, endTime: 1,matches:
    {$cond: [{$and:[
            {$lt: ['$startTime',new Date()]},
            {$gt: ['$endTime', {$add: [new Date(), '$duration']}]}
    ]},1,0]}}},
{$match: {matches:1}}
)


问:
Returning `Maybe (Entity a)` from Esqueleto `LeftOuterJoin`
From a contrived config/models in a scaffolded site:

```<code>Inventory
  name        Text
  description Text
Container
  name        Text
ContainerSlot
  container   ContainerId
  item        InventoryId Maybe
</code>```

Now, using Esqueleto, I want to use LeftOuterJoin to get the slots in a container, with the actual inventory empty if it has not been assigned.

```<code>selectContainerSlots containerKey = do
  stuff <- select $ from $ \(cs `LeftOuterJoin` i) -> do
    on $ cs ^. ContainerSlotItem ==. just (i ^. InventoryId)
    where_ $ cs ^. ContainerSlotContainer ==. val containerKey
    return (cs, i)
  return $ uncurry buildStuff <$> stuff
</code>```

I would expect buildStuff to need the following signature due to the "outer" nature of the join:

```<code>buildStuff :: Entity ContainerSlot -> Maybe (Entity Inventory) -> Result
</code>```

but find that it needs the following:

```<code>buildStuff :: Entity ContainerSlot -> Entity Inventory -> Result
</code>```

Which causes runtime failures when (predictably) the the Inventory fields are filled with NULL values.

```<code>PersistMarshalError "field id: int64 Expected Integer, received: PersistNull"
</code>```

Is there a way to project the Entity Inventory as an Maybe (Entity Inventory)?

答:
This could probably be marked a duplicate of Outer Joins with Esqueleto; however the difference is in the projection.

When dealing with any outer joins, all tables which may come back null should have all projections done with the ?. syntax. This will force the table's entities to become Maybe (Entity a) So the solution to the above is

```<code>selectContainerSlots containerKey = do
  stuff <- select $ from $ \(cs `LeftOuterJoin` i) -> do
    on $ cs ^. ContainerSlotItem ==. i ?. InventoryId
    where_ $ cs ^. ContainerSlotContainer ==. val containerKey
    return (cs, i)
  return $ uncurry buildStuff <$> stuff
</code>```

Additionally, if more than one table is chained; e.g.

```<code>select $ from $ \(cs `LeftOuterJoin` (i `InnerJoin` is)) -> do
</code>```

Then both i and is (inventory SKU table) should be projected with that syntax:

```<code>  on $ i ?. InventoryId ==. is ?. InventorySkuItem
  on $ cs ^. ContainerSlotItem ==. i ?. InventoryId
</code>```

Body:
From a contrived config/models in a scaffolded site:

Inventory
  name        Text
  description Text
Container
  name        Text
ContainerSlot
  container   ContainerId
  item        InventoryId Maybe

Now, using Esqueleto, I want to use LeftOuterJoin to get the slots in a container, with the actual inventory empty if it has not been assigned.

selectContainerSlots containerKey = do
  stuff <- select $ from $ \(cs `LeftOuterJoin` i) -> do
    on $ cs ^. ContainerSlotItem ==. just (i ^. InventoryId)
    where_ $ cs ^. ContainerSlotContainer ==. val containerKey
    return (cs, i)
  return $ uncurry buildStuff <$> stuff

I would expect buildStuff to need the following signature due to the "outer" nature of the join:

buildStuff :: Entity ContainerSlot -> Maybe (Entity Inventory) -> Result

but find that it needs the following:

buildStuff :: Entity ContainerSlot -> Entity Inventory -> Result

Which causes runtime failures when (predictably) the the Inventory fields are filled with NULL values.

PersistMarshalError "field id: int64 Expected Integer, received: PersistNull"

Is there a way to project the Entity Inventory as an Maybe (Entity Inventory)?

Body:
This could probably be marked a duplicate of Outer Joins with Esqueleto; however the difference is in the projection.

When dealing with any outer joins, all tables which may come back null should have all projections done with the ?. syntax. This will force the table's entities to become Maybe (Entity a) So the solution to the above is

selectContainerSlots containerKey = do
  stuff <- select $ from $ \(cs `LeftOuterJoin` i) -> do
    on $ cs ^. ContainerSlotItem ==. i ?. InventoryId
    where_ $ cs ^. ContainerSlotContainer ==. val containerKey
    return (cs, i)
  return $ uncurry buildStuff <$> stuff

Additionally, if more than one table is chained; e.g.

select $ from $ \(cs `LeftOuterJoin` (i `InnerJoin` is)) -> do

Then both i and is (inventory SKU table) should be projected with that syntax:

  on $ i ?. InventoryId ==. is ?. InventorySkuItem
  on $ cs ^. ContainerSlotItem ==. i ?. InventoryId


问:
pass a static value to a controller from routes in laravel
i would like to pass a static value(variable or a static string) from route definition to a controller.
for example if consider the following route:

```<code>Route::get('/', [
      'uses' => '\Controllers\FoController@show',
      'as' => 'show'
]);
</code>```

i want to pass a variable(ex, $var1) to that, and then can access to that in the FoController constructor or other controller methods , so i don't like that variable's value shows in the url.
how can i do this? thanks...

答:
you can do like this.

```<code>Route::any('/home/createuser/{id}','HomeController@createuser');
</code>```

you can use {} operator for parameters.
in controller.

```<code>public function createuser($id){
//here you can use $id
}
</code>```

Body:
i would like to pass a static value(variable or a static string) from route definition to a controller.
for example if consider the following route:

Route::get('/', [
      'uses' => '\Controllers\FoController@show',
      'as' => 'show'
]);

i want to pass a variable(ex, $var1) to that, and then can access to that in the FoController constructor or other controller methods , so i don't like that variable's value shows in the url.
how can i do this? thanks...

Body:
you can do like this.

Route::any('/home/createuser/{id}','HomeController@createuser');

you can use {} operator for parameters.
in controller.

public function createuser($id){
//here you can use $id
}


问:
What is the sleep time between ticks in nodejs

Revised Question

I would like to know how the event loop of nodejs (whatever underlying implementation it is, may it be v8, libuv, libev) loops without exhausting the CPU. As the code example below shows, a sleep call is inserted in order to "free" the CPU and prevent the while loop using up the CPU. Since someone has already pointed out that it is not the case, then I would like to know what mechanism is employed in nodejs (or its underlying libraries) for such purpose?

Linking to relative sections of the source code is welcome. Thanks.

Original Question

I am asking about the nodejs internals: I would like to know if there is any sleep time between the ticks in nodejs' event loop.

In other words, I assume nodejs internals look like the code below, I would like to know what is the value of sometime, if any.

```<code>while(true) {
  for(event in queue) handleEvent(event);
  sleep(sometime);
}
</code>```

I made such assumption because I believe there must exist some kind of sleeping such that the while loop will not exhaust the CPU.

答: No there is no sleep, because that would be blocking.  This answer has a lot of details about the Node.js internals that are relevant to your question.</p>

Body:
Revised Question

I would like to know how the event loop of nodejs (whatever underlying implementation it is, may it be v8, libuv, libev) loops without exhausting the CPU. As the code example below shows, a sleep call is inserted in order to "free" the CPU and prevent the while loop using up the CPU. Since someone has already pointed out that it is not the case, then I would like to know what mechanism is employed in nodejs (or its underlying libraries) for such purpose?

Linking to relative sections of the source code is welcome. Thanks.

Original Question

I am asking about the nodejs internals: I would like to know if there is any sleep time between the ticks in nodejs' event loop.

In other words, I assume nodejs internals look like the code below, I would like to know what is the value of sometime, if any.

while(true) {
  for(event in queue) handleEvent(event);
  sleep(sometime);
}

I made such assumption because I believe there must exist some kind of sleeping such that the while loop will not exhaust the CPU.


问:
Array size in Java
What would be the memory size/space occupied in bits/bytes by array as follows.</p>

```<code>final String[] objects_user1={"1","10","100","1000","10000"};
</code>```

答: Did you try to Google it? Here is the first result of my Google search.</p>

ContentLicense: CC BY-SA 2.5

Title: Array size in Java

Body:
What would be the memory size/space occupied in bits/bytes by array as follows.

final String[] objects_user1={"1","10","100","1000","10000"};


答:
Continuing from the comment, while you can do it with grep and extended regex matching, or with sed and a back reference, the easy way is to read it into an array, and simply test as you iterate over the array:

```<code>#!/bin/bash

line="completed Protectedfor52weeks failed Protectedfor365days"

array=( $line )

for ((i = 0; i < ${#array[@]}; i++)); do
    if [[ (${array[i]} == Protectedfor52weeks || \
    ${array[i]} == Protectedfor365days) && \
    $i -lt $((${#array[@]} - 1)) ]]; then
        echo ${array[$((i+1))]}
    fi
done
</code>```

Example Use/Output

```<code>$ bash weeks.sh
failed
</code>```

Title: grep a particular string and print one column before match

Body:
Continuing from the comment, while you can do it with grep and extended regex matching, or with sed and a back reference, the easy way is to read it into an array, and simply test as you iterate over the array:

#!/bin/bash

line="completed Protectedfor52weeks failed Protectedfor365days"

array=( $line )

for ((i = 0; i < ${#array[@]}; i++)); do
    if [[ (${array[i]} == Protectedfor52weeks || \
    ${array[i]} == Protectedfor365days) && \
    $i -lt $((${#array[@]} - 1)) ]]; then
        echo ${array[$((i+1))]}
    fi
done

Example Use/Output

$ bash weeks.sh
failed


问:
javascript: How can I round a number to the nearest 10 cents?
I want to round '189.46' to 189.5

Here's an example if we are starting with the number as a string. Can someone please tell me why my method isn't working and what the correct way to do it is?

```<code>Math.round(parseFloat('189.46')).toFixed(1);
</code>```

答:
Multiply the number by 10 and round that (using the provided 189.46  - this will give 1895), and then divide by 10 to return to a decimal number( in this example 189.5).

Assuming that you are requiring this to take a value from an input - rather than a hard coded string / number - I have provided an input to enter the value and a button that triggers the rounding function on the click event.

I have also just put in a small basic number check to ensure that the inputted value is a number (note that all inputs will yield a string) but to check simply if a number has been put in - after parsing it using parseFloat - multiply it by 1 and compare the new value to the inputted value - if its not the same - its not a number.

I also popped in a method of clearing the text description as well when a new value is to be entered into the input box - jus cos' :)

function roundNumber(){
  var num = parseFloat(document.getElementById('numberInput').value);
  if(num * 1 !== num) {
    document.getElementById('numberDisplay').innerText = 'Not a Valid Number - try again';
    document.getElementById('numberInput').value = '';
  } else {
   var numRounded = (Math.round(num*10)/10).toFixed(1);
   document.getElementById('numberDisplay').innerText = 'Rounded number:   '+ numRounded;
   }
}

function clearText(){
  document.getElementById('numberInput').value = '';
  document.getElementById('numberDisplay').innerText = '';
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="numberInput" onclick="clearText()"/>
<button type = "button" id="inputButton" onclick="roundNumber()">Round Value</button>
<p id = "numberDisplay"><p></code>```

Body:
I want to round '189.46' to 189.5

Here's an example if we are starting with the number as a string. Can someone please tell me why my method isn't working and what the correct way to do it is?

Math.round(parseFloat('189.46')).toFixed(1);

Body:
Multiply the number by 10 and round that (using the provided 189.46  - this will give 1895), and then divide by 10 to return to a decimal number( in this example 189.5).

Assuming that you are requiring this to take a value from an input - rather than a hard coded string / number - I have provided an input to enter the value and a button that triggers the rounding function on the click event.

I have also just put in a small basic number check to ensure that the inputted value is a number (note that all inputs will yield a string) but to check simply if a number has been put in - after parsing it using parseFloat - multiply it by 1 and compare the new value to the inputted value - if its not the same - its not a number.

I also popped in a method of clearing the text description as well when a new value is to be entered into the input box - jus cos' :)

function roundNumber(){
  var num = parseFloat(document.getElementById('numberInput').value);
  if(num * 1 !== num) {
    document.getElementById('numberDisplay').innerText = 'Not a Valid Number - try again';
    document.getElementById('numberInput').value = '';
  } else {
   var numRounded = (Math.round(num*10)/10).toFixed(1);
   document.getElementById('numberDisplay').innerText = 'Rounded number:   '+ numRounded;
   }
}

function clearText(){
  document.getElementById('numberInput').value = '';
  document.getElementById('numberDisplay').innerText = '';
 }

<input type="text" id="numberInput" onclick="clearText()"/>
<button type = "button" id="inputButton" onclick="roundNumber()">Round Value</button>
<p id = "numberDisplay"><p>


问:
How to translate this matlab code to python(numpy)
Matlab code :

```<code> Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));
</code>```

The code I translate :

```<code> Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))
</code>```

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.

答:
It looks fine. Did you try to find what's the difference in the two results?
Two issues I can think of are indexing and type casting:
- MATLAB indexing starts with 1 whereas python starts with 0
- (alpha/(dx**2)) and (1/(dt**2)) : you could try making it (alpha./(dx**2)) and (1./(dt**2))</p>

Body:
Matlab code :

 Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));

The code I translate :

 Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.


问:
What's the difference between this function and the lambda?
```<code>#include<iostream>

using namespace std;

int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/
}
int main()
{
    cout << Foo() << endl;
    return 0;
}
</code>```

I'm fresh in C++, I encounter a situation above, I had review the chapter 10.3.2 to 10.3.3 of C++ Primer, where introduces the lambda expression.But it doesn't work for me, I'm also confused about the last annotation I list.

答:
Actuall, I didn't call my lambda because it lacks the call operator.
So, I fix it as:

```<code>return []() { return *(new int(666)); }();
</code>```

It works now.

I review the words from Chapter of 10.3.2 of C++ Primer "We call a lambda the same way we call funtion by using the call operator".

ContentLicense: CC BY-SA 4.0

Body:
#include<iostream>

using namespace std;

int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/
}
int main()
{
    cout << Foo() << endl;
    return 0;
}

I'm fresh in C++, I encounter a situation above, I had review the chapter 10.3.2 to 10.3.3 of C++ Primer, where introduces the lambda expression.But it doesn't work for me, I'm also confused about the last annotation I list.

Body:
Actuall, I didn't call my lambda because it lacks the call operator.
So, I fix it as:

return []() { return *(new int(666)); }();

It works now.

I review the words from Chapter of 10.3.2 of C++ Primer "We call a lambda the same way we call funtion by using the call operator".


问:
find nested array based on given value
```<code>var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);
</code>```

How to display one array from myarr? For example if I enter 002 in input box it should display: 002,"John",700000

答:
This is a classic example of Arrays inside an array.

If you want to display the entire array 002,"John",700000 then take an index of that array from the outer array.

e.g.

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

<p id="demo"></p>

<script>
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],[004,"Michel",600000],[005,"Stella",700000]);

//This will display your entire second array.
document.getElementById("demo").innerHTML = myarr[1];

</script>

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

If you want a lookup to try key-value data structure in which your id will be key and the entire object will be value.

e.g.
var obj = {key1: value1, key2: value2};

Title: find nested array based on given value

Body:
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);

How to display one array from myarr? For example if I enter 002 in input box it should display: 002,"John",700000

Body:
This is a classic example of Arrays inside an array.

If you want to display the entire array 002,"John",700000 then take an index of that array from the outer array.

e.g.

<html>
<body>

<p id="demo"></p>

<script>
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],[004,"Michel",600000],[005,"Stella",700000]);

//This will display your entire second array.
document.getElementById("demo").innerHTML = myarr[1];

</script>

</body>
</html>

If you want a lookup to try key-value data structure in which your id will be key and the entire object will be value.

e.g.
var obj = {key1: value1, key2: value2};


问:
How to count vowels and consonants in Python?
I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.

1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.

2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.

Here is what I have:

```<code>def main():
   user_input = input("Enter a string of vowels and consonants: ")
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   countConsonants(user_input, vowel_list)

def countVowels(user_input, vowel_list):
    user_input.lower()
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
            index += 1
            print ('Your input has', vowels , 'vowels.')

def countConsonants(user_input, vowel_list):
    user_input.lower()
    index = 0
    consonants = 0

    while index < len(user_input):
        if user_input[index] not in vowel_list:
            consonants += 1
            index += 1
            print ('Your input has' , consonants , 'consonants.')

main()
</code>```

Here is an IO:

```<code>Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.
</code>```

答:
I hope this is what you want. I replaced the while loop with the for loop and added a variable count_Consonant with a list of consonants.</p>

```<code>def countVowels(user_input, vowel_list):
    vowels = 0
    for i in vowel_list:
        if i in user_input:
            vowels+=1
            print ('Your input has {} vowels.'.format(vowels))

def countConsonants(user_input, count_Consonants):
    consonants = 0
    for i in count_Consonants:
        if i in user_input:
            consonants+=1
            print ('Your input has {} consonants.'.format(consonants))

def main():
   user_input = input("Enter a string of vowels and consonants:  ").lower()
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   count_Consonants = set(["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"])
   countConsonants(user_input, count_Consonants)

main()
</code>```

Body:
I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.

1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.

2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.

Here is what I have:

def main():
   user_input = input("Enter a string of vowels and consonants: ")
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   countConsonants(user_input, vowel_list)

def countVowels(user_input, vowel_list):
    user_input.lower()
    index = 0
    vowels = 0

    while index < len(user_input):
        if user_input[index] in vowel_list:
            vowels += 1
            index += 1
            print ('Your input has', vowels , 'vowels.')

def countConsonants(user_input, vowel_list):
    user_input.lower()
    index = 0
    consonants = 0

    while index < len(user_input):
        if user_input[index] not in vowel_list:
            consonants += 1
            index += 1
            print ('Your input has' , consonants , 'consonants.')

main()

Here is an IO:

Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.

Body:
I hope this is what you want. I replaced the while loop with the for loop and added a variable count_Consonant with a list of consonants.

def countVowels(user_input, vowel_list):
    vowels = 0
    for i in vowel_list:
        if i in user_input:
            vowels+=1
            print ('Your input has {} vowels.'.format(vowels))

def countConsonants(user_input, count_Consonants):
    consonants = 0
    for i in count_Consonants:
        if i in user_input:
            consonants+=1
            print ('Your input has {} consonants.'.format(consonants))

def main():
   user_input = input("Enter a string of vowels and consonants:  ").lower()
   vowel_list = set(['a','e','i','o','u'])
   countVowels(user_input, vowel_list)
   count_Consonants = set(["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"])
   countConsonants(user_input, count_Consonants)

main()


问:
euler project 23 - can't find the mistake in my code [Java]
After a week that I spent stuck on this problem I can't find where is my mistake.
the problem is:

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
  A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

so my code is:

```<code>package eulerProject;
import java.util.*;

import java.math.BigInteger;

public class e23 {

public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();

    BigInteger sum = BigInteger.ZERO;

    for (int i = 1; i <= 28123; i++) {

        if (!check(i))
            list.add(i);
    }

    System.out.println(list);

    for (int i = 0; i < list.size(); i++)
        sum = sum.add(BigInteger.valueOf(list.get(i)));

    System.out.println(sum);

}

public static boolean check(long z) {

    long y = 0;

    for (long i = 1; i <= z / 2; i++) {
        if (abundant(i)) {
            y = z - i;

            if (abundant(y)) {
                return true;
            }

            y = 0;
        }
    }

    return false;
}

public static long sum(long x) {
    long sum = 0;

    for (int i = 1; i < (Math.sqrt(x)); i++) {
        if (x % i == 0) {
            if (x / i == i) {
                sum += i;
            } else {
                sum = sum + i + (x / i);
            }
        }
    }

    sum = sum - x;
    return sum;
}

public static boolean abundant(long x) {
    if (sum(x) > x)
        return true;
    return false;
}
}
</code>```

I'll just explain the methods:

"sum" - sums all the proper divisors of a number.
(like number = 12 , so it sum: 1+2+3+4+6.)

"abundant" - just checks if the number is abundant or not by compairing the sum of his divisors and the number itself.

"check" - generating two numbers which their sum is the number we checking - and checking if the both numbers are abundant. if they are so returns true.

and the main just generating numbers until the max limit, adding to list and then I sum the list.

my answer is: 4190404.
the correct answer is: 4179871.

where is the mistake?

答:
Your sum method doesn't get the correct sum for perfect squares because your loop stops before the square root. For example, if you called sum(16), the loop would run up to i = 3 and stop, so 4 would not contribute to the sum.

Solution:

(I also fixed some inefficiencies.)

```<code>public static long sum(long x){
long sum = 1;
int sqrt = (int)Math.sqrt(x);

for (int i = 2; i <= sqrt; i++) {
    if (x % i == 0) {
        sum += i + (x/i);
    }
}
//checks if perfect square and subtracts out extra square root.
if(sqrt * sqrt == x) sum -= sqrt;

return sum;
}
</code>```

Body:
After a week that I spent stuck on this problem I can't find where is my mistake.
the problem is:

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
  A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

so my code is:

package eulerProject;
import java.util.*;

import java.math.BigInteger;

public class e23 {

public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();

    BigInteger sum = BigInteger.ZERO;

    for (int i = 1; i <= 28123; i++) {

        if (!check(i))
            list.add(i);
    }

    System.out.println(list);

    for (int i = 0; i < list.size(); i++)
        sum = sum.add(BigInteger.valueOf(list.get(i)));

    System.out.println(sum);

}

public static boolean check(long z) {

    long y = 0;

    for (long i = 1; i <= z / 2; i++) {
        if (abundant(i)) {
            y = z - i;

            if (abundant(y)) {
                return true;
            }

            y = 0;
        }
    }

    return false;
}

public static long sum(long x) {
    long sum = 0;

    for (int i = 1; i < (Math.sqrt(x)); i++) {
        if (x % i == 0) {
            if (x / i == i) {
                sum += i;
            } else {
                sum = sum + i + (x / i);
            }
        }
    }

    sum = sum - x;
    return sum;
}

public static boolean abundant(long x) {
    if (sum(x) > x)
        return true;
    return false;
}
}

I'll just explain the methods:

"sum" - sums all the proper divisors of a number.
(like number = 12 , so it sum: 1+2+3+4+6.)

"abundant" - just checks if the number is abundant or not by compairing the sum of his divisors and the number itself.

"check" - generating two numbers which their sum is the number we checking - and checking if the both numbers are abundant. if they are so returns true.

and the main just generating numbers until the max limit, adding to list and then I sum the list.

my answer is: 4190404.
the correct answer is: 4179871.

where is the mistake?

Body:
Your sum method doesn't get the correct sum for perfect squares because your loop stops before the square root. For example, if you called sum(16), the loop would run up to i = 3 and stop, so 4 would not contribute to the sum.

Solution:

(I also fixed some inefficiencies.)

public static long sum(long x){
long sum = 1;
int sqrt = (int)Math.sqrt(x);

for (int i = 2; i <= sqrt; i++) {
    if (x % i == 0) {
        sum += i + (x/i);
    }
}
//checks if perfect square and subtracts out extra square root.
if(sqrt * sqrt == x) sum -= sqrt;

return sum;
}


问:
How to center a google map marker with a smooth zoom (api V3)?
i'm using map.panTo() to have a nice smooth transition between the markers, when i click from a list of locations, but i can't see a similar methods for the zoom...I imagine something like setZoom(13, 1500) where 1500 is the duration...

any clue?

答:
The only native function to zoom so far is map.setZoom which does not let you change the speed.

If you want to set your map to the zoom level based on a set of markers you can do something like this:

```<code>var bounds : LatLngBounds = new LatLngBounds(southwestmarker.getLatLng(), northeastmarker.getLatLng());
bounds.extend(someMarker.getLatLng());
//some more extend() here
map.setZoom(map.getBoundsZoomLevel(bounds));
</code>```

Body:
The only native function to zoom so far is map.setZoom which does not let you change the speed.

If you want to set your map to the zoom level based on a set of markers you can do something like this:

var bounds : LatLngBounds = new LatLngBounds(southwestmarker.getLatLng(), northeastmarker.getLatLng());
bounds.extend(someMarker.getLatLng());
//some more extend() here
map.setZoom(map.getBoundsZoomLevel(bounds));


问:
Index Ruby on Rails Enums from 1 instead of 0
Ruby on Rails Enums automatically indexes starting at 0. I'd like to index these starting from 1. Is there any simple way to do this?</p>

答:
The easiest way is not to use an array at all. Enum is magical. It has the ability to act as a simple array, e.g.

```<code>enum status: ["bored", "busy", "working", "sleeping"]
</code>```

or a hash, based on how its declared

```<code>enum status: {bored: 1, busy: 2, working: 3, sleeping: 4}
</code>```

Just make sure in your migration you set a default status, it can be any number you prefer.

Body:
The easiest way is not to use an array at all. Enum is magical. It has the ability to act as a simple array, e.g.

enum status: ["bored", "busy", "working", "sleeping"]

or a hash, based on how its declared

enum status: {bored: 1, busy: 2, working: 3, sleeping: 4}

Just make sure in your migration you set a default status, it can be any number you prefer.


问:
Multiplying an option value by a fixed value
Using Excel 2010 I have a form that contains five option buttons in each of nine rows.  Each column, in which an option button can be selected, has a numeric value ranging from 5 -1.  Each row begins with a statement which also has a numeric value, which ranges from 10-1.  When an option button is selected, the value of that column is to be multiplied by the value of the row and the result entered in another column on the form.

Suggestions?

Thank you in advance.
JB

答:
Presuming that you have used ActiveX option buttons the following idea should do what you want.

Reserve 5 columns on your worksheet. In my test they were the cells H3:M3.

Now look for the LinkedCell property of your option buttons. Link No. 1 to H3, No. 2 to I3, No. 3 to J3 (whatever your corresponding columns are, but within the same row as your option buttons). Bear in mind that these are the numbers 1 to 5 which you want to use in multiplications.

In the cell where you want the result, enter this formula.

=MATCH(TRUE,$H3:$M3,0) * $A3

where 3 is the row where your linked option buttons are, and A is the value between 10 and 1 which you indicated you have somewhere.

The formula will create a total by multiplying a value between 1 and 5, depending upon which option button was clicked, with the value in column A. Copy the formulas down as required. Unfortunately, you will have to set the LinkedCell properties individually for each button.


问:
Unable to sort an Arraylist
Trying to print output as:

First max

First min

Second Max

Second min

Third Max ... and so on

This is my code:

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Arraylist1 {
public static void main(String args[]){
 List <Integer>list= new ArrayList <Integer> ( );
 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);
 for(int i=0;i<list.size();i++) {
  if(i%2==0){
    Object num=Collections.max(list);
    System.out.println(num);
    list.remove(num);
  }
 else if(i%2!=0)
    {
    Object num1=Collections.min(list);
    System.out.println(num1);
    list.remove(num1);
    }
}
}
}

 70
 20
 60
</code>```

Why it printing only first three numbers?

My expected output:

```<code> 70 20 60 30 50 40
</code>```

答:
Your problem is that your loop iterates until until reachig list.size().

But you keep decreasing that size on the one hand; but on the other hand, you keep re-computing that loop condition!

You have to assign that size to a helper variable like initialSize and compare against that fixed value instead!

Title: Unable to sort an Arraylist

Body:
Trying to print output as:

First max

First min

Second Max

Second min

Third Max ... and so on

This is my code:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Arraylist1 {
public static void main(String args[]){
 List <Integer>list= new ArrayList <Integer> ( );
 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);
 for(int i=0;i<list.size();i++) {
  if(i%2==0){
    Object num=Collections.max(list);
    System.out.println(num);
    list.remove(num);
  }
 else if(i%2!=0)
    {
    Object num1=Collections.min(list);
    System.out.println(num1);
    list.remove(num1);
    }
}
}
}

 70
 20
 60

Why it printing only first three numbers?

My expected output:

 70 20 60 30 50 40


问:
Could not find 'com.firebase:firebase-jobdispatcher'
I am trying to add Firebase Job Dispatcher to my project, but I am unable to build because of this error:

Gradle sync failed: Could not find
  com.firebase:firebase-jobdispatcher:[version]. Required by: project
  :[module]

My build.gradle file looks like this:

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            zipAlignEnabled true
        }
    }
}

repositories {
    mavenCentral()
    maven {url "https://clojars.org/repo/"}
}

dependencies {
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'

    compile 'com.firebase:firebase-jobdispatcher:0.5.2'

    compile 'com.facebook.stetho:stetho:1.4.2'

    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'

    compile 'frankiesardo:icepick:3.2.0'
    provided 'frankiesardo:icepick-processor:3.2.0'

    compile 'org.greenrobot:eventbus:3.0.0'

    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.android.support:support-v13:25.3.0'

    compile 'com.google.code.gson:gson:2.7'

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/volley.jar')
}
</code>```

Additionally, I have version 45 of the Google Repository and version 39 of Google Play Services installed via the SDK manager.

According to the documentation on the firebase-jobdispatcher Github page, this should be the only thing I need to add the dependency. My project does not rely on GCM, so I'm not sure what is going on. Is there something I'm missing here?

答:
Apparently, Gradle could not resolve the dependency using Maven Central alone. Adding JCenter to my list of repositories fixed the issue:</p>

```<code>repositories {
    jcenter()  // new
    mavenCentral()
    maven {url "https://clojars.org/repo/"}
}
</code>```

Body:
I am trying to add Firebase Job Dispatcher to my project, but I am unable to build because of this error:

Gradle sync failed: Could not find
  com.firebase:firebase-jobdispatcher:[version]. Required by: project
  :[module]

My build.gradle file looks like this:

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 2
        versionName "1.0.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            zipAlignEnabled true
        }
    }
}

repositories {
    mavenCentral()
    maven {url "https://clojars.org/repo/"}
}

dependencies {
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'

    compile 'com.firebase:firebase-jobdispatcher:0.5.2'

    compile 'com.facebook.stetho:stetho:1.4.2'

    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'

    compile 'frankiesardo:icepick:3.2.0'
    provided 'frankiesardo:icepick-processor:3.2.0'

    compile 'org.greenrobot:eventbus:3.0.0'

    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.android.support:support-v13:25.3.0'

    compile 'com.google.code.gson:gson:2.7'

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/volley.jar')
}

Additionally, I have version 45 of the Google Repository and version 39 of Google Play Services installed via the SDK manager.

According to the documentation on the firebase-jobdispatcher Github page, this should be the only thing I need to add the dependency. My project does not rely on GCM, so I'm not sure what is going on. Is there something I'm missing here?

Body:
Apparently, Gradle could not resolve the dependency using Maven Central alone. Adding JCenter to my list of repositories fixed the issue:

repositories {
    jcenter()  // new
    mavenCentral()
    maven {url "https://clojars.org/repo/"}
}


问:
The correct way of using %in% within apply function
New to R so have some basic and stupid questions. Hope that I could learn from all the experienced masters here and became someone who could be helpful to all other data experts as well in the near future.

My target is to check each row of test if id is listed in id_lag in the same row. My sample code is as follows:

```<code>test <- as.data.frame(matrix(NA,10,3))
names(test) <- c("Year","id","id_lag")
test[,1] <- c(2011,2012,2013,2010,2014,2015,2016,2010,2011,2012)
test[,2] <- c(76,560,342,7908,200,23,23,890,780,150)
test[,3] <- c("76,89","209,2000,400","342,333,234","908,888","","23","8097,5678","12","780,209","150,4504")

involved <- function(id,id_lag)
{
 a <- return(id %in% scan(what = "", sep = ",",text = id_lag) )
 return(a)
}

check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))
</code>```

I'm expecting a 1 by 10 list as TRUE or FALSE if it listed in this row or not. However, I'm getting a 10 by 10 matrix with TRUE or FALSE that scanned the entire list 10 times. Is there any way I can eliminate this apply function only scan through line rather than do the full scan of whole list? Or is there any better approach say data.tables etc that would work?

Thanks,

Anne

答:
apply(X, MARGIN, FUN, ...) applies a function across the rows of a matrix if MARGIN = 1 and across the columns if MARGIN = 2.

What you have done with

```<code>check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))
</code>```

is "call the function involved(test$id,test$id_lag) for each row of the text matrix". So you end up with a 10x10 matrix because you have called involved(test$id,test$id_lag) once for each of the 10 rows of test.

If you want to apply a function across a row while taking the elements of multiple columns as arguments for each function call, mapply() is a useful function. Perhaps something like:

```<code>mapply( function(x,y) involved(x,y), x = test$id, y = test$id_lag )
</code>```

Body:
New to R so have some basic and stupid questions. Hope that I could learn from all the experienced masters here and became someone who could be helpful to all other data experts as well in the near future.

My target is to check each row of test if id is listed in id_lag in the same row. My sample code is as follows:

test <- as.data.frame(matrix(NA,10,3))
names(test) <- c("Year","id","id_lag")
test[,1] <- c(2011,2012,2013,2010,2014,2015,2016,2010,2011,2012)
test[,2] <- c(76,560,342,7908,200,23,23,890,780,150)
test[,3] <- c("76,89","209,2000,400","342,333,234","908,888","","23","8097,5678","12","780,209","150,4504")

involved <- function(id,id_lag)
{
 a <- return(id %in% scan(what = "", sep = ",",text = id_lag) )
 return(a)
}

check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))

I'm expecting a 1 by 10 list as TRUE or FALSE if it listed in this row or not. However, I'm getting a 10 by 10 matrix with TRUE or FALSE that scanned the entire list 10 times. Is there any way I can eliminate this apply function only scan through line rather than do the full scan of whole list? Or is there any better approach say data.tables etc that would work?

Thanks,

Anne

Body:
apply(X, MARGIN, FUN, ...) applies a function across the rows of a matrix if MARGIN = 1 and across the columns if MARGIN = 2.

What you have done with

check <- apply(test, 1, function(x,y) involved(test$id,test$id_lag))

is "call the function involved(test$id,test$id_lag) for each row of the text matrix". So you end up with a 10x10 matrix because you have called involved(test$id,test$id_lag) once for each of the 10 rows of test.

If you want to apply a function across a row while taking the elements of multiple columns as arguments for each function call, mapply() is a useful function. Perhaps something like:

mapply( function(x,y) involved(x,y), x = test$id, y = test$id_lag )


问:
grep a particular string and print one column before match
I need to print the value of one column left after matching Protectedfor52weeks  or Protectedfor365days. Below is my line

```<code>completed Protectedfor52weeks failed Protectedfor365days
</code>```

For above line desired output is as below

```<code>completed failed
</code>```

答:
awk; iterating over the fields and printing the field before any of the desired words:

```<code>awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}'
</code>```

Example:

```<code>% awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}' <<<'completed Protectedfor52weeks failed Protectedfor365days'
completed
failed
</code>```

Body:
I need to print the value of one column left after matching Protectedfor52weeks  or Protectedfor365days. Below is my line

completed Protectedfor52weeks failed Protectedfor365days

For above line desired output is as below

completed failed

Body:
awk; iterating over the fields and printing the field before any of the desired words:

awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}'

Example:

% awk '{for(i=1; i<=NF; ++i) if ($i ~ /^Protectedfor(52weeks|365days)$/) print $(i-1)}' <<<'completed Protectedfor52weeks failed Protectedfor365days'
completed
failed


答:
```<code>for(int i=0;i<list.size();i++)
</code>```

You looping condition is incorrect.

You don't loop 6 times.

You only loop 3 times because the size changes as you remove an item from the list in each iteration.

So you probably want:

```<code>int max = list.size();

for(int i = 0; i < max; i++)
</code>```

That is you want to fix the loop to be the initial number of entries in the list.

Title: Unable to sort an Arraylist

Body:
for(int i=0;i<list.size();i++)

You looping condition is incorrect.

You don't loop 6 times.

You only loop 3 times because the size changes as you remove an item from the list in each iteration.

So you probably want:

int max = list.size();

for(int i = 0; i < max; i++)

That is you want to fix the loop to be the initial number of entries in the list.


问:
c++ pointer to member function using std::function
I know this has been asked multiple times, most of the answers are difficult for me to understand.
Could you please help me in figuring out what am I doing wrong ?

```<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <functional>

class A{
    public:
        A(double i){
            _b = i;
        }
        double square(double i){

            return i*i*_b;
        }

    private:
    double _i;
    double _b;
};

double cube(double (*objfunc)(double), double x){
    return objfunc(x)*x;
}

int main()
{
    double v = 2.0;
    A a(v);

    using std::placeholders::_1;
    std::function<double(double)> f_square = std::bind( &A::square, &a, _1 );
    double x = cube(f_square,3.0);
    std::cout << " x = " << x << std::endl;

}
</code>```

Thank you as always for your advice.

Given the class A and the cube function as they are how can I use the cube function in the main function ?

Update: Only way to do this would be to modify:

```<code>double cube(std::function<double(double)> objfunc, double x){
    return objfunc(x)*x;
}
</code>```

答:
Make cube take an std::function object instead of a function pointer.  Also get rid of the std::bind and use a lambda together with the magic of auto.

```<code>#include <iostream>
#include <functional>

class A
{
public:
  A(double i) : _b(i) {}
  double square(double i) { return i*i*_b; }
private:
  double _b;
};

double cube(std::function<double(double)> objfunc, double x)
{
  return objfunc(x)*x;
}

int main()
{
  double v = 2.0;
  A a(v);

  auto f_square = [&a] ( double x ) { return a.square(x); };
  double x = cube(f_square,3.0);
  std::cout << " x = " << x << std::endl;
}
</code>```

Body:
I know this has been asked multiple times, most of the answers are difficult for me to understand.
Could you please help me in figuring out what am I doing wrong ?

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <functional>

class A{
    public:
        A(double i){
            _b = i;
        }
        double square(double i){

            return i*i*_b;
        }

    private:
    double _i;
    double _b;
};

double cube(double (*objfunc)(double), double x){
    return objfunc(x)*x;
}

int main()
{
    double v = 2.0;
    A a(v);

    using std::placeholders::_1;
    std::function<double(double)> f_square = std::bind( &A::square, &a, _1 );
    double x = cube(f_square,3.0);
    std::cout << " x = " << x << std::endl;

}

Thank you as always for your advice.

Given the class A and the cube function as they are how can I use the cube function in the main function ?

Update: Only way to do this would be to modify:

double cube(std::function<double(double)> objfunc, double x){
    return objfunc(x)*x;
}

Body:
Make cube take an std::function object instead of a function pointer.  Also get rid of the std::bind and use a lambda together with the magic of auto.

#include <iostream>
#include <functional>

class A
{
public:
  A(double i) : _b(i) {}
  double square(double i) { return i*i*_b; }
private:
  double _b;
};

double cube(std::function<double(double)> objfunc, double x)
{
  return objfunc(x)*x;
}

int main()
{
  double v = 2.0;
  A a(v);

  auto f_square = [&a] ( double x ) { return a.square(x); };
  double x = cube(f_square,3.0);
  std::cout << " x = " << x << std::endl;
}


问:
how does work the creation of indexes when the index is part of a closure?
In the following code I'm confused about the line with the comment "here!":

```<code>var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}
</code>```

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

答:
Why the i value creates the indices of foo correctly:

In javascript a list is just an object underneath. Using the [] accessor on a variable creates a map from the contents of [] to an assigned value. You are mapping the key i to a function that returns the value of y.

Why the indexes for foo were created correctly having a closure over the i variable:

You are storing references to functions in the loop. If you were to do the following I believe you will get the result you expected:

```<code>foo[10]() // This will return 10.
</code>```

References:

Insert into array at non-existent index

Body:
In the following code I'm confused about the line with the comment "here!":

var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

Body:
Why the i value creates the indices of foo correctly:

In javascript a list is just an object underneath. Using the [] accessor on a variable creates a map from the contents of [] to an assigned value. You are mapping the key i to a function that returns the value of y.

Why the indexes for foo were created correctly having a closure over the i variable:

You are storing references to functions in the loop. If you were to do the following I believe you will get the result you expected:

foo[10]() // This will return 10.

References:

Insert into array at non-existent index


问:
JQuery Tabs & cookie plugins - 2 tabs highlighted
I'm using jquery with tabs plugin and the cookie plugin to remember the previously selected tab.
However, when the page is opened again it successfully remembers the last tab selected but then when a new tab is chosen both the new and the old one are highlighted.
When another is selected then it just highlights that one.

```<code>$("#tabs").tabs({ cookie: { name: 'selectedTab', expires: 300 }});
</code>```

Can anyone suggest a solution please?
Thanks

答:
http://jqueryui.com/demos/tabs/#cookie

Have you gone through this ?

Body:
I'm using jquery with tabs plugin and the cookie plugin to remember the previously selected tab.
However, when the page is opened again it successfully remembers the last tab selected but then when a new tab is chosen both the new and the old one are highlighted.
When another is selected then it just highlights that one.

$("#tabs").tabs({ cookie: { name: 'selectedTab', expires: 300 }});

Can anyone suggest a solution please?
Thanks


问:
I can't figure out how to limit user input to numbers and commas
my program asks the user to input a bunch of numbers with commas separating each number so like (1,2,3,-4,55.0,100). The only valid symbols being "0"-"9", "-", ".", and ",". I cant figure out how to limit the input to these symbols.

```<code>import java.util.Scanner;
import java.util.StringTokenizer;

public class Lab9Question2 {

public static void main(String[] args) {
    double total = 0.0;
    boolean askMore = true;
    Scanner Keyboard = new Scanner(System.in);

    while (askMore) {
        System.out.println("Enter a series of numbers separated only by
        commas or type QUIT to exit:");
        String input = Keyboard.nextLine();
        String tokens[] = input.split(",");
          for (String str : tokens)
          {
             total += Integer.parseInt(str);
          }
        System.out.println(total);

        if (input.equalsIgnoreCase("QUIT")){
            askMore = false;
        }

    }

    Keyboard.close();
}
}
</code>```

This is what I have so far, it still wont display invalid input when someone enters something that is not allowed.

```<code>boolean askMore = true;
    boolean inputValid = true;
    Scanner Keyboard = new Scanner(System.in);

    while (askMore) {
        total = 0.0;
        System.out.println("Enter a series of numbers separated only by
    commas or type QUIT to exit:");
        String input = Keyboard.nextLine();

        inputValid = input.matches("[0-9]+" + "," + ".");

        if (inputValid = false){
            System.out.println("Invalid input");
        }
</code>```

答:
There are two ways you can do this that come to mind:

You can put your System.out.println("Enter a series of numbers separated only by
    commas or type QUIT to exit:");
String input = Keyboard.nextline() in a loop. When the input is finished being entered, you use Regex to validate if the input is valid. If not, message and have user edit the input. If okay, move to input.Split()

Another option is to get the input on each keyup and recognize if the input is invalid. You can then highlight the input box border red or otherwise alert the user that their input is invalid.

Edit: Missed line of code in original answer, formatting.

Body:
my program asks the user to input a bunch of numbers with commas separating each number so like (1,2,3,-4,55.0,100). The only valid symbols being "0"-"9", "-", ".", and ",". I cant figure out how to limit the input to these symbols.

import java.util.Scanner;
import java.util.StringTokenizer;

public class Lab9Question2 {

public static void main(String[] args) {
    double total = 0.0;
    boolean askMore = true;
    Scanner Keyboard = new Scanner(System.in);

    while (askMore) {
        System.out.println("Enter a series of numbers separated only by
        commas or type QUIT to exit:");
        String input = Keyboard.nextLine();
        String tokens[] = input.split(",");
          for (String str : tokens)
          {
             total += Integer.parseInt(str);
          }
        System.out.println(total);

        if (input.equalsIgnoreCase("QUIT")){
            askMore = false;
        }

    }

    Keyboard.close();
}
}

This is what I have so far, it still wont display invalid input when someone enters something that is not allowed.

boolean askMore = true;
    boolean inputValid = true;
    Scanner Keyboard = new Scanner(System.in);

    while (askMore) {
        total = 0.0;
        System.out.println("Enter a series of numbers separated only by
    commas or type QUIT to exit:");
        String input = Keyboard.nextLine();

        inputValid = input.matches("[0-9]+" + "," + ".");

        if (inputValid = false){
            System.out.println("Invalid input");
        }


问:
How to secure requests or/and responds from server
I have AngularJS + Php application, developed an API in php which handles requests and retrieves data. The problem is that steal my data analysing requests.

Are there any ways to secure my data? Maybe I need to use using encryption on server and decryption on client-side of application? Are there any reliable ways to do it?

Data was collected by 4 employees for several months and I'm very concerned about the safety of my data.

答: May be, you must use https protocol?</p>

Body: May be, you must use https protocol?


问:
Understanding ReactJS Controlled form components
I am implementing the following code based on the following page: https://facebook.github.io/react/docs/forms.html

```<code>class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    let data = {
      isGoing: this.state.isGoing,
      numberOfGuests: this.state.numberofGuests
    }

    /* Send data in ajax request here */

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
</code>```

Some questions I have about it:

Why do we need to store the component values in state? Why not
just grab the values we need when the form is submitted as normally
would be done with standard JavaScript? The recommended way would seem to reload the render function for every single character typed in or deleted. To me this makes little sense.

Since the execution of setState is asynchronous and there may be a delay between this.setState() and actually accessing the state with this.state.numberOfGuests does this mean that this code may end up grabbing the state before it has been set? If so, why is this code being suggested in the official React docs? If not, why not?

答:
Why do we need to store the component values in state?

We don't really need to store the component values in state and it's perfectly fine to access those values on form submit.

However, storing the component values in state has its own advantages. The main reason behind this is to make React state as the single source of truth. When the state is updated (on handleInputChange method), React checks the components (or specifically the parts of components or sub-trees) which needs to be re-rendered.

Using this approach, React helps us to achieve what was earlier achieved via Two Way Binding helpers. In short:

```<code>Form updated -> handleInputChange -> state updated -> updated state passed to other components accessing it
</code>```

For example say, you have a <Card /> component which needs input from the user via a <Form /> component and you wish to display the information as the user types, then the best way would be update your state which would cause React to look for the sub-trees where it was accessed and re-render only those. Thus your <Card /> component will update itself as you type in the <Form />.

Also, React doesn't re-render everything for every single character typed but only those sub-trees which needs to reflect the text change. See the React diffing algorithm for how it is done. In this case, as you type in the characters in a particular field in the form, only those sub-trees in components will be re-rendered which display that field.

Execution of setState and asynchronous behavior

As mentioned by the React docs:

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for
  performance.

Because this.props and this.state may be updated asynchronously, you
  should not rely on their values for calculating the next state.

Your code should work fine since you're not relying on the previous state to calculate the next state and also you're accessing this.state in a different block. So your state updates should be reflected fine; however if you don't want to think about the state updates (or suspect that your code might pick up previous state), React docs also mention an alternative method (which is actually better) that accepts a function rather than an object:

```<code>this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));
</code>```

If you're still wondering when you can use the setState method safely, use it if other components don't rely on the state or when you don't need to persist the state (save in local storage or a server). When working with larger projects its always a good idea to make use of state containers to save yourself the hassle, like Redux.

Body:
I am implementing the following code based on the following page: https://facebook.github.io/react/docs/forms.html

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    let data = {
      isGoing: this.state.isGoing,
      numberOfGuests: this.state.numberofGuests
    }

    /* Send data in ajax request here */

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />

          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />

        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Some questions I have about it:

Why do we need to store the component values in state? Why not
just grab the values we need when the form is submitted as normally
would be done with standard JavaScript? The recommended way would seem to reload the render function for every single character typed in or deleted. To me this makes little sense.

Since the execution of setState is asynchronous and there may be a delay between this.setState() and actually accessing the state with this.state.numberOfGuests does this mean that this code may end up grabbing the state before it has been set? If so, why is this code being suggested in the official React docs? If not, why not?

Body:
Why do we need to store the component values in state?

We don't really need to store the component values in state and it's perfectly fine to access those values on form submit.

However, storing the component values in state has its own advantages. The main reason behind this is to make React state as the single source of truth. When the state is updated (on handleInputChange method), React checks the components (or specifically the parts of components or sub-trees) which needs to be re-rendered.

Using this approach, React helps us to achieve what was earlier achieved via Two Way Binding helpers. In short:

Form updated -> handleInputChange -> state updated -> updated state passed to other components accessing it

For example say, you have a <Card /> component which needs input from the user via a <Form /> component and you wish to display the information as the user types, then the best way would be update your state which would cause React to look for the sub-trees where it was accessed and re-render only those. Thus your <Card /> component will update itself as you type in the <Form />.

Also, React doesn't re-render everything for every single character typed but only those sub-trees which needs to reflect the text change. See the React diffing algorithm for how it is done. In this case, as you type in the characters in a particular field in the form, only those sub-trees in components will be re-rendered which display that field.

Execution of setState and asynchronous behavior

As mentioned by the React docs:

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for
  performance.

Because this.props and this.state may be updated asynchronously, you
  should not rely on their values for calculating the next state.

Your code should work fine since you're not relying on the previous state to calculate the next state and also you're accessing this.state in a different block. So your state updates should be reflected fine; however if you don't want to think about the state updates (or suspect that your code might pick up previous state), React docs also mention an alternative method (which is actually better) that accepts a function rather than an object:

this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

If you're still wondering when you can use the setState method safely, use it if other components don't rely on the state or when you don't need to persist the state (save in local storage or a server). When working with larger projects its always a good idea to make use of state containers to save yourself the hassle, like Redux.


问:
Use index of summation as the order of derivation
Given some function f, I want to compute the following sum using sympy:

In general I want to use the index of summation as the order of differentiation of the function but I could not find out how to do it with sympy.

答: If n is an known integer, you can use something like Add(*[diff(f(x), x, i) for i in range(n+1)]). For symbolic n or infinity, it isn't possible yet, as there is no way yet to represent derivatives of symbolic order.