问:
Short-circuit evaluation evaluating if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
The program is posted below:

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

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}
</code>```

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

```<code>        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496
</code>```

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.

答: In short, when you compare using OR,  evaluation is done until the 1st occurrence of TRUE. So only a=4 is assigned. Rest are still uninitialized. </p>

Body:
The program is posted below:

#include <stdio.h>

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.


来源: stackexchange

问:
AngularJS overlaps http.get results and limits them to 10 per page
This happens to be my first angularJS application that fetches data from newsapi and displays all the result in an infinite scrolling pattern.
I am getting data but not as expected, the new results overlap the previous ones and limits to 10 per page.

please advice if i am doing something wrong.

```<code><!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<body>
<div class="w3-container" ng-app="myApp" ng-controller="myCtrl">
<p>Today's News:</p>
<div class="w3-card-4" style="width:100px margin:20px" ng-repeat="x in
source">
<img src="{{x.urlToImage}}" style="width:100%">
<div class="w3-container w3-center">
<h2><a href="{{x.url}}" target="_blank">{{x.title}}</a></h2>
</div>
</div><br><br>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror",
"reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
for(var i=0; i<websites.length;i++){
$http.get("https://newsapi.org/v1/articles?source=" +websites[i]
+"&apiKey=f483fa2a3f714981afbee1a1996545b4")
.then(function(response) {
$scope.source = response.data.articles;
});
}
});
</script>

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

答:
You are overwriting $scope.source in each loop over the sources. If you need to get all sources you can push it to an array of sources:

```<code>app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror",
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.sources=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i]
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      $scope.sources.push(response.data.articles);
    });
  }
})
</code>```

Then, you can use the $scope.sources and iterate over each source.

If you need all articles merged in one array, you can use the concat() method for arrays:

```<code>app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror",
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.source=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i]
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      if (response.data.articles){
         $scope.source.concat(response.data.articles);
      }
    });
  }
})
</code>```

Now you have a $scope.source with all articles merged into one array.

ContentLicense: CC BY-SA 3.0

Body:
This happens to be my first angularJS application that fetches data from newsapi and displays all the result in an infinite scrolling pattern.
I am getting data but not as expected, the new results overlap the previous ones and limits to 10 per page.

please advice if i am doing something wrong.

<!DOCTYPE html>

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Today's News:

{{x.title}}

Body:
You are overwriting $scope.source in each loop over the sources. If you need to get all sources you can push it to an array of sources:

app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror",
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.sources=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i]
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      $scope.sources.push(response.data.articles);
    });
  }
})

Then, you can use the $scope.sources and iterate over each source.

If you need all articles merged in one array, you can use the concat() method for arrays:

app.controller('myCtrl', function($scope, $http) {
  var websites = ["the-times-of-india", "google-news", "bbc-news", "mirror",
    "reuters", "the-hindu", "the-new-york-times", "the-wall-street-journal"];
  $scope.source=[];
  for(var i=0; i<websites.length;i++){
    $http.get("https://newsapi.org/v1/articles?source=" +websites[i]
    +"&apiKey=f483fa2a3f714981afbee1a1996545b4")
    .then(function(response) {
      if (response.data.articles){
         $scope.source.concat(response.data.articles);
      }
    });
  }
})

Now you have a $scope.source with all articles merged into one array.


问:
How to drop_duplicates
I have raw data as following example. At instant t1, a variable has a value x1, this variable should be recorded at instant t2 if and only if its value is not equal to x1. There is a way to compare a value in dataframes in python with the previous value and delete it if it's the same. I tried follow function, but it doesn't work.Please help.

```<code>df
time                 Variable   Value
2014-07-11 19:50:20  Var1       10
2014-07-11 19:50:30  Var1       20
2014-07-11 19:50:40  Var1       20
2014-07-11 19:50:50  Var1       30
2014-07-11 19:50:60  Var1       20
2014-07-11 19:50:70  Var2       50
2014-07-11 19:50:80  Var2       60
2014-07-11 19:50:90  Var2       70
</code>```

Coding:

```<code>for y in df.time:
    for x in df.Value:
        if y == y:
            if x == x:
                df1 = df.drop_duplicates(subset = ['time', 'Variable', 'Value'], keep=False)
            else:
                df1 = df.drop_duplicates(['time', 'Variable', 'Value'])
</code>```

Expected output:

```<code>df
time                 Variable   Value
2014-07-11 19:50:20  Var1       10
2014-07-11 19:50:30  Var1       20
2014-07-11 19:50:50  Var1       30
2014-07-11 19:50:60  Var1       20
2014-07-11 19:50:70  Var2       50
2014-07-11 19:50:80  Var2       60
2014-07-11 19:50:90  Var2       70
</code>```

Title: How to drop_duplicates

Body:
I have raw data as following example. At instant t1, a variable has a value x1, this variable should be recorded at instant t2 if and only if its value is not equal to x1. There is a way to compare a value in dataframes in python with the previous value and delete it if it's the same. I tried follow function, but it doesn't work.Please help.

df
time                 Variable   Value
2014-07-11 19:50:20  Var1       10
2014-07-11 19:50:30  Var1       20
2014-07-11 19:50:40  Var1       20
2014-07-11 19:50:50  Var1       30
2014-07-11 19:50:60  Var1       20
2014-07-11 19:50:70  Var2       50
2014-07-11 19:50:80  Var2       60
2014-07-11 19:50:90  Var2       70

Coding:

for y in df.time:
    for x in df.Value:
        if y == y:
            if x == x:
                df1 = df.drop_duplicates(subset = ['time', 'Variable', 'Value'], keep=False)
            else:
                df1 = df.drop_duplicates(['time', 'Variable', 'Value'])

Expected output:

df
time                 Variable   Value
2014-07-11 19:50:20  Var1       10
2014-07-11 19:50:30  Var1       20
2014-07-11 19:50:50  Var1       30
2014-07-11 19:50:60  Var1       20
2014-07-11 19:50:70  Var2       50
2014-07-11 19:50:80  Var2       60
2014-07-11 19:50:90  Var2       70

Body:
df.drop_duplicates(subset=['Variable','Value'],keep='first')
#                time Variable  Value
#2014-07-11  19:50:20     Var1     10
#2014-07-11  19:50:30     Var1     20
#2014-07-11  19:50:50     Var2     30
#2014-07-11  19:50:60     Var2     40
#2014-07-11  19:50:70     Var2     50


问:
Mysql Union All & order by
I have 3 tables

table member

```<code>id   |   type
1    |    A
2    |    B
3    |    A
</code>```

table commission A

```<code>id   |  member_id   |     date     |   amount   |
1    |     1        |  2017-06-06  |   30.00    |
2    |     2        |  2017-06-18  |   20.00    |
3    |     1        |  2017-06-21  |   10.00    |
4    |     3        |  2017-06-23  |   30.00    |
5    |     3        |  2017-06-27  |   30.00    |
</code>```

table commission B

```<code>id   |  member_id   |     date     |   amount   |
1    |     2        |  2017-06-05  |   30.00    |
2    |     2        |  2017-06-13  |   30.00    |
3    |     1        |  2017-06-22  |   30.00    |
4    |     3        |  2017-06-22  |   30.00    |
5    |     1        |  2017-06-23  |   30.00    |
</code>```

i want result to show only member type A, and order by date

```<code>id  |     date       |   member id   |    from
1   |   2017-06-06   |      1        |   table A
3   |   2017-06-21   |      1        |   table A
3   |   2017-06-22   |      1        |   table B
4   |   2017-06-22   |      3        |   table B
5   |   2017-06-23   |      1        |   table B
</code>```

and total amount = 130

I tried this:

```<code>select member_id, date, amount
from commission A
union all
select member_id, date, amount
from commission B
order by date asc
</code>```

But I couldn't select only members of type A: my query shows all members' results.

How should I do it?

答:
You need to join the members table in order to filter on the type:

```<code>select      c.*
from        member m
inner join (
            select id, member_id, `date`, amount, 'table A' `from`
            from   commissionA
            union all
            select id, member_id, `date`, amount, 'table B' `from`
            from   commissionB
           ) c
        on  m.id = c.member_id
where       m.type = 'A'
order by    c.`date` asc
</code>```

NB: I would avoid names like date and from, since they have special meanings.

To get the total in an additional row, group by all the fields (except amount), and add the with rollup clause. Finally, filter out any subtotals that are generated:

```<code>select *
from   (
    select      c.id, c.member_id, c.`date`, sum(c.amount) amount, c.`from`
    from        member m
    inner join (
                select id, member_id, `date`, amount, 'table A' `from`
                from   commissionA
                union all
                select id, member_id, `date`, amount, 'table B' `from`
                from   commissionB
               ) c
            on  m.id = c.member_id
    where       m.type = 'A'
    group by    c.id, c.member_id, c.`date`, c.`from` with rollup) base
where       id is null or `from` is not null;
order by    `date` asc
</code>```

Title: Mysql Union All & order by

Body:
I have 3 tables

table member

id   |   type
1    |    A
2    |    B
3    |    A

table commission A

id   |  member_id   |     date     |   amount   |
1    |     1        |  2017-06-06  |   30.00    |
2    |     2        |  2017-06-18  |   20.00    |
3    |     1        |  2017-06-21  |   10.00    |
4    |     3        |  2017-06-23  |   30.00    |
5    |     3        |  2017-06-27  |   30.00    |

table commission B

id   |  member_id   |     date     |   amount   |
1    |     2        |  2017-06-05  |   30.00    |
2    |     2        |  2017-06-13  |   30.00    |
3    |     1        |  2017-06-22  |   30.00    |
4    |     3        |  2017-06-22  |   30.00    |
5    |     1        |  2017-06-23  |   30.00    |

i want result to show only member type A, and order by date

id  |     date       |   member id   |    from
1   |   2017-06-06   |      1        |   table A
3   |   2017-06-21   |      1        |   table A
3   |   2017-06-22   |      1        |   table B
4   |   2017-06-22   |      3        |   table B
5   |   2017-06-23   |      1        |   table B

and total amount = 130

I tried this:

select member_id, date, amount
from commission A
union all
select member_id, date, amount
from commission B
order by date asc

But I couldn't select only members of type A: my query shows all members' results.

How should I do it?

Body:
You need to join the members table in order to filter on the type:

select      c.*
from        member m
inner join (
            select id, member_id, `date`, amount, 'table A' `from`
            from   commissionA
            union all
            select id, member_id, `date`, amount, 'table B' `from`
            from   commissionB
           ) c
        on  m.id = c.member_id
where       m.type = 'A'
order by    c.`date` asc

NB: I would avoid names like date and from, since they have special meanings.

To get the total in an additional row, group by all the fields (except amount), and add the with rollup clause. Finally, filter out any subtotals that are generated:

select *
from   (
    select      c.id, c.member_id, c.`date`, sum(c.amount) amount, c.`from`
    from        member m
    inner join (
                select id, member_id, `date`, amount, 'table A' `from`
                from   commissionA
                union all
                select id, member_id, `date`, amount, 'table B' `from`
                from   commissionB
               ) c
            on  m.id = c.member_id
    where       m.type = 'A'
    group by    c.id, c.member_id, c.`date`, c.`from` with rollup) base
where       id is null or `from` is not null;
order by    `date` asc


问:
"Incorrect syntax near '.'." when using "insert into select" statement
Hello friends i came here waiting for your help, i wan reading similar error in this site but nothing useful for me, i am using "insert into select" statement but something is wrong i can't find the mistake, i think is problem with aliases of the tables but if i write tableName.ColumName i get the same error i am almost crazy,
here is my Code:

```<code>Dim sqlventa As New SqlCommand
        Form2.conexionLocal.Open()
        Try
            sqlventa.CommandText = ("Insert into Ventas (Codigo_Consejera, Venta_Acumulada)" _
                           & "select T0.Codigo_Consejera, SUM(T1.Precio_Articulo) as ""Venta_Acumulada""" _
                           & "From Transacciones as T0 inner join Detalle as T1" _
                           & "On T0.Pedido_numero = T1.Pedido_numero" _
                           & "Where month(T0.Fecha) = '" & mes & "'and year(T0.Fecha)='" & year & "' Group by T0.Codigo_Consejera")
            sqlventa.Connection = Form2.conexionLocal
            sqlventa.ExecuteNonQuery()
            MessageBox.Show("ventas acumuladas calculadas con exito")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Form2.conexionLocal.Close()
        End Try
</code>```

Thanks

答:
When you are building the SQL, your lines neither end with, nor egin with a space, so they will run together:

Insert into Ventas (Codigo_Consejera, Venta_Acumulada)select T0.Codigo_Consejera, SUM(T1.Precio_Articulo) as "Venta_Acumulada"From Transacciones as T0 inner join Detalle as T1On T0.Pedido_numero = T1.Pedido_numeroWhere month(T0.Fecha) =etc

so you have T1On was the alias of Detalle and no ON for your inner join.

to fix, end each line of the string with a space:

```<code> sqlventa.CommandText = ("Insert into Ventas (Codigo_Consejera, Venta_Acumulada) " _
 '                                                                   space here ^
</code>```

Body:
Hello friends i came here waiting for your help, i wan reading similar error in this site but nothing useful for me, i am using "insert into select" statement but something is wrong i can't find the mistake, i think is problem with aliases of the tables but if i write tableName.ColumName i get the same error i am almost crazy,
here is my Code:

Dim sqlventa As New SqlCommand
        Form2.conexionLocal.Open()
        Try
            sqlventa.CommandText = ("Insert into Ventas (Codigo_Consejera, Venta_Acumulada)" _
                           & "select T0.Codigo_Consejera, SUM(T1.Precio_Articulo) as ""Venta_Acumulada""" _
                           & "From Transacciones as T0 inner join Detalle as T1" _
                           & "On T0.Pedido_numero = T1.Pedido_numero" _
                           & "Where month(T0.Fecha) = '" & mes & "'and year(T0.Fecha)='" & year & "' Group by T0.Codigo_Consejera")
            sqlventa.Connection = Form2.conexionLocal
            sqlventa.ExecuteNonQuery()
            MessageBox.Show("ventas acumuladas calculadas con exito")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Form2.conexionLocal.Close()
        End Try

Thanks

Body:
When you are building the SQL, your lines neither end with, nor egin with a space, so they will run together:

Insert into Ventas (Codigo_Consejera, Venta_Acumulada)select T0.Codigo_Consejera, SUM(T1.Precio_Articulo) as "Venta_Acumulada"From Transacciones as T0 inner join Detalle as T1On T0.Pedido_numero = T1.Pedido_numeroWhere month(T0.Fecha) =etc

so you have T1On was the alias of Detalle and no ON for your inner join.

to fix, end each line of the string with a space:

 sqlventa.CommandText = ("Insert into Ventas (Codigo_Consejera, Venta_Acumulada) " _
 '                                                                   space here ^


问:
Build boost libraries for sh4 arhitecture
I have the following problem. I need to buld some boost libraries for sh4 platform. I'm trying to use boost.build tool for this aim. I have made for desktop and all are okey - it seems I'm doing all correctly for x86. But for sh4 does not work. I heard that this may not be trivial. Can you give advice?

I have corresponding toolchain and etc...

答:
It seems I have found where was my mistake. In user-config.jam file I made mistake when defined rule for toolchain:
using gcc : 4.8.2 : /opt/STM/STLinux-2.3/devkit/sh4/bin - that is path to the toolchain directory. Instead of I should write full path to the executable file:
should be using gcc : 4.8.2 : /opt/STM/STLinux-2.3/devkit/sh4/bin/sh4-linux-g++


问:
sql in oracle to find ratio with grouping by a column
Can anyone please help me to find the following by using a sql in oracle

```<code>Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA
</code>```

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

```<code>Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1
</code>```

答:
When functions exist that do exactly what you need, it is best to use those functions. In this case, the function is RATIO_TO_REPORT. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

```<code>select   columnA, columnB,
         ratio_to_report(columnB) over (partition by columnA) as ratio
from     tablex
order by columnA  --   if needed
;
</code>```

Body:
Can anyone please help me to find the following by using a sql in oracle

Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1

Body:
When functions exist that do exactly what you need, it is best to use those functions. In this case, the function is RATIO_TO_REPORT. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

select   columnA, columnB,
         ratio_to_report(columnB) over (partition by columnA) as ratio
from     tablex
order by columnA  --   if needed
;


问:
How to integrate bootstrap template to cakephp 3.x
Copied css, js and relevant file to webroot folder. Then call css and js file to src->Template->Layout->default.php  i.e.

        <?= $this->Html->charset() ?>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <?= $cakeDescription ?>:
            <?= $this->fetch('title') ?>
        </title>
        <?= $this->Html->meta('icon') ?>

        <?= $this->Html->css('base.css') ?>
        <?= $this->Html->css('cake.css') ?>

        <?= $this->Html->css('bootstrap.min') ?>
        <?= $this->Html->css('freelancer.min') ?>

        <?= $this->Html->script('bootstrap.min') ?>
        <?= $this->Html->script('freelancer.min') ?>
        <?= $this->Html->script('contact_me') ?>
        <?= $this->Html->script('jqBootstrapValidation') ?>

        <?= $this->fetch('meta') ?>
        <?= $this->fetch('css') ?>
        <?= $this->fetch('script') ?>

    ```

After including these file, css is not working properly. As I am new to here Please somebody guide me the proper way to include the bootstrap template in a cakephp 3 project.

答:
It's not src->Template->Layout->default.php may be it is src->Template->Layout->default.ctp You have to use Like this format.

```<code><?php echo $this->Html->charset(); ?>
<?= echo $this->Html->charset() ?>
<?= echo $this->Html->meta('icon') ?>
</code>```

and so on

Body:
Copied css, js and relevant file to webroot folder. Then call css and js file to src->Template->Layout->default.php  i.e.

        <?= $this->Html->charset() ?>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <?= $cakeDescription ?>:
            <?= $this->fetch('title') ?>
        </title>
        <?= $this->Html->meta('icon') ?>

        <?= $this->Html->css('base.css') ?>
        <?= $this->Html->css('cake.css') ?>

        <?= $this->Html->css('bootstrap.min') ?>
        <?= $this->Html->css('freelancer.min') ?>

        <?= $this->Html->script('bootstrap.min') ?>
        <?= $this->Html->script('freelancer.min') ?>
        <?= $this->Html->script('contact_me') ?>
        <?= $this->Html->script('jqBootstrapValidation') ?>

        <?= $this->fetch('meta') ?>
        <?= $this->fetch('css') ?>
        <?= $this->fetch('script') ?>

After including these file, css is not working properly. As I am new to here Please somebody guide me the proper way to include the bootstrap template in a cakephp 3 project.

Body:
It's not src->Template->Layout->default.php may be it is src->Template->Layout->default.ctp You have to use Like this format.

<?php echo $this->Html->charset(); ?>
<?= echo $this->Html->charset() ?>
<?= echo $this->Html->meta('icon') ?>

and so on


问:
Non-resolvable parent POM using Maven 3.0.3 and relativePath notation
After migrating to Mavent 3.0.3 Parent poms in several Projects cannot be resolved anymore.

The Projects are structured in a default manner, so I set
parent.relativePath to "../pom.xml"

```<code>superpom (located in repository)
|-rootpom (located locally: no error)
|-|-parentpom (located locally: error resolving parent)
|-|-|-module1 (located locally: error resolving parent)
|-|-|-module2 (located locally: error resolving parent)
|-|-|-module3 (located locally: error resolving parent)
|-|-|-module4 (located locally: error resolving parent)
</code>```

The Error...

Non-resolvable parent POM for myGroup:myArtifactId:1.0:  Failure to
find myGroup:myParentArtifactId:1.0 in
http://myRepo.net/archiva/repository/maven2 was cached in the local
repository, resollution will not be reattempted until the update
interval of maven2 has elapsed or updates are forced and
'parent.relativePath' points at wrong local POM @
myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml, line
x, column y -> [Help 2]

... seems to indicate that the pom was searched for in the repository, so I wonder why the pom was not found locally before looked elsewhere.

I have read that maven3 might get confused when several repositories are defined in the settings.xml, but that was always when searching for a pom inside repositories and not locally.

update

Up until now we did execute the maven build on the parent-project level (parentpom) - a fact which I did not know was important, since maven2 completed successfully until now.

When using maven3 this seems to be of importance.
When executing maven3 on the root-project level (rootpom) the build finishes successfully.
So my immediate problem is solved.

Since I don't necessarily want to answer my own question maybe
someone can explain why maven3 behaves this way now or why the old
approach was wrong.

答:
```<code><parent>
        <groupId>com.test.vaquar.khan</groupId>
        <artifactId>vk-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../projectname/pom.xml</relativePath>
    </parent>
</code>```

Add following line in parent

```<code><relativePath>../projectname/pom.xml</relativePath>
</code>```

You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path

ContentLicense: CC BY-SA 4.0

Body:
After migrating to Mavent 3.0.3 Parent poms in several Projects cannot be resolved anymore.

The Projects are structured in a default manner, so I set
parent.relativePath to "../pom.xml"

superpom (located in repository)
|-rootpom (located locally: no error)
|-|-parentpom (located locally: error resolving parent)
|-|-|-module1 (located locally: error resolving parent)
|-|-|-module2 (located locally: error resolving parent)
|-|-|-module3 (located locally: error resolving parent)
|-|-|-module4 (located locally: error resolving parent)

The Error...

Non-resolvable parent POM for myGroup:myArtifactId:1.0:  Failure to
find myGroup:myParentArtifactId:1.0 in
http://myRepo.net/archiva/repository/maven2 was cached in the local
repository, resollution will not be reattempted until the update
interval of maven2 has elapsed or updates are forced and
'parent.relativePath' points at wrong local POM @
myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml, line
x, column y -> [Help 2]

... seems to indicate that the pom was searched for in the repository, so I wonder why the pom was not found locally before looked elsewhere.

I have read that maven3 might get confused when several repositories are defined in the settings.xml, but that was always when searching for a pom inside repositories and not locally.

update

Up until now we did execute the maven build on the parent-project level (parentpom) - a fact which I did not know was important, since maven2 completed successfully until now.

When using maven3 this seems to be of importance.
When executing maven3 on the root-project level (rootpom) the build finishes successfully.
So my immediate problem is solved.

Since I don't necessarily want to answer my own question maybe
someone can explain why maven3 behaves this way now or why the old
approach was wrong.

Body:
<parent>
        <groupId>com.test.vaquar.khan</groupId>
        <artifactId>vk-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../projectname/pom.xml</relativePath>
    </parent>

Add following line in parent

<relativePath>../projectname/pom.xml</relativePath>

You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path


问:
Adding user to group after running New-ADUser
So I'm coming tot he end of my first powershell project, I have been creating a script to import users into active directory from a CSV file containing only first and surnames.

```<code>Import-Csv users.csv |
    select Surname,
        @{n='GivenName';e={$_.'FirstName'}},
        @{n='samaccountname';e={$_.FirstName.substring(0,2) + $_.Surname}},
        @{n='UserPrincipalName';e={$_.FirstName.substring(0,2) + $_.Surname}},
        @{n='Name';e={$_.'FirstName' + ' ' + $_.'Surname'}} |
    New-ADUser -Enabled $true -AccountPassword (ConvertTo-SecureString -AsPlainText "Password1" -Force) -ChangePasswordAtLogon $true -Path "OU=Intake 20XX,OU=Students,OU=Ravenloft users,DC=RAVENLOFT,DC=test" -ProfilePath {"\\TESTSVR\Profiles$\Intake20XX\" +$_.SamAccountName} -HomeDrive "D:" -HomeDirectory {"\\TESTSVR\Work$\Intake20XX\" +$_.SamAccountName}
</code>```

Now my last job for this would be to add all of these new users to a group called StudentGroup, I understand there is no parameter in new-aduser to edit the "Member of" field in AD. So what would be the best way to go about doing this?

答:
I prefer to do this on two separate lines

```<code>New-ADUser ...
Add-ADGroupMember -Identity "name_of_group" -Members "username"
</code>```

If you want to one line it, credit goes to Mathias's comment  (using -PassThru)

```<code>New-ADUser ... -PassThru | % {Add-ADGroupMember -Identity "DN of StudentGroup" -Members $_}
</code>```

How you fit that into your script is up to you

-Members can accept an array or a single string of username

```<code>New-ADUser ...
Add-ADGroupMember -Identity "name_of_group" -Members @("username1","username2")
</code>```

Body:
So I'm coming tot he end of my first powershell project, I have been creating a script to import users into active directory from a CSV file containing only first and surnames.

Import-Csv users.csv |
    select Surname,
        @{n='GivenName';e={$_.'FirstName'}},
        @{n='samaccountname';e={$_.FirstName.substring(0,2) + $_.Surname}},
        @{n='UserPrincipalName';e={$_.FirstName.substring(0,2) + $_.Surname}},
        @{n='Name';e={$_.'FirstName' + ' ' + $_.'Surname'}} |
    New-ADUser -Enabled $true -AccountPassword (ConvertTo-SecureString -AsPlainText "Password1" -Force) -ChangePasswordAtLogon $true -Path "OU=Intake 20XX,OU=Students,OU=Ravenloft users,DC=RAVENLOFT,DC=test" -ProfilePath {"\\TESTSVR\Profiles$\Intake20XX\" +$_.SamAccountName} -HomeDrive "D:" -HomeDirectory {"\\TESTSVR\Work$\Intake20XX\" +$_.SamAccountName}

Now my last job for this would be to add all of these new users to a group called StudentGroup, I understand there is no parameter in new-aduser to edit the "Member of" field in AD. So what would be the best way to go about doing this?

Body:
I prefer to do this on two separate lines

New-ADUser ...
Add-ADGroupMember -Identity "name_of_group" -Members "username"

If you want to one line it, credit goes to Mathias's comment  (using -PassThru)

New-ADUser ... -PassThru | % {Add-ADGroupMember -Identity "DN of StudentGroup" -Members $_}

How you fit that into your script is up to you

-Members can accept an array or a single string of username

New-ADUser ...
Add-ADGroupMember -Identity "name_of_group" -Members @("username1","username2")


答:
Alas, SQL Server doesn't support count(distinct) as a window function.  But it is easy enough to emulate:

```<code>select t.*,
       sum(case when seqnum = 1 then 1 else 0 end) over (partition by box_barcode) as distinct_count
from (select t.*,
             row_number() over (partition by box_barcode, order_numbers order by box_barcode) as seqnum
      from t
     ) t;
</code>```

Title: A Column to count number of distinct values in column X based on column Y?

Body:
In SSMS 2016, I have a select statement with various joins which gives me the following data:

| box_barcode | order_number | order_shipment_id | item     | qty |
|-------------|--------------|-------------------|----------|-----|
|  3330000001 | 0000105      | FP001             | tshirt-S | 1   |
|  3330000001 | 0000105      | FP001             | tshirt-M | 2   |
|  3330000001 | 0000105      | FP001             | tshirt-L | 2   |
|  3330000005 | 0000108      | FP002             | shorts-S | 2   |
|  3330000005 | 0000108      | FP002             | shorts-M | 1   |
|  3330000005 | 0000120      | FP002             | shorts-S | 1   |
|  3330000010 | 0000120      | FP003             | shirts-M | 2   |
|  3330000010 | 0000120      | FP003             | shirts-L | 2   |
|  3330000010 | 0000121      | FP003             | shirts-S | 3   |
|  3330000010 | 0000121      | FP003             | shirts-M | 3   |
|  3330000010 | 0000122      | FP003             | shirts-S | 2   |

I'd like to add a column to count the number of distinct order_numbers for each box_barcode, for the desired result:

| box_barcode | order_number | order_shipment_id | item     | qty | count |
|-------------|--------------|-------------------|----------|-----|-------|
|  3330000001 | 0000105      | FP001             | tshirt-S | 1   | 1
|  3330000001 | 0000105      | FP001             | tshirt-M | 2   | 1
|  3330000001 | 0000105      | FP001             | tshirt-L | 2   | 1
|  3330000005 | 0000108      | FP002             | shorts-S | 2   | 2
|  3330000005 | 0000108      | FP002             | shorts-M | 1   | 2
|  3330000005 | 0000120      | FP002             | shorts-S | 1   | 2
|  3330000010 | 0000120      | FP003             | shirts-M | 2   | 3
|  3330000010 | 0000120      | FP003             | shirts-L | 2   | 3
|  3330000010 | 0000121      | FP003             | shirts-S | 3   | 3
|  3330000010 | 0000121      | FP003             | shirts-M | 3   | 3
|  3330000010 | 0000122      | FP003             | shirts-S | 2   | 3

I'm struggling to find out how best to achieve this. I know of count(distinct..), but would I have to put my current query into a subquery for the count to go against the results of that query first?

Body:
Alas, SQL Server doesn't support count(distinct) as a window function.  But it is easy enough to emulate:

select t.*,
       sum(case when seqnum = 1 then 1 else 0 end) over (partition by box_barcode) as distinct_count
from (select t.*,
             row_number() over (partition by box_barcode, order_numbers order by box_barcode) as seqnum
      from t
     ) t;


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
I just talked to some Xcode engineers at WWDC and the auto discovery of iDevices is still a little buggy. Also sometimes your phone is not correctly broadcasting. Switching your device on and off can help.

There are a few workarounds/fallbacks:

You can check if your phone is broadcasting with Bonjour Browser (www.tildesoft.com). Look if your wifi address is listed under the service called '_apple-mobdev2._tcp. - 215' (you can find your wifi address here: settings > general > about > wifi address.

As a fallback you can connect to your device by manually entering the IP address (right click on your devices in the Devices window).
However this IP address will be persisted, so if you change networks you'll need to reset this. That option is not available in Xcode yet, but you can do it via the terminal with the following command:

```<code>defaults read com.apple.dt.Xcode | grep IDEIDS
</code>```

This will print an identifier which you need to use in the next command:

```<code>defaults delete com.apple.dt.Xcode <identifier>
</code>```

Now the ip address is cleared and you can enter a new one.

The last option is to create a computer-to-computer network. This works fine, but logically you won't have internet access then.

Body:
I just talked to some Xcode engineers at WWDC and the auto discovery of iDevices is still a little buggy. Also sometimes your phone is not correctly broadcasting. Switching your device on and off can help.

There are a few workarounds/fallbacks:

You can check if your phone is broadcasting with Bonjour Browser (www.tildesoft.com). Look if your wifi address is listed under the service called '_apple-mobdev2._tcp. - 215' (you can find your wifi address here: settings > general > about > wifi address.

As a fallback you can connect to your device by manually entering the IP address (right click on your devices in the Devices window).
However this IP address will be persisted, so if you change networks you'll need to reset this. That option is not available in Xcode yet, but you can do it via the terminal with the following command:

defaults read com.apple.dt.Xcode | grep IDEIDS

This will print an identifier which you need to use in the next command:

defaults delete com.apple.dt.Xcode <identifier>

Now the ip address is cleared and you can enter a new one.

The last option is to create a computer-to-computer network. This works fine, but logically you won't have internet access then.


问:
Set <select> element depending on another <select> element
I need a select element's options to change depending on the value of another.

```<code><select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

<script>
    $("#first").on("change", function() {
        <pseudo>
            if #first == "1"
                #second = {"this", "that", "the other"}
            else if #first == "2"
                #second = {"more", "even more", "yet another", "still more"}
        </pseudo>
    }
</script>
</code>```

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

```<code><select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>
</code>```

JS:

```<code>var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});
</code>```

答:
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:

$(document).on('change', '#two', function() {
  var option_to_add = $(this).find("option:selected").text();
  var number_of_options = $('#two option').length
  $('#one').append($('<option>', {
    value: number_of_options,
    text: option_to_add
  }));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
    <option value="cash">Cash</option>
    <option value="money">Money</option>
</select>
<select id="two">
    <option value="stack">Stack</option>
    <option value="overflow">Overflow</option>
    <option value="my">My</option>
    <option value="question">Question</option>
    <option value="op1">Should be option 1: </option>
</select> Should also be option 1:
<div id="option1"></div></code>```

Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:

// dummy data array of arrays
var list = [
  [11, "Eleven"],
  [12, "Twelve"],
  [13, "Thirteen"]
];

// click the button, replace the select contents
$('#btn').on('click', function() {

  // build an array of option objects from an array of arrays
  // see below
  var opt_array = build_opt_array(list);

  $('#sel').empty();

  // add the new options
  $(opt_array).each(function(index) {
    $('#sel').append(opt_array[index]);
  });

});

// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
  var opt_array = [];
  $(items).each(function(index) {
    var new_option = $('<option>', {
      value: items[index][0],
      text: items[index][1]
    });
    opt_array.push(new_option);
  });
  return opt_array;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button id="btn">
  Click me
</button></code>```

Body:
I need a select element's options to change depending on the value of another.

<select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

<select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>

JS:

var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});

Body:
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:

$(document).on('change', '#two', function() {
  var option_to_add = $(this).find("option:selected").text();
  var number_of_options = $('#two option').length
  $('#one').append($('<option>', {
    value: number_of_options,
    text: option_to_add
  }));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
    <option value="cash">Cash</option>
    <option value="money">Money</option>
</select>
<select id="two">
    <option value="stack">Stack</option>
    <option value="overflow">Overflow</option>
    <option value="my">My</option>
    <option value="question">Question</option>
    <option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>

Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:

// dummy data array of arrays
var list = [
  [11, "Eleven"],
  [12, "Twelve"],
  [13, "Thirteen"]
];

// click the button, replace the select contents
$('#btn').on('click', function() {

  // build an array of option objects from an array of arrays
  // see below
  var opt_array = build_opt_array(list);

  $('#sel').empty();

  // add the new options
  $(opt_array).each(function(index) {
    $('#sel').append(opt_array[index]);
  });

});

// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
  var opt_array = [];
  $(items).each(function(index) {
    var new_option = $('<option>', {
      value: items[index][0],
      text: items[index][1]
    });
    opt_array.push(new_option);
  });
  return opt_array;
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button id="btn">
  Click me
</button>


问:
Mongo - Return items that exist with one value but not another
I have a collection of documents that represent products available in different locales. Some products are available only in certain locales. If a product isn't specifically listed for a given locale, then it's not available for that locale.

Here's a tiny example, with only the pertinent bits:

```<code>{ "locale": "US", "productId": "123" }
{ "locale": "CA", "productId": "123" }
{ "locale": "FR", "productId": "123" }
{ "locale": "US", "productId": "456" }
{ "locale": "FR", "productId": "456" }
</code>```

I'd like to query for all the productIds that are available in the US, but not in CA. In this example, that'd be productId 456.

If I were doing this in SQL, I'd join the table to itself and find the answer that way. But I'm not sure how to tackle this sort of query in Mongo. What's the most appropriate way to do this sort of thing?

答:
You can use aggregation pipeline:

```<code>db.products.aggregate([
  { $group: { _id: "$productId", locales: { $push: "$locale" } } },
  { $match: { locales: "US", locales: {$nin: ["CA"] } } },
  { $project: { _id: 0, productId: "$_id" } }
])
</code>```

Details:

Group products by id and push all product locales into the array.

Select those documents which have US locale but don't have CA locale

Project results to get only productId values.

Output:

```<code>{ "productId" : "456" }
</code>```

Note that you can get all product ids in single array if you'll do grouping after match stage:

```<code>{ $group: { _id: 1, productIds: { $push: "$_id" } } }
</code>```

Body:
I have a collection of documents that represent products available in different locales. Some products are available only in certain locales. If a product isn't specifically listed for a given locale, then it's not available for that locale.

Here's a tiny example, with only the pertinent bits:

{ "locale": "US", "productId": "123" }
{ "locale": "CA", "productId": "123" }
{ "locale": "FR", "productId": "123" }
{ "locale": "US", "productId": "456" }
{ "locale": "FR", "productId": "456" }

I'd like to query for all the productIds that are available in the US, but not in CA. In this example, that'd be productId 456.

If I were doing this in SQL, I'd join the table to itself and find the answer that way. But I'm not sure how to tackle this sort of query in Mongo. What's the most appropriate way to do this sort of thing?

Body:
You can use aggregation pipeline:

db.products.aggregate([
  { $group: { _id: "$productId", locales: { $push: "$locale" } } },
  { $match: { locales: "US", locales: {$nin: ["CA"] } } },
  { $project: { _id: 0, productId: "$_id" } }
])

Details:

Group products by id and push all product locales into the array.

Select those documents which have US locale but don't have CA locale

Project results to get only productId values.

Output:

{ "productId" : "456" }

Note that you can get all product ids in single array if you'll do grouping after match stage:

{ $group: { _id: 1, productIds: { $push: "$_id" } } }


问:
Excel - count first adjacent non-zero and not-null values in a row
I'm trying to write a formula, which will count numbers (>0) in a row.

Only the first set of >0 numbers in a row should be counted.

When there is a 0 or an empty cell after the >0 number, the count should ignore next values.

Example:

答:
Create a UDF so you can loop through the columns from left to right. Place the following code in a module and use it like any other formula. It has one arguement - the range of cells on the row.

```<code>Function CountAdjacent(rng As Range)

Dim x As Integer, result As Integer
Dim ws As Worksheet
Dim firstValuePassed As Boolean

Set ws = rng.Parent

For x = rng.Column To rng.Column + rng.Columns.Count - 1
    If ws.Cells(rng.Row, x) <> 0 And Not IsEmpty(ws.Cells(rng.Row, x)) Then
        result = result + 1
        firstValuePassed = True
    Else
        If firstValuePassed = True Then Exit For
    End If
Next x

CountAdjacent = result

End Function
</code>```

How it works:
The For loop on x goes from the first selected column to the last. If it encounters a number it increments the result by one and flags that a number has been encountered in the firstValuePassed boolean, since you want any gaps in the numbers to stop the count. If it encounters a zero or blank cell it checks against firstValuePassed to see if it comes after a number >0, if so it stops the count, if not it moves to the next cell.

Body:
Create a UDF so you can loop through the columns from left to right. Place the following code in a module and use it like any other formula. It has one arguement - the range of cells on the row.

Function CountAdjacent(rng As Range)

Dim x As Integer, result As Integer
Dim ws As Worksheet
Dim firstValuePassed As Boolean

Set ws = rng.Parent

For x = rng.Column To rng.Column + rng.Columns.Count - 1
    If ws.Cells(rng.Row, x) <> 0 And Not IsEmpty(ws.Cells(rng.Row, x)) Then
        result = result + 1
        firstValuePassed = True
    Else
        If firstValuePassed = True Then Exit For
    End If
Next x

CountAdjacent = result

End Function

How it works:
The For loop on x goes from the first selected column to the last. If it encounters a number it increments the result by one and flags that a number has been encountered in the firstValuePassed boolean, since you want any gaps in the numbers to stop the count. If it encounters a zero or blank cell it checks against firstValuePassed to see if it comes after a number >0, if so it stops the count, if not it moves to the next cell.


问:
Telegram new source code APP ID issue (CONNECTION_API_ID_INVALID)
I'm experiencing issue with NEW Telegram iOS app source code.

Short question:

There is always CONNECTION_API_ID_INVALID error while I'm trying to connect. Do someone solve such issue?

Long question:

I've downloaded theirs NEW source code
So, I did fix assertion's by replacing in TGTelegraph.mm:

```<code>NSAssert(false, @"Please obtain your own apiId and apiHash at https://my.telegam.org");
</code>```

With:

```<code>_apiId = @"my_api_id"; // Number
_apiHash = @"my_api_hash"; // Hash string
</code>```

Also I did comment same assert in TGTelegramNetworking.mm

```<code>//NSAssert(false, @"Please obtain your own apiId at https://my.telegam.org");
</code>```

And the result is always an error:

```<code>[MTRequestMessageService#0x1a3c2770 in response to 6129750297537847296 400: (null):CONNECTION_API_ID_INVALID]
</code>```

I've tried:

Replace api_id and api_hash with another one private (currently working with old code)

Replace api_id and api_hash with another public api_id and api_hash that was provided by Telegram with old public code.

Change MTDatacenterAddress in TGTelegramNetworking.mm to IP provided at https://my.telegram.org/apps

Change MTDatacenterAddress in TGTelegramNetworking.mm to IP provided by old source code

Try different combinations at the list above.

I found:

Changes to MTDatacenterAddress in TGTelegramNetworking.mm
applies only after app reinstallation

Public keys stop working in
old code too.

Fingerprint of a server being checked successfully
(last field in dev console)

Did someone experience same issue? Can anyone suggest something to try? Actually I ran out of varians to solve this issue.

答:
I know this is outdated, but if anyone needs it, now they are under

```<code>/Telegraph/TGTelegraph.mm
</code>```

in the form of

```<code>getAppPrefs.api_id = id_as_number;
getAppPrefs.api_hash = @"hash_as_string";
</code>```

Body:
I'm experiencing issue with NEW Telegram iOS app source code.

Short question:

There is always CONNECTION_API_ID_INVALID error while I'm trying to connect. Do someone solve such issue?

Long question:

I've downloaded theirs NEW source code
So, I did fix assertion's by replacing in TGTelegraph.mm:

NSAssert(false, @"Please obtain your own apiId and apiHash at https://my.telegam.org");

With:

_apiId = @"my_api_id"; // Number
_apiHash = @"my_api_hash"; // Hash string

Also I did comment same assert in TGTelegramNetworking.mm

//NSAssert(false, @"Please obtain your own apiId at https://my.telegam.org");

And the result is always an error:

[MTRequestMessageService#0x1a3c2770 in response to 6129750297537847296 400: (null):CONNECTION_API_ID_INVALID]

I've tried:

Replace api_id and api_hash with another one private (currently working with old code)

Replace api_id and api_hash with another public api_id and api_hash that was provided by Telegram with old public code.

Change MTDatacenterAddress in TGTelegramNetworking.mm to IP provided at https://my.telegram.org/apps

Change MTDatacenterAddress in TGTelegramNetworking.mm to IP provided by old source code

Try different combinations at the list above.

I found:

Changes to MTDatacenterAddress in TGTelegramNetworking.mm
applies only after app reinstallation

Public keys stop working in
old code too.

Fingerprint of a server being checked successfully
(last field in dev console)

Did someone experience same issue? Can anyone suggest something to try? Actually I ran out of varians to solve this issue.

Body:
I know this is outdated, but if anyone needs it, now they are under

/Telegraph/TGTelegraph.mm

in the form of

getAppPrefs.api_id = id_as_number;
getAppPrefs.api_hash = @"hash_as_string";


问:
python find() fails to find substring at start of string
I have encountered some odd behavior with find. When searching for a substring, if that substring is at the very beginning of the string I am searching (the substring starts at index 0), it will not be found. If I pad the string with a single whitespace character (so the substring starts at index 1), it rescues find functionality and behaves as expected. Am I using find incorrectly?

```<code>my_string = "hello world"
searches = ["hello",
            "world",
            ]
# Search the string for the two substrings
for search in searches:
    if my_string.find(search):
        print("Found", search)
    else:
        print("Did not find", search)
# Did not find hello
# Found world

# Try padding the string, so substring 'hello' is not at the very beginning
my_padded_string = " " + my_string
for search in searches:
    if my_padded_string.find(search):
        print("Found", search)
    else:
        print("Did not find", search)
# Found world
# Found hello
</code>```

Note the order of the substrings in the searches list does not seem to matter.

I am using Python 3.6.0 :: Anaconda 4.3.0 (64-bit).

答:
find is actually working as intended. It is supposed to return the index of the string if found and -1 otherwise.

Your if statement should read as follows:

```<code>for search in searches:
    if my_string.find(search) >= 0:
        print("Found", search)
    else:
        print("Did not find", search)
</code>```

Body:
I have encountered some odd behavior with find. When searching for a substring, if that substring is at the very beginning of the string I am searching (the substring starts at index 0), it will not be found. If I pad the string with a single whitespace character (so the substring starts at index 1), it rescues find functionality and behaves as expected. Am I using find incorrectly?

my_string = "hello world"
searches = ["hello",
            "world",
            ]
# Search the string for the two substrings
for search in searches:
    if my_string.find(search):
        print("Found", search)
    else:
        print("Did not find", search)
# Did not find hello
# Found world

# Try padding the string, so substring 'hello' is not at the very beginning
my_padded_string = " " + my_string
for search in searches:
    if my_padded_string.find(search):
        print("Found", search)
    else:
        print("Did not find", search)
# Found world
# Found hello

Note the order of the substrings in the searches list does not seem to matter.

I am using Python 3.6.0 :: Anaconda 4.3.0 (64-bit).

Body:
find is actually working as intended. It is supposed to return the index of the string if found and -1 otherwise.

Your if statement should read as follows:

for search in searches:
    if my_string.find(search) >= 0:
        print("Found", search)
    else:
        print("Did not find", search)


问:
Square Root to 2 Decimal places
I've been trying to do some homework and was getting on fine until I came across a particular task.

The Task is: Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to 2 decimal places.

My current code is below I have managed to make it do the square root part but it is not displaying it to 2 decimal places.

```<code>import math
number = float(input("Please Input a number over 500 and i will work out the square root of that number and display it to 2 decimal places! "))

if number < 500:
    print("That number is not above 500!")
else:
    print(math.sqrt(round(number,2)))
</code>```

答:
I think you can use the format() function</p>

```<code>format(math.sqrt(num), '.2f')
</code>```

Title: Square Root to 2 Decimal places

Body:
I've been trying to do some homework and was getting on fine until I came across a particular task.

The Task is: Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to 2 decimal places.

My current code is below I have managed to make it do the square root part but it is not displaying it to 2 decimal places.

import math
number = float(input("Please Input a number over 500 and i will work out the square root of that number and display it to 2 decimal places! "))

if number < 500:
    print("That number is not above 500!")
else:
    print(math.sqrt(round(number,2)))

Body:
I think you can use the format() function

format(math.sqrt(num), '.2f')


问:
Pyplot Create Intensity Plot From 1D Array
I currently have a 1D array, representing intensity values with the index of the value being its x-position.

```<code>intensity_values = [0.10, 0.32, ... , 0.12, 0.23]
</code>```

I want to create a subplot at the bottom of my figure with an intensity plot, visually showing the data as such.

I've seen examples which require an array with 3-dimension to be able to fufil the data plot. How would I achieve this result?

答:
If you reshape intensity_values into a 2D NumPy array, you could use imshow:

```<code>ax.imshow(np.atleast_2d(intensity_values))
</code>```

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
x = np.linspace(0, np.pi, 100)
intensity_values = np.sin(x)

# https://stackoverflow.com/a/35881382/190597
fig, (ax0, ax1) = plt.subplots(
    nrows=2, gridspec_kw={'height_ratios':[7, 1],}, sharex=True)
ax0.plot(x, intensity_values)
ax1.imshow(np.atleast_2d(intensity_values), cmap=plt.get_cmap('gray'),
              extent=(0, np.pi, 0, 1))
plt.show()
</code>```

Body:
I currently have a 1D array, representing intensity values with the index of the value being its x-position.

intensity_values = [0.10, 0.32, ... , 0.12, 0.23]

I want to create a subplot at the bottom of my figure with an intensity plot, visually showing the data as such.

I've seen examples which require an array with 3-dimension to be able to fufil the data plot. How would I achieve this result?

Body:
If you reshape intensity_values into a 2D NumPy array, you could use imshow:

ax.imshow(np.atleast_2d(intensity_values))

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
x = np.linspace(0, np.pi, 100)
intensity_values = np.sin(x)

# https://stackoverflow.com/a/35881382/190597
fig, (ax0, ax1) = plt.subplots(
    nrows=2, gridspec_kw={'height_ratios':[7, 1],}, sharex=True)
ax0.plot(x, intensity_values)
ax1.imshow(np.atleast_2d(intensity_values), cmap=plt.get_cmap('gray'),
              extent=(0, np.pi, 0, 1))
plt.show()


问:
Create Dictionary after SelectMany
I have the classes Category and CategoryI18N:

```<code>public class Category {
  public Int32 Id { get; set; }
  public virtual ICollection<CategoryI18N> CategoriesI18N { get; set; };
}

public class CategoryI18N {
  public String LanguageCode { get; set; }
  public String Name { get; set; }
}
</code>```

And I have the following query:

```<code>IList<Category> categories = service.GetCategories();

var result = categories.SelectMany(y => y.CategoriesI18N, (c, cI18N) => new { c, cI18N })
</code>```

I would like result to be a List<Dictionary<String, CategoryI18N>> where:

1 - The list is the list of categories;

2 - The dictionary values are the CategoriesI18N in each Category and the Key is each CategoryI18N language code.

How should I do this after the SelectMany?

答:
I think what you want is this:

```<code>categories.Select(x=>x.CategoriesI18N.ToDictionary(y=>y.LanguageCode)).ToList()
</code>```

The Select will mean it will make one entry in the final list for each catgegory.

We then transform the category to a dictionary by using ToDictionary on its CategoriesI18N property. We pass in a simple selector to define the key for each entry. Since we provide no selector for the value it will put the object ie the CategoriesI18N entry) as the value in the dictionary.

I'm not sure how the LanguageCode is defined in your CategoriesI18N object so you may need to edit that.

Note that I have not used SelectMany - this is because it loses the information we want which is the categories. It will instead put all of the CategoriesI18N into a single list which will make it much harder to then put it in a list based on categories.

Title: Create Dictionary after SelectMany

Body:
I have the classes Category and CategoryI18N:

public class Category {
  public Int32 Id { get; set; }
  public virtual ICollection<CategoryI18N> CategoriesI18N { get; set; };
}

public class CategoryI18N {
  public String LanguageCode { get; set; }
  public String Name { get; set; }
}

And I have the following query:

IList<Category> categories = service.GetCategories();

var result = categories.SelectMany(y => y.CategoriesI18N, (c, cI18N) => new { c, cI18N })

I would like result to be a List<Dictionary<String, CategoryI18N>> where:

1 - The list is the list of categories;

2 - The dictionary values are the CategoriesI18N in each Category and the Key is each CategoryI18N language code.

How should I do this after the SelectMany?

Body:
I think what you want is this:

categories.Select(x=>x.CategoriesI18N.ToDictionary(y=>y.LanguageCode)).ToList()

The Select will mean it will make one entry in the final list for each catgegory.

We then transform the category to a dictionary by using ToDictionary on its CategoriesI18N property. We pass in a simple selector to define the key for each entry. Since we provide no selector for the value it will put the object ie the CategoriesI18N entry) as the value in the dictionary.

I'm not sure how the LanguageCode is defined in your CategoriesI18N object so you may need to edit that.

Note that I have not used SelectMany - this is because it loses the information we want which is the categories. It will instead put all of the CategoriesI18N into a single list which will make it much harder to then put it in a list based on categories.


问:
play framework java rest api example
I'm starting in the play framework with Java and downloaded the project from the official website: https://github.com/playframework/play-java-rest-api-example/tree/2.5.x

I joined the eclipse as it says at: https://www.playframework.com/documentation/2.5.x/IDE

And run the command: sbt run
It worked. However, if I send a post to the given address, I get the message "Unauthorized".

Does anyone know if I have to do anything else?

Thank you very much in advance.

答: I found out. I have not yet studied Filters, but I left it that way and it worked:

Title: play framework java rest api example


问:
How to check if button in react is disabled?
I have this code for my button that doesn't work, FOR the title:

```<code><Button
        id="completeSelectedButton"
        title={Boolean(document.getElementById('completeSelectedButton').disabled) ? 'Some of the selected todos is already Complete.' : '' }
        disabled={Boolean((this.state.checkedIds.length !== 0) && // check if not empty
                           this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length) ? false : true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false
                  }
        onClick={() => {
          onCompleteMultipleClick(this.state.checkedIds)
          this.setState({checkedIds:[]});
        }}
      >
</code>```

I want to set the title if the button is disabled, but I think it's not working because I am having this error, I think React cannot find it?

Uncaught TypeError: Cannot read property 'disabled' of null

答:
You should rarely need to read from the DOM in React components. The DOM is a reflection of the props and state of your components, so you already know everything that the DOM might tell you. In this case, extract the value to a variable and reference it in both places:

```<code>const disabled = Boolean(
    (this.state.checkedIds.length !== 0) && // check if not empty
    this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length
  ) ?
  false :
  true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false

<Button
  id="completeSelectedButton"
  title={disabled ? 'Some of the selected todos is already Complete.' : '' }
  disabled={disabled}
  onClick={() => {
    onCompleteMultipleClick(this.state.checkedIds)
    this.setState({checkedIds:[]});
  }}
>
</code>```

Body:
I have this code for my button that doesn't work, FOR the title:

<Button
        id="completeSelectedButton"
        title={Boolean(document.getElementById('completeSelectedButton').disabled) ? 'Some of the selected todos is already Complete.' : '' }
        disabled={Boolean((this.state.checkedIds.length !== 0) && // check if not empty
                           this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length) ? false : true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false
                  }
        onClick={() => {
          onCompleteMultipleClick(this.state.checkedIds)
          this.setState({checkedIds:[]});
        }}
      >

I want to set the title if the button is disabled, but I think it's not working because I am having this error, I think React cannot find it?

Uncaught TypeError: Cannot read property 'disabled' of null

Body:
You should rarely need to read from the DOM in React components. The DOM is a reflection of the props and state of your components, so you already know everything that the DOM might tell you. In this case, extract the value to a variable and reference it in both places:

const disabled = Boolean(
    (this.state.checkedIds.length !== 0) && // check if not empty
    this.state.checkedIds.length === todos.filter(({id, completed}) => this.state.checkedIds.includes(id) && completed === false ).length
  ) ?
  false :
  true // if it matched, ALL THE CHECKED TODOS ARE UNFINISHED OR HAS completed property === false

<Button
  id="completeSelectedButton"
  title={disabled ? 'Some of the selected todos is already Complete.' : '' }
  disabled={disabled}
  onClick={() => {
    onCompleteMultipleClick(this.state.checkedIds)
    this.setState({checkedIds:[]});
  }}
>


问:
Get name of button onPress in react native
I have two buttons that both call the same onPress function.   In the callback I want to be able to differentiate between which was pressed.

```<code><MKRadioButton
   title='A'
   group={this.radioGroup}
   onPress={this._toggle}
 />

<MKRadioButton
   title='B'
   group={this.radioGroup}
   onPress={this._toggle}
 />
</code>```

then the call

```<code>_toggle(event) {
    //what should go here to figure out if title A or B was called?
}
</code>```

答:
One solution is to pass that info as a parameter:

```<code><MKRadioButton
  title='A'
  group={this.radioGroup}
  onPress={(event) => this._toggle(event, 'A')}
/>
</code>```

The callback would then use that parameter

```<code>_toggle(event, buttonId) {
  // Use buttonId
}
</code>```

EDIT: Another solution is a parent component that always returns the title prop:

```<code>class RadioParent extends Component {
  render() {
    return (
      <MKRadioButton
        title={this.props.title}
        group={this.props.radioGroup}
        onPress={(event) => this.props.onPress(event, this.props.title)}
      />
    );
  }
}
</code>```

Body:
I have two buttons that both call the same onPress function.   In the callback I want to be able to differentiate between which was pressed.

<MKRadioButton
   title='A'
   group={this.radioGroup}
   onPress={this._toggle}
 />

<MKRadioButton
   title='B'
   group={this.radioGroup}
   onPress={this._toggle}
 />

then the call

_toggle(event) {
    //what should go here to figure out if title A or B was called?
}

Body:
One solution is to pass that info as a parameter:

<MKRadioButton
  title='A'
  group={this.radioGroup}
  onPress={(event) => this._toggle(event, 'A')}
/>

The callback would then use that parameter

_toggle(event, buttonId) {
  // Use buttonId
}

EDIT: Another solution is a parent component that always returns the title prop:

class RadioParent extends Component {
  render() {
    return (
      <MKRadioButton
        title={this.props.title}
        group={this.props.radioGroup}
        onPress={(event) => this.props.onPress(event, this.props.title)}
      />
    );
  }
}


问:
HTML css margin pading content border
What is my problem? I cannot find a solution to make it look like this
Hello World box I'm not very good at coding but I'm trying to understand what I did wrong. Can someone help me please and fix my code?

.mano-modelis .content {
  content: "Hello World!";
  width: 300px;
  font-size: 1em;
  color: white;
  display: block;
  text-align: center;
  line-height: 300px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: black;
}

.mano-modelis .border {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
}

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  border: 2px;
  transition: all;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div></code>```

答:
Here is simplified version of linked image, I used only two elements.

.blue {
  background: blue;
  width: 300px;
  padding: 10px;
  box-sizing: border-box;
}
.green {
  background: green;
  text-align: center;
  height: 250px;
  border: 10px solid black;
  line-height: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blue">
  <div class="green">
    Hello world
  </div>
</div></code>```

it can also be done with one element, like this:

.green {
  background: green;
  text-align: center;
  height: 250px;
  width: 250px;
  border: 10px solid black;
  box-sizing: boreder-box;
  line-height: 250px;
  box-shadow: 0px 0px 0px 10px blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="green">
    Hello world
  </div></code>```

And here is it with your code, fixed:

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
}

.mano-modelis .content {
  font-size: 1em;
  color: white;
  text-align: center;
  line-height: 270px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 270px;
  height: 270px;
  background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div></code>```

Title: HTML css margin pading content border

Body:
What is my problem? I cannot find a solution to make it look like this
Hello World box I'm not very good at coding but I'm trying to understand what I did wrong. Can someone help me please and fix my code?

.mano-modelis .content {
  content: "Hello World!";
  width: 300px;
  font-size: 1em;
  color: white;
  display: block;
  text-align: center;
  line-height: 300px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  background: black;
}

.mano-modelis .border {
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
}

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
  position: relative;
  border: 2px;
  transition: all;
}

Hello world!

Body:
Here is simplified version of linked image, I used only two elements.

.blue {
  background: blue;
  width: 300px;
  padding: 10px;
  box-sizing: border-box;
}
.green {
  background: green;
  text-align: center;
  height: 250px;
  border: 10px solid black;
  line-height: 250px;
}

<div class="blue">
  <div class="green">
    Hello world
  </div>
</div>

it can also be done with one element, like this:

.green {
  background: green;
  text-align: center;
  height: 250px;
  width: 250px;
  border: 10px solid black;
  box-sizing: boreder-box;
  line-height: 250px;
  box-shadow: 0px 0px 0px 10px blue;
}

  <div class="green">
    Hello world
  </div>

And here is it with your code, fixed:

.mano-modelis .margin {
  background: blue;
  padding: 15px;
  width: 300px;
  height: 300px;
}

.mano-modelis .content {
  font-size: 1em;
  color: white;
  text-align: center;
  line-height: 270px;
  background-color: green;
}

.mano-modelis .padding {
  color: black;
  padding: 15px;
  width: 270px;
  height: 270px;
  background: black;
}

<div class="mano-modelis">
  <div class="margin">
    <div class="border">
      <div class="padding">
        <div class="content">Hello world!</div>
      </div>
    </div>
  </div>
</div>


问:
How to initialize msvcrt.dll?
If I do a LoadLibrary("msvcrt.dll") do I need to initialize the CRT somehow? Section 2 in the following document seems to say that I do, but I just get an undefined symbol error for _CRT_INIT when I try to call _CRT_INIT:

http://support.microsoft.com/kb/94248

Edit: I should have said that this is for a program that dynamically loads all the dlls that it uses, hence the call to LoadLibrary("msvcrt.dll").

答: You must not call _CRT_INIT() but call CRT_INIT() (if you really must)

ContentLicense: CC BY-SA 2.5

Title: How to initialize msvcrt.dll?


问:
Elastic search simple query to find all ids
I am trying to get all id's for a type, but I am pulling my hair out.

Please see my attacment.

HERE IS THE cURL call :

```<code>curl -XGET 'localhost:9200/_search?pretty' -H 'Content-Type: application/json'
-d'{ "query": { "wildcard" : { "id" : "Account[enter image description here][1]*" }    }}'
</code>```

cURL call with no results

答: I would guess there is an issue with the way your id-field is analyzed. You can retrieve the mapping by using the _mapping endpoint (described in the docs). Your id field should be analyzed as a string (with break characters, tokenizers and all) for the wildcard query to work. If it is not analyzed, as you might expect for an id-field, the wildcard query will not work. Then you would need to change the mapping and reindex your data to make it work.</p>

Body:
I am trying to get all id's for a type, but I am pulling my hair out.

Please see my attacment.

HERE IS THE cURL call :

curl -XGET 'localhost:9200/_search?pretty' -H 'Content-Type: application/json'
-d'{ "query": { "wildcard" : { "id" : "Account[enter image description here][1]*" }    }}'

cURL call with no results


问:
Create PDF file from iframe
I want to save a PDF file which contains an IFrame content. I am using jsPDF for it. When I hit the button that calls the function the script creates an empty PDF page.

The content of the frame looks like: https://jsfiddle.net/ss6780qn/

I am using the following script:

```<code><script src="../jspdf/plugins/standard_fonts_metrics.js"></script>
<script type="text/javascript">
function toPDF(){
        var pdf = new jsPDF('p', 'in', 'letter');

    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#frame')[0]

    // we support special element handlers. Register them with jQuery-style
    // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
    // There is no support for any other type of selectors
    // (class, of compound) at this time.
    specialElementHandlers = {
        // element with id of "bypass" - jQuery style selector
        'div': function(element, renderer){
            // true = "handled elsewhere, bypass text extraction"
            return true
        }
    }

    // all coords and widths are in jsPDF instance's declared units
    // 'inches' in this case
    pdf.fromHTML(
        source // HTML string or DOM elem ref.
        , 0.5 // x coord
        , 0.5 // y coord
        , {
            'width':7.5 // max width of content on PDF
             ,'elementHandlers': specialElementHandlers
        }
    )

    pdf.save('Test.pdf');
}
</code>```

Does someone know what is wrong and how I can fix this?

答:
Looks like an open case on Github for this very issue, still open since 2015. See https://github.com/MrRio/jsPDF/issues/496. Maybe there is no solution.

Plus, in the source code is the following notation before the jsPDFAPI.fromHTML function that you are calling. Please see the last point re tables which may affect your work.

```<code>* Converts HTML-formatted text into formatted PDF text.
*
* Notes:
* 2012-07-18
* Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
* Plugin relies on jQuery for CSS extraction.
* Targeting HTML output from Markdown templating, which is a very simple
* markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
* Images, tables are NOT supported.
</code>```

Also - I tried to set up a working snippet here and in jsfiddle but could not get jsPDF.fromHTML to work. I am not a jsPDF expert, but I've been around the block and I don't get the feeling that jsPDF is very robust - you may want to cast your net wider and find another plugin. Just my opinion.

Title: Create PDF file from iframe

Body:
Looks like an open case on Github for this very issue, still open since 2015. See https://github.com/MrRio/jsPDF/issues/496. Maybe there is no solution.

Plus, in the source code is the following notation before the jsPDFAPI.fromHTML function that you are calling. Please see the last point re tables which may affect your work.

* Converts HTML-formatted text into formatted PDF text.
*
* Notes:
* 2012-07-18
* Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
* Plugin relies on jQuery for CSS extraction.
* Targeting HTML output from Markdown templating, which is a very simple
* markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
* Images, tables are NOT supported.

Also - I tried to set up a working snippet here and in jsfiddle but could not get jsPDF.fromHTML to work. I am not a jsPDF expert, but I've been around the block and I don't get the feeling that jsPDF is very robust - you may want to cast your net wider and find another plugin. Just my opinion.


问:
Optimizing a SQL query on SQL Server
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc
</code>```

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc
</code>```

Any help is appreciated,
Thank you!

答:
I would write this as:

```<code>SELECT DeptNo, BrandDesc, MfgDesc,
       SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) OVER (PARTITION BY BrandDesc, MfgDesc, DeptNo) as CountOfActiveSKUs
FROM dbo.SKU s
ORDER BY BrandDesc;
</code>```

I would leave the SELECT DISTINCT out, unless it is absolutely necessary.  If it is necessary, then use an explicit GROUP BY:

```<code>SELECT DeptNo, BrandDesc, MfgDesc,
       SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) as CountOfActiveSKUs
FROM dbo.SKU s
GROUP BY DeptNo, BrandDesc, MfgDesc
ORDER BY BrandDesc;
</code>```

Title: Optimizing a SQL query on SQL Server

Body:
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc

Any help is appreciated,
Thank you!

Body:
I would write this as:

SELECT DeptNo, BrandDesc, MfgDesc,
       SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) OVER (PARTITION BY BrandDesc, MfgDesc, DeptNo) as CountOfActiveSKUs
FROM dbo.SKU s
ORDER BY BrandDesc;

I would leave the SELECT DISTINCT out, unless it is absolutely necessary.  If it is necessary, then use an explicit GROUP BY:

SELECT DeptNo, BrandDesc, MfgDesc,
       SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) as CountOfActiveSKUs
FROM dbo.SKU s
GROUP BY DeptNo, BrandDesc, MfgDesc
ORDER BY BrandDesc;


问:
VBA | Reduce Number of Active Sheets Based on Cell Values
I am creating a user interface that allows users to use a maximum of 10 data tabs. On most occasions, the user will use less tabs (lets say 3). I am interested in a code that operates off of a value within the range [P2:P11] for the ten tabs. If a data tab is in use, the box returns "True" but when a tab is not in use, it returns the value of "False."

I would like the user to not have the burden of seeing the other data tabs (4-10) if they only use 1, 2 and 3. (The data tabs are actually labeled 1, 2, 3 etc. for convenience). This macro is meant to operate on a page called "HIDE_ME" that will be hidden when the program is sent out to users. I have created the code for the event below but I cannot get them to operate. Can anyone assist me in locating my error? Many thanks.

```<code>Sub Worksheet_Change(ByVal Target As Range)
If [P2] = "True" Then
Sheets("1").Visible = True
Else
Sheets("1").Visible = False
End If

If [P3] = "True" Then
Sheets("2").Visible = True
Else
Sheets("2").Visible = False
End If

If [P4] = "True" Then
Sheets("3").Visible = True
Else
Sheets("3").Visible = False
End If

If [P5] = "True" Then
Sheets("4").Visible = True
Else
Sheets("4").Visible = False
End If

If [P6] = "True" Then
Sheets("5").Visible = True
Else
Sheets("5").Visible = False
End If

If [P7] = "True" Then
Sheets("6").Visible = True
Else
Sheets("6").Visible = False
End If

If [P8] = "True" Then
Sheets("7").Visible = True
Else
Sheets("7").Visible = False
End If

If [P9] = "True" Then
Sheets("8").Visible = True
Else
Sheets("8").Visible = False
End If

If [P10] = "True" Then
Sheets("9").Visible = True
Else
Sheets("9").Visible = False
End If

If [P11] = "True" Then
Sheets("10").Visible = True
Else
Sheets("10").Visible = False
End If

End Sub
</code>```

答:
```<code>Sub DataSheetsShown()
'Test whether or not the cell value is present
'If value is present, show field
    If IsEmpty(Range("P2").Value) = True Then
        Sheets("1").Visible = False
    End If
    If IsEmpty(Range("P3").Value) = True Then
        Sheets("2").Visible = False
    End If
    If IsEmpty(Range("P4").Value) = True Then
        Sheets("3").Visible = False
    End If
    If IsEmpty(Range("P5").Value) = True Then
        Sheets("4").Visible = False
    End If
    If IsEmpty(Range("P6").Value) = True Then
        Sheets("5").Visible = False
    End If
    If IsEmpty(Range("P7").Value) = True Then
        Sheets("6").Visible = False
    End If
    If IsEmpty(Range("P8").Value) = True Then
        Sheets("7").Visible = False
    End If
    If IsEmpty(Range("P9").Value) = True Then
        Sheets("8").Visible = False
    End If
    If IsEmpty(Range("P10").Value) = True Then
        Sheets("9").Visible = False
    End If
    If IsEmpty(Range("P11").Value) = True Then
        Sheets("10").Visible = False
    End If
End Sub
</code>```

Body:
I am creating a user interface that allows users to use a maximum of 10 data tabs. On most occasions, the user will use less tabs (lets say 3). I am interested in a code that operates off of a value within the range [P2:P11] for the ten tabs. If a data tab is in use, the box returns "True" but when a tab is not in use, it returns the value of "False."

I would like the user to not have the burden of seeing the other data tabs (4-10) if they only use 1, 2 and 3. (The data tabs are actually labeled 1, 2, 3 etc. for convenience). This macro is meant to operate on a page called "HIDE_ME" that will be hidden when the program is sent out to users. I have created the code for the event below but I cannot get them to operate. Can anyone assist me in locating my error? Many thanks.

Sub Worksheet_Change(ByVal Target As Range)
If [P2] = "True" Then
Sheets("1").Visible = True
Else
Sheets("1").Visible = False
End If

If [P3] = "True" Then
Sheets("2").Visible = True
Else
Sheets("2").Visible = False
End If

If [P4] = "True" Then
Sheets("3").Visible = True
Else
Sheets("3").Visible = False
End If

If [P5] = "True" Then
Sheets("4").Visible = True
Else
Sheets("4").Visible = False
End If

If [P6] = "True" Then
Sheets("5").Visible = True
Else
Sheets("5").Visible = False
End If

If [P7] = "True" Then
Sheets("6").Visible = True
Else
Sheets("6").Visible = False
End If

If [P8] = "True" Then
Sheets("7").Visible = True
Else
Sheets("7").Visible = False
End If

If [P9] = "True" Then
Sheets("8").Visible = True
Else
Sheets("8").Visible = False
End If

If [P10] = "True" Then
Sheets("9").Visible = True
Else
Sheets("9").Visible = False
End If

If [P11] = "True" Then
Sheets("10").Visible = True
Else
Sheets("10").Visible = False
End If

End Sub


问:
How do I pass a reference of one object to another and still modify that first object?
I am trying to understand how references work in c++ so I have make a couple files with two different objects. One is an animal and another is a zookeeper. My goal is to pass a reference of an animal to a zookeeper and have the zookeeper change the animal's name, and still be reflected in the original animal object. How is this done using references? Here are the files I'm using.

Source.cpp

```<code>#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"

using namespace std;

int main() {

    Animal animal;
    Animal& animalRef = animal;

    printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());

    //Keep cmd window open
    int j;
    cin >> j;
    return 0;
}
</code>```

Animal.h

```<code>#pragma once
#include <string>

using namespace std;

class Animal {

    string name = "";
    int height = 0;
public:
    string getName() { return name; }
    int getHeight() { return height; }

    void setName(string n) { name = n; }
    void setHeight(int h) { height = h; }
};
</code>```

zookeeper.cpp

```<code>#include "zookeeper.h"

using namespace std;

Zookeeper::Zookeeper(Animal& a) {
    _myAnimal = a;
}

void Zookeeper::changeMyAnimalsName(string newName) {
    _myAnimal.setName(newName);
}
</code>```

zookeeper.h

```<code>#pragma once

#include "Animal.h"

class Zookeeper {
    Animal _myAnimal;
public:
    Zookeeper(Animal& a);
    void changeMyAnimalsName(std::string newName);
};
</code>```

答:
Your class Zookeeper defines data member _myAnimal of type Animal (and not of type Animal&). Hence, if in your constructor you assign _myAnimal = a, then a - though being a reference - is copied because _myAnimal is not a reference.
To keep the reference to the object passed to the constructor, you'd need to define data member _myAnimal as a reference, too:

```<code>class Zookeeper {
    Animal &_myAnimal;
public:
    Zookeeper(Animal& a) : _myAnimal(a) { };
    void changeMyAnimalsName(std::string newName);
};
</code>```

Body:
I am trying to understand how references work in c++ so I have make a couple files with two different objects. One is an animal and another is a zookeeper. My goal is to pass a reference of an animal to a zookeeper and have the zookeeper change the animal's name, and still be reflected in the original animal object. How is this done using references? Here are the files I'm using.

Source.cpp

#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"

using namespace std;

int main() {

    Animal animal;
    Animal& animalRef = animal;

    printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());

    Zookeeper aZookeeper = Zookeeper(animalRef);
    aZookeeper.changeMyAnimalsName("Fred");

    printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());

    //Keep cmd window open
    int j;
    cin >> j;
    return 0;
}

Animal.h

#pragma once
#include <string>

using namespace std;

class Animal {

    string name = "";
    int height = 0;
public:
    string getName() { return name; }
    int getHeight() { return height; }

    void setName(string n) { name = n; }
    void setHeight(int h) { height = h; }
};

zookeeper.cpp

#include "zookeeper.h"

using namespace std;

Zookeeper::Zookeeper(Animal& a) {
    _myAnimal = a;
}

void Zookeeper::changeMyAnimalsName(string newName) {
    _myAnimal.setName(newName);
}

zookeeper.h

#pragma once

#include "Animal.h"

class Zookeeper {
    Animal _myAnimal;
public:
    Zookeeper(Animal& a);
    void changeMyAnimalsName(std::string newName);
};

Body:
Your class Zookeeper defines data member _myAnimal of type Animal (and not of type Animal&). Hence, if in your constructor you assign _myAnimal = a, then a - though being a reference - is copied because _myAnimal is not a reference.
To keep the reference to the object passed to the constructor, you'd need to define data member _myAnimal as a reference, too:

class Zookeeper {
    Animal &_myAnimal;
public:
    Zookeeper(Animal& a) : _myAnimal(a) { };
    void changeMyAnimalsName(std::string newName);
};


问:
Get value of selected radio button which is saved in Firebase, and set it as default state in user profile
```<code>public void showFields(){
    databaseReference = FirebaseDatabase.getInstance().getReference().child("user");
    databaseReference.child(User_Login.userid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            id1.setText(User_Login.userid);
            name1.setText(dataSnapshot.child("name").getValue().toString());
            password1.setText(dataSnapshot.child("password").getValue().toString());
            mobile1.setText(dataSnapshot.child("mobile").getValue().toString());
            city1.setText(dataSnapshot.child("city").getValue().toString());
            area1.setText(dataSnapshot.child("area").getValue().toString());
             //gender.setSelected(dataSnapshot.child("area").getValue().toString());
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

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

How can I set the gender radio button to its selected value from the database, as I did for the Edit Text ones.

答:
Try This

First, u have to store gender value string to Firebase.

gender.equalsIgnoreCase will check if the value of gender equals Man (case man), if true then the radiobutton male will setChecked(true).

```<code>public void showFields(){
databaseReference = FirebaseDatabase.getInstance().getReference().child("user");
databaseReference.child(User_Login.userid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot){
        id1.setText(User_Login.userid);
        name1.setText(dataSnapshot.child("name").getValue().toString());
        password1.setText(dataSnapshot.child("password").getValue().toString());
        mobile1.setText(dataSnapshot.child("mobile").getValue().toString());
        city1.setText(dataSnapshot.child("city").getValue().toString());
        area1.setText(dataSnapshot.child("area").getValue().toString());
         String gender = dataSnapshot.child("gender").getValue().toString();
            if(gender.equalsIgnoreCase("Man")){
                mGenderMan.setChecked(true);
            }else if(gender.equalsIgnoreCase("Woman")){
                mGenderWoman.setChecked(true);
            }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

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

Body:
public void showFields(){
    databaseReference = FirebaseDatabase.getInstance().getReference().child("user");
    databaseReference.child(User_Login.userid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            id1.setText(User_Login.userid);
            name1.setText(dataSnapshot.child("name").getValue().toString());
            password1.setText(dataSnapshot.child("password").getValue().toString());
            mobile1.setText(dataSnapshot.child("mobile").getValue().toString());
            city1.setText(dataSnapshot.child("city").getValue().toString());
            area1.setText(dataSnapshot.child("area").getValue().toString());
             //gender.setSelected(dataSnapshot.child("area").getValue().toString());
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

How can I set the gender radio button to its selected value from the database, as I did for the Edit Text ones.

Body:
Try This

First, u have to store gender value string to Firebase.

gender.equalsIgnoreCase will check if the value of gender equals Man (case man), if true then the radiobutton male will setChecked(true).

public void showFields(){
databaseReference = FirebaseDatabase.getInstance().getReference().child("user");
databaseReference.child(User_Login.userid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot){
        id1.setText(User_Login.userid);
        name1.setText(dataSnapshot.child("name").getValue().toString());
        password1.setText(dataSnapshot.child("password").getValue().toString());
        mobile1.setText(dataSnapshot.child("mobile").getValue().toString());
        city1.setText(dataSnapshot.child("city").getValue().toString());
        area1.setText(dataSnapshot.child("area").getValue().toString());
         String gender = dataSnapshot.child("gender").getValue().toString();
            if(gender.equalsIgnoreCase("Man")){
                mGenderMan.setChecked(true);
            }else if(gender.equalsIgnoreCase("Woman")){
                mGenderWoman.setChecked(true);
            }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});}