问:
Testing with node, mocha and chai (should/bdd syntax)
Context

I'm a JavaScript hobbyist, and to take my project to the next level, I'm trying to setup a pipeline in BitBucket that will run my unit tests (and do other things later on).

I already used Mocha and Chai for testing, but I used it in the browser using an html page that sets up the dependencies and runs the tests.

Problem

The problem I'm facing is that I can't get the should syntax to work in node, while I did have working tests before in the browser. should should be available as part of the Chai library.

I initialized a new project with minimal code in it, but here it also doesn't work: should simply is not assigned.

package.json, including mocha and chai, and setting up mocha for testing.

```<code>{
  "name": "testtest",
  "version": "1.0.0",
  "description": "Minimal, complete and verifiable example",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "chai": "^4.0.1",
    "mocha": "^3.4.2"
  },
  "scripts": {
    "test": "mocha -u bdd"
  },
  "author": "GolezTrol",
  "license": "ISC"
}
</code>```

test/test-foo.js, containing the test. The only thing I added is the first line with require. Before, the browser included the file and Foo was global.
I echoed sut, giving me 5 and sut.should giving me undefined.

```<code>var Foo = require('../src/foo.js').Foo;

describe('Foo', function(){
  it('should flurp gnip snop', function() {
    var sut = Foo.flurp();
    console.log(sut); // 5
    console.log(sut.should); // undefined
    sut.should.be.closeTo(5.00000, 0.00001);
  });
});
</code>```

src/foo.js, the actual unit being tested. In the old setup, Foo would be global (or actually add itself as a property to another global, but that's irrelevant now). I changed this, so it is exported as exports.Foo, so I can require it. This basically works, because I do get '5' in the test.

```<code>exports.Foo = function(){}; // Export Foo

var Foo = exports.Foo;

// Give Foo a method
Foo.flurp = function(){
  return 5;
}
</code>```

The output I get from the test shows 'Foo' (the describe), 5 (the logged result) and undefined (the logged value of sut.should). After that, it obviously shows the formal output that the test has failed:

```<code>  Foo
5
undefined

<clipped for brevity>

  1) Foo should flurp gnip snop:
     TypeError: Cannot read property 'be' of undefined
      at Context.<anonymous> (test\test-foo.js:9:15)
</code>```

Alternative

I can change all  existing unit tests, by adding this line:

```<code>var expect = require('chai').expect;
</code>```

and changing the syntax of the assert to

```<code>expect(sut).to.be.closeTo(5.00000, 0.00001);
</code>```

This is a feasible alternative, since I only got a few dozens of tests. But I'm still interested in finding an answer to the question above.

答:
You need to call the should method to add all should prototype at the beginning</p>

```<code>let should = chai.should();
</code>```

Body:
Context

I'm a JavaScript hobbyist, and to take my project to the next level, I'm trying to setup a pipeline in BitBucket that will run my unit tests (and do other things later on).

I already used Mocha and Chai for testing, but I used it in the browser using an html page that sets up the dependencies and runs the tests.

Problem

The problem I'm facing is that I can't get the should syntax to work in node, while I did have working tests before in the browser. should should be available as part of the Chai library.

I initialized a new project with minimal code in it, but here it also doesn't work: should simply is not assigned.

package.json, including mocha and chai, and setting up mocha for testing.

{
  "name": "testtest",
  "version": "1.0.0",
  "description": "Minimal, complete and verifiable example",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "chai": "^4.0.1",
    "mocha": "^3.4.2"
  },
  "scripts": {
    "test": "mocha -u bdd"
  },
  "author": "GolezTrol",
  "license": "ISC"
}

test/test-foo.js, containing the test. The only thing I added is the first line with require. Before, the browser included the file and Foo was global.
I echoed sut, giving me 5 and sut.should giving me undefined.

var Foo = require('../src/foo.js').Foo;

describe('Foo', function(){
  it('should flurp gnip snop', function() {
    var sut = Foo.flurp();
    console.log(sut); // 5
    console.log(sut.should); // undefined
    sut.should.be.closeTo(5.00000, 0.00001);
  });
});

src/foo.js, the actual unit being tested. In the old setup, Foo would be global (or actually add itself as a property to another global, but that's irrelevant now). I changed this, so it is exported as exports.Foo, so I can require it. This basically works, because I do get '5' in the test.

exports.Foo = function(){}; // Export Foo

var Foo = exports.Foo;

// Give Foo a method
Foo.flurp = function(){
  return 5;
}

The output I get from the test shows 'Foo' (the describe), 5 (the logged result) and undefined (the logged value of sut.should). After that, it obviously shows the formal output that the test has failed:

  Foo
5
undefined

<clipped for brevity>

  1) Foo should flurp gnip snop:
     TypeError: Cannot read property 'be' of undefined
      at Context.<anonymous> (test\test-foo.js:9:15)

Alternative

I can change all  existing unit tests, by adding this line:

var expect = require('chai').expect;

and changing the syntax of the assert to

expect(sut).to.be.closeTo(5.00000, 0.00001);

This is a feasible alternative, since I only got a few dozens of tests. But I'm still interested in finding an answer to the question above.

Body:
You need to call the should method to add all should prototype at the beginning

let should = chai.should();


来源: stackexchange

问:
Prometheus cAdvisor docker monitoring
I've setup a docker monitoring stack using Prometheus, Grafana and cAdvisor. While using this query to get running containers:

```<code>count_scalar(container_last_seen{name=~container1|container2})
</code>```

It picks up the containers allright, as soon as i launch a new container it is picked up right away. The problem is when a container is stopped or removed it does not pick it up, it still shows it as a running container.

From the cAdvisor/metrics endpoint it is removed as soon as the container stops.

Is there something wrong with the query?

(this is what i used for the stack: https://github.com/vegasbrianc/prometheus)

答:
It seems to be related to the amount of time cAdvisor stores the data in memory.

While cAdvisor keeps the data in memory, you still have a valid date in container_last_seen metric. So the count_scalar instruction still 'sees' the container as it has a valid value.

In my test setup, cAdvisor keeps the data during 5 minutes. After this duration, I get the right information out of your formula because the container_last_seen metric has disappeared.

You can change this cAdvisor configuration with the --storage_duration flag.

```<code>--storage_duration=2m0s: How long to store data.
</code>```

As an alternative if you wan't quick alerting, you could also consider running a query that would compare last seen date with current date:

```<code>count_scalar(time()-container_last_seen{name=~"container1|container2"}<=60)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Prometheus cAdvisor docker monitoring

Body:
I've setup a docker monitoring stack using Prometheus, Grafana and cAdvisor. While using this query to get running containers:

count_scalar(container_last_seen{name=~container1|container2})

It picks up the containers allright, as soon as i launch a new container it is picked up right away. The problem is when a container is stopped or removed it does not pick it up, it still shows it as a running container.

From the cAdvisor/metrics endpoint it is removed as soon as the container stops.

Is there something wrong with the query?

(this is what i used for the stack: https://github.com/vegasbrianc/prometheus)

Body:
It seems to be related to the amount of time cAdvisor stores the data in memory.

While cAdvisor keeps the data in memory, you still have a valid date in container_last_seen metric. So the count_scalar instruction still 'sees' the container as it has a valid value.

In my test setup, cAdvisor keeps the data during 5 minutes. After this duration, I get the right information out of your formula because the container_last_seen metric has disappeared.

You can change this cAdvisor configuration with the --storage_duration flag.

--storage_duration=2m0s: How long to store data.

As an alternative if you wan't quick alerting, you could also consider running a query that would compare last seen date with current date:

count_scalar(time()-container_last_seen{name=~"container1|container2"}<=60)


问:
How to narrow down a rounding issue in a Java program?
```<code>public class Rest {
    public static void main(String[] args) {
        double mealCost;
        int tipPercent;
        int taxPercent;
        double totalCost;

        Scanner scan = new Scanner(System.in);

        mealCost = scan.nextDouble();
        tipPercent = scan.nextInt();
        taxPercent = scan.nextInt();

        double tipInD = mealCost * (double)tipPercent / 100;
        double taxInD = mealCost * (double)taxPercent / 100;

        totalCost = (double)mealCost + (double)tipInD + (double)taxInD;

        System.out.println("The total meal cost is "+(int)totalCost+" dollars.");
    }
}
</code>```

This is the program i have created and I have to pass 4 different input cases, 3 of which am passing with this code, but the fourth 1 am not able to.

input cases with expected o/p.

Input for 1st - 3rd cases

```<code>---------
12.00 20 8
----------
15.50 15 10
----------
20.75 10 3
</code>```

Output for 1st - 3rd cases

```<code>---------
The total meal cost is 15 dollars.
---------
The total meal cost is 19 dollars.
---------
The total meal cost is 23 dollars.
</code>```

For the 4th case, the code I have written is not able to give the wanted O/P for it.

Input

```<code>--------
10.25
17
5
</code>```

Output Should Be

The total meal cost is 13 dollars.
And am Getting The total meal cost is 12 dollars.

答:
You are casting an double value to an integer value. Note that by doing so you cut of the number at the decimal point and there is no rounding involved. Your calculation is 10.25*0.17 + 10.25*0.05 + 10.25 = 12.505
By applying the cast you get 12 and not 13. Don't cast your value, and you will be fine.

Body:
public class Rest {
    public static void main(String[] args) {
        double mealCost;
        int tipPercent;
        int taxPercent;
        double totalCost;

        Scanner scan = new Scanner(System.in);

        mealCost = scan.nextDouble();
        tipPercent = scan.nextInt();
        taxPercent = scan.nextInt();

        double tipInD = mealCost * (double)tipPercent / 100;
        double taxInD = mealCost * (double)taxPercent / 100;

        totalCost = (double)mealCost + (double)tipInD + (double)taxInD;

        System.out.println("The total meal cost is "+(int)totalCost+" dollars.");
    }
}

This is the program i have created and I have to pass 4 different input cases, 3 of which am passing with this code, but the fourth 1 am not able to.

input cases with expected o/p.

Input for 1st - 3rd cases

---------
12.00 20 8
----------
15.50 15 10
----------
20.75 10 3

Output for 1st - 3rd cases

---------
The total meal cost is 15 dollars.
---------
The total meal cost is 19 dollars.
---------
The total meal cost is 23 dollars.

For the 4th case, the code I have written is not able to give the wanted O/P for it.

Input

--------
10.25
17
5

Output Should Be

The total meal cost is 13 dollars.
And am Getting The total meal cost is 12 dollars.


问:
Table A drops rows in table B in SQL JOIN
I have two tables which I need joined. I have two select statements with the same columns except OrderValue and SalesTarget:

```<code>SELECT
    b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue
FROM
    dbo.vw_jab_Consolidated_Orders as b
INNER JOIN
    dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson
WHERE
    b.TrnYear = '2017'
ORDER BY
    a.TrnMonth

SELECT
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
FROM
    dbo.vw_jab_SalTargets as a
WHERE
    a.TrnYear = '2017' AND a.SequenceType = 'BR'
GROUP BY
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
</code>```

My problem is that as there are months where there are no OrderValues, the SalesTarget value is being filtered out when I join the two tables as follows:

```<code>SELECT
    a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
FROM
    (SELECT
         TrnYear, SUM(SalesTarget) AS SalesTarget
     FROM
         dbo.vw_jab_SalTargets
     WHERE
         (SequenceType = 'BR')
     GROUP BY
         SequenceType, TrnYear) AS A
LEFT JOIN
    (SELECT
         TrnYear, SUM(ActualSales) AS InvoicedSales
     FROM
         dbo.vw_jab_Consolidated_Sales
     GROUP BY
         TrnYear) AS b ON a.TrnYear = b.TrnYear
WHERE
    a.TrnYear = '2017'
GROUP BY
    a.TrnYear
</code>```

答:
You could switch to a RIGHT JOIN, but then if you have no InvoicedSales, you won't get any SalesTargets.  I'd use a FULL OUTER JOIN like so:

```<code>SELECT COALESCE(a.TrnYear,b.TrnYear) AS TrnYear
    ,SUM(a.SalesTarget) AS SalesTarget
    ,SUM(b.InvoicedSales) AS InvoicedSales
FROM (
    SELECT TrnYear
        ,SUM(SalesTarget) AS SalesTarget
    FROM dbo.vw_jab_SalTargets
    WHERE (SequenceType = 'BR')
    GROUP BY SequenceType
        ,TrnYear
    ) AS a
FULL OUTER JOIN (
    SELECT TrnYear
        ,SUM(ActualSales) AS InvoicedSales
    FROM dbo.vw_jab_Consolidated_Sales
    GROUP BY TrnYear
    ) AS b
    ON a.TrnYear = b.TrnYear
WHERE a.TrnYear = '2017'
    OR b.TrnYear = '2017'
GROUP BY COALESCE(a.TrnYear,b.TrnYear)
</code>```

The COALESCE() is necessary so that the column will always return the TrnYear.

Body:
I have two tables which I need joined. I have two select statements with the same columns except OrderValue and SalesTarget:

SELECT
    b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue
FROM
    dbo.vw_jab_Consolidated_Orders as b
INNER JOIN
    dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson
WHERE
    b.TrnYear = '2017'
ORDER BY
    a.TrnMonth

SELECT
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
FROM
    dbo.vw_jab_SalTargets as a
WHERE
    a.TrnYear = '2017' AND a.SequenceType = 'BR'
GROUP BY
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget

My problem is that as there are months where there are no OrderValues, the SalesTarget value is being filtered out when I join the two tables as follows:

SELECT
    a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
FROM
    (SELECT
         TrnYear, SUM(SalesTarget) AS SalesTarget
     FROM
         dbo.vw_jab_SalTargets
     WHERE
         (SequenceType = 'BR')
     GROUP BY
         SequenceType, TrnYear) AS A
LEFT JOIN
    (SELECT
         TrnYear, SUM(ActualSales) AS InvoicedSales
     FROM
         dbo.vw_jab_Consolidated_Sales
     GROUP BY
         TrnYear) AS b ON a.TrnYear = b.TrnYear
WHERE
    a.TrnYear = '2017'
GROUP BY
    a.TrnYear

Body:
You could switch to a RIGHT JOIN, but then if you have no InvoicedSales, you won't get any SalesTargets.  I'd use a FULL OUTER JOIN like so:

SELECT COALESCE(a.TrnYear,b.TrnYear) AS TrnYear
    ,SUM(a.SalesTarget) AS SalesTarget
    ,SUM(b.InvoicedSales) AS InvoicedSales
FROM (
    SELECT TrnYear
        ,SUM(SalesTarget) AS SalesTarget
    FROM dbo.vw_jab_SalTargets
    WHERE (SequenceType = 'BR')
    GROUP BY SequenceType
        ,TrnYear
    ) AS a
FULL OUTER JOIN (
    SELECT TrnYear
        ,SUM(ActualSales) AS InvoicedSales
    FROM dbo.vw_jab_Consolidated_Sales
    GROUP BY TrnYear
    ) AS b
    ON a.TrnYear = b.TrnYear
WHERE a.TrnYear = '2017'
    OR b.TrnYear = '2017'
GROUP BY COALESCE(a.TrnYear,b.TrnYear)

The COALESCE() is necessary so that the column will always return the TrnYear.


问:
How to access the keys from an object to method
```<code>var myParser = {
    instr: document.getElementById("pString"),
    v1: [],
    crstr: function() {
        return this.instr.value;
    },
    aV: function() {
        for(i=0;i<this.instr.lenght;i++) {
            if(this.instr[i] == '(') this.v1.push(0);
        }
        return this.v1;
    }
}
</code>```

Above is my object. I want to make a method in my object to access the keys from the object and put a value in v1 array. How can I access the keys from my object in the aV method?

Thank you!

Here is the display code:

```<code>function pSubmit() {
    document.write(myParser.crstr() + '</br>');
    document.write(myParser.aV());
}
</code>```

答:
Do you need to access keys from this object? if that is the case, then:

var myParser = {
instr: document.getElementById("pString"),
v1: [],
crstr: function() {
    return this.instr.value;
},
aV: function() {
    for(i=0;i<this.instr.lenght;i++)
        if(this.instr[i] == '(') this.v1.push(0);
    return this.v1;
},
getKeys:function(){
  this.v1 = Object.keys(this)
}}
myParser.getKeys()
console.log(myParser.v1)```
</div>
</div>
</p>

<p>If you are providing another object, then:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myParser = {
instr: document.getElementById("pString"),
v1: [],
crstr: function() {
    return this.instr.value;
},
aV: function() {
    for(i=0;i<this.instr.lenght;i++)
        if(this.instr[i] == '(') this.v1.push(0);
    return this.v1;
},
getKeys:function(obj){
  this.v1 = Object.keys(obj)
}}
var foo = {a:2,b:3}
myParser.getKeys(foo)
console.log(myParser.v1)</code>```

EDIT: I'm still not sure what are you trying to do, but 2 things to fix is length instead of lenght, and "this.instr" is HTML element, this.instr.value is string.

var myParser = {
    instr: document.getElementById("pString"),
    v1: [],
    crstr: function() {
        return this.instr.value;
    },
    aV: function() {
      var str = this.instr.value;
        for(i=0;i<str.length;i++) {
            if(str[i] == '(') this.v1.push(0);
        }
        return this.v1;
    }
}

console.log(myParser.aV())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="pString" value="(abc)"></code>```

Body:
var myParser = {
    instr: document.getElementById("pString"),
    v1: [],
    crstr: function() {
        return this.instr.value;
    },
    aV: function() {
        for(i=0;i<this.instr.lenght;i++) {
            if(this.instr[i] == '(') this.v1.push(0);
        }
        return this.v1;
    }
}

Above is my object. I want to make a method in my object to access the keys from the object and put a value in v1 array. How can I access the keys from my object in the aV method?

Thank you!

Here is the display code:

function pSubmit() {
    document.write(myParser.crstr() + '
');
    document.write(myParser.aV());
}

Body:
Do you need to access keys from this object? if that is the case, then:

var myParser = {
instr: document.getElementById("pString"),
v1: [],
crstr: function() {
    return this.instr.value;
},
aV: function() {
    for(i=0;i<this.instr.lenght;i++)
        if(this.instr[i] == '(') this.v1.push(0);
    return this.v1;
},
getKeys:function(){
  this.v1 = Object.keys(this)
}}
myParser.getKeys()
console.log(myParser.v1)

If you are providing another object, then:

var myParser = {
instr: document.getElementById("pString"),
v1: [],
crstr: function() {
    return this.instr.value;
},
aV: function() {
    for(i=0;i<this.instr.lenght;i++)
        if(this.instr[i] == '(') this.v1.push(0);
    return this.v1;
},
getKeys:function(obj){
  this.v1 = Object.keys(obj)
}}
var foo = {a:2,b:3}
myParser.getKeys(foo)
console.log(myParser.v1)

EDIT: I'm still not sure what are you trying to do, but 2 things to fix is length instead of lenght, and "this.instr" is HTML element, this.instr.value is string.

var myParser = {
    instr: document.getElementById("pString"),
    v1: [],
    crstr: function() {
        return this.instr.value;
    },
    aV: function() {
      var str = this.instr.value;
        for(i=0;i<str.length;i++) {
            if(str[i] == '(') this.v1.push(0);
        }
        return this.v1;
    }
}

console.log(myParser.aV())

<input id="pString" value="(abc)">


问:
Batch file to split text file into multiple files in same directory on Win Svr 2012 using NO 3rd Party Apps
I am hoping the wonderful experts here can assist me with my problem.  I have found this site extremely useful in the past in solving other issues I have had but I have searched this site and tried all the answers similar to my problem but cant seem to get any of them to work for this particular problem. I am not a coder but have dabbled with other code and got them to work for other issues.

I need to split a text file containing keywords(1 kw per line, no blank lines) into multiple text files within the same directory, each with 300 lines (except last text file if total input lines not exactly divisible by 300). The input file will NEVER be larger than 100MB.

Ideally, I then need the input file deleted once it has been split and all split text files moved to another directory (there are no other text files to worry about in the original directory)
I need it to be a bat file or vbs script called via bat file.

input file:

keyword-file.txt

output files:

keyword-file_1.txt (300 lines)

keyword-file_2.txt (300 lines)

keyword-file_3.txt (300 lines)

etc

To clarify requirements the above:

Split input text file (<100MB) into smaller text files, each with 300 lines

Delete input text file

Move all split text files to another specified directory

答:
For the splitting, perhaps something like this will do:

@Echo Off
Setlocal EnableExtensions DisableDelayedExpansion

Set "inFile=keyword-file.txt"
Set "nLines=300"

If Not Exist "%inFile%" GoTo :EOF
For %%A In ("%inFile%") Do Set "fName=%%~nA"&Set "fExt=%%~xA"

Set "count=0"
For /F %%A In ('Find /C /V ""^<"%inFile%"') Do Set "fLines=%%A"

(For /L %%A In (1 1 %fLines%) Do (Set/P "data="
    Set/A "file=(count/%nLines%)+1", "count+=1"
    SetLocal EnableDelayedExpansion
    (Echo=!data!)>>"%fName%_!file!%fExt%"
    EndLocal))<"%inFile%"

EndLocal
GoTo :EOF
```

I'll leave the deletion and move commands to you…

Body:
For the splitting, perhaps something like this will do:

@Echo Off
Setlocal EnableExtensions DisableDelayedExpansion

Set "inFile=keyword-file.txt"
Set "nLines=300"

If Not Exist "%inFile%" GoTo :EOF
For %%A In ("%inFile%") Do Set "fName=%%~nA"&Set "fExt=%%~xA"

Set "count=0"
For /F %%A In ('Find /C /V ""^<"%inFile%"') Do Set "fLines=%%A"

(For /L %%A In (1 1 %fLines%) Do (Set/P "data="
    Set/A "file=(count/%nLines%)+1", "count+=1"
    SetLocal EnableDelayedExpansion
    (Echo=!data!)>>"%fName%_!file!%fExt%"
    EndLocal))<"%inFile%"

EndLocal
GoTo :EOF

I'll leave the deletion and move commands to you…


问:
How to combine multiple QueryDescriptor in hibernate elastic search
I am new to hibernate elastic search. I have gone through the official document and I found, to get the data from elastic search I have to write following code.

```<code>FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryDescriptor query = ElasticsearchQueries.fromQueryString("title:tales");
List<?> result = fullTextSession.createFullTextQuery(query, ComicBook.class).list();
</code>```

But I am trying to understand how can I combine multiple QueryDescriptor into BooleanJunction as it is only taking lucene query.

答:
ElasticsearchQueries.fromQueryString is a way to avoid the Hibernate Search DSL, which includes BooleanJunction in particular. You can use ElasticsearchQueries.fromQueryString, or the Hibernate Search DSL, but not both in the same query.

If you really want to stick with ElasticsearchQueries.fromQueryString, this becomes a problem of understanding the syntax of Elasticsearch queries. Something like that should do the trick

```<code>FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryDescriptor query = ElasticsearchQueries.fromQueryString("title:tales AND someOtherField:someOtherValue");
List result = fullTextSession.createFullTextQuery(query, ComicBook.class).list();
</code>```

You can have a look at the Elasticsearch documentation for more information on the syntax: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-query-string-query.html

Note that, unless your queries are particularly complex, you shouldn't need to use ElasticsearchQueries.fromQueryString; the Hibernate Search DSL should work equally well, and may spare you some time trying to fix your queries (because you would use Java code, which is mostly checked at compile time, instead of String queries validated at runtime). More information on the Query DSL can be found here: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query

ContentLicense: CC BY-SA 4.0

Body:
I am new to hibernate elastic search. I have gone through the official document and I found, to get the data from elastic search I have to write following code.

FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryDescriptor query = ElasticsearchQueries.fromQueryString("title:tales");
List<?> result = fullTextSession.createFullTextQuery(query, ComicBook.class).list();

But I am trying to understand how can I combine multiple QueryDescriptor into BooleanJunction as it is only taking lucene query.

Body:
ElasticsearchQueries.fromQueryString is a way to avoid the Hibernate Search DSL, which includes BooleanJunction in particular. You can use ElasticsearchQueries.fromQueryString, or the Hibernate Search DSL, but not both in the same query.

If you really want to stick with ElasticsearchQueries.fromQueryString, this becomes a problem of understanding the syntax of Elasticsearch queries. Something like that should do the trick

FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryDescriptor query = ElasticsearchQueries.fromQueryString("title:tales AND someOtherField:someOtherValue");
List result = fullTextSession.createFullTextQuery(query, ComicBook.class).list();

You can have a look at the Elasticsearch documentation for more information on the syntax: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-query-string-query.html

Note that, unless your queries are particularly complex, you shouldn't need to use ElasticsearchQueries.fromQueryString; the Hibernate Search DSL should work equally well, and may spare you some time trying to fix your queries (because you would use Java code, which is mostly checked at compile time, instead of String queries validated at runtime). More information on the Query DSL can be found here: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query


问:
Replace one URL with another by using mod_rewrite
Current situation

```<code>RewriteRule ^$ /index.php?page=Portal [R=301,L]
</code>```

When a user comes to the website and goes to the "root" url of the domain (RegExp "^$") he's redirected to /index.php?page=Portal

That's working.

Now we have "index.php?page=Portal" in the google index and we have tons of links to that page on various locations all over the internet.

Intended new situation

We want the portal page to show up on the root url - no redirect. That's no problem... Just remove the redirect:

```<code>RewriteRule ^$ /index.php?page=Portal [L]
</code>```

Now we also want the old url to redirect to the new location, and that's where I fail but can't see why:

```<code>RewriteCond %{QUERY_STRING} ^page=Portal$
RewriteRule ^index.php$ http://www.jacatu.de/? [R=301,L]
</code>```

As soon as I do this I end up in a redirect loop:

(When I change to 302 in .htaccess I see 302 redirects, so the loop really seems to be caused by mod_rewrite)

But why? All rules are marked as last [L] - so I think I can rule out that rule 2 triggers rule 1.

答:
I enabled logging as suggested by Jacek Prucia and in fact it looked like having [L] in the URL doesn't stop execution. Both rules were processed.

I now changed the first rewrite to

```<code>RewriteRule ^$ /index.php?page=Portal&int=1 [L]
</code>```

so that it doesn't match the RewriteCond of the internal rewrite so theoretically my problem is solved. It would be nice to know, though, why it did what it did. :)

ContentLicense: CC BY-SA 2.5

Body:
Current situation

RewriteRule ^$ /index.php?page=Portal [R=301,L]

When a user comes to the website and goes to the "root" url of the domain (RegExp "^$") he's redirected to /index.php?page=Portal

That's working.

Now we have "index.php?page=Portal" in the google index and we have tons of links to that page on various locations all over the internet.

Intended new situation

We want the portal page to show up on the root url - no redirect. That's no problem... Just remove the redirect:

RewriteRule ^$ /index.php?page=Portal [L]

Now we also want the old url to redirect to the new location, and that's where I fail but can't see why:

RewriteCond %{QUERY_STRING} ^page=Portal$
RewriteRule ^index.php$ http://www.jacatu.de/? [R=301,L]

As soon as I do this I end up in a redirect loop:

(When I change to 302 in .htaccess I see 302 redirects, so the loop really seems to be caused by mod_rewrite)

But why? All rules are marked as last [L] - so I think I can rule out that rule 2 triggers rule 1.

Body:
I enabled logging as suggested by Jacek Prucia and in fact it looked like having [L] in the URL doesn't stop execution. Both rules were processed.

I now changed the first rewrite to

RewriteRule ^$ /index.php?page=Portal&int=1 [L]

so that it doesn't match the RewriteCond of the internal rewrite so theoretically my problem is solved. It would be nice to know, though, why it did what it did. :)


问:
PHP: number_format issue
Iv taken over a very old php project that is still currently in use.
Its a custom "shopping" website.

When a product gets ordered it inserts the money value into the database as a string of integers:

```<code>2000
</code>```

which then gets outputted as follows:

R20,00

Using this code

```<code>echo number_format($order['order_total'] / 100, 2, ",", "");
</code>```

My problem is that if an order gets placed to the value of R 15 256.00
The record gets inserted as such:

```<code>15256
</code>```

and gets outputted to the user as:

R 152,56

But it should ultimately show like this

R15, 256.00

I do understand that the problem comes in by dividing the amount by 100 in the above query. If i alter the query then the larger numbers appear fine but the smaller amounts such as R20,00 get shown as R2000,00

Any help would be great.

答:
Try This

```<code>echo number_format($order['order_total'] / 100, 2, ".", ",");
</code>```

you can read more about number format here .

Title: PHP: number_format issue

Body:
Iv taken over a very old php project that is still currently in use.
Its a custom "shopping" website.

When a product gets ordered it inserts the money value into the database as a string of integers:

2000

which then gets outputted as follows:

R20,00

Using this code

echo number_format($order['order_total'] / 100, 2, ",", "");

My problem is that if an order gets placed to the value of R 15 256.00
The record gets inserted as such:

15256

and gets outputted to the user as:

R 152,56

But it should ultimately show like this

R15, 256.00

I do understand that the problem comes in by dividing the amount by 100 in the above query. If i alter the query then the larger numbers appear fine but the smaller amounts such as R20,00 get shown as R2000,00

Any help would be great.

Body:
Try This

echo number_format($order['order_total'] / 100, 2, ".", ",");

you can read more about number format here .


问:
Error in c++ openCv my very first code (median filter)
hi I just started c++/openCv and trying to write a median code
i'm cinda confused......

EDIT2:
OK thank to dear friends my first error is corrected
now this is my new error :|
I want to sort 9 elemented Mat file. could I use onother type for window not Mat file? how can I sort it corectly

the error refers to this line:
std::sort(window.begin(), window.end());
error: request for member 'begin' in 'window', which is of non-class type 'cv::Mat [9]'|
|36|error: request for member 'end' in 'window', which is of non-class type 'cv::Mat [9]'|

I exped matlab and i'm a complete noob at c++, this is my code:

```<code>using namespace std;
using namespace cv;
Mat img_gray,img;

int main ()
{

img = imread( "6.jpg", IMREAD_COLOR ); // Load an image
if( img.empty() )
    { return -1; }
cvtColor( img, img_gray, COLOR_BGR2GRAY );
int M = img.rows;
int N = img.cols;
cvNamedWindow("windows",WINDOW_AUTOSIZE);
imshow("windows",img);
for (int m = 2; m < M - 1; ++m)
    for (int n = 2; n < N - 1; ++n)
    {
        int k = 0;
        int tmpmedian = 0;
        //int window[9]={0};
        Mat window[9];
        for (int i = m - 1; i < m + 2; ++i){
            for (int j = n - 1; j < n + 2; ++j)
            {
                window[k++] = img_gray.at<uchar>(i, j);
            }
            std::sort(window.begin(), window.end());
            tmpmedian = window[5];
            fimg[m][n] = tmpmedian;
        }
    }
}
</code>```

i'm a student and need this for my class project
and I appreciate your responses thanks alot

答:
In your double for loop, try this.

```<code>int k = 0;
int tmpmedian = 0;
int window[9]={0};
for (int i = m - 1; i < m + 2; ++i)
    for (int j = n - 1; j < n + 2; ++j)
        window[k++] = img_gray.at<uchar>(i, j);
std::sort(std::begin(window), std::end(window));
tmpmedian = window[4];
fimg[m][n] = tmpmedian;
</code>```

Mat window[9] declares an array of 9 Mat type object. I don't think you'd want that. You just need an array of 9 int values. So what you need is int window[9].

Your usage of std::begin() and std::end() is wrong. std::sort(std::begin(window), std::end(window)) is what you need.

Array indices are zero-based. So your median number is stored at window[4] not window[5].

Body:
hi I just started c++/openCv and trying to write a median code
i'm cinda confused......

EDIT2:
OK thank to dear friends my first error is corrected
now this is my new error :|
I want to sort 9 elemented Mat file. could I use onother type for window not Mat file? how can I sort it corectly

the error refers to this line:
std::sort(window.begin(), window.end());
error: request for member 'begin' in 'window', which is of non-class type 'cv::Mat [9]'|
|36|error: request for member 'end' in 'window', which is of non-class type 'cv::Mat [9]'|

I exped matlab and i'm a complete noob at c++, this is my code:

using namespace std;
using namespace cv;
Mat img_gray,img;

int main ()
{

img = imread( "6.jpg", IMREAD_COLOR ); // Load an image
if( img.empty() )
    { return -1; }
cvtColor( img, img_gray, COLOR_BGR2GRAY );
int M = img.rows;
int N = img.cols;
cvNamedWindow("windows",WINDOW_AUTOSIZE);
imshow("windows",img);
for (int m = 2; m < M - 1; ++m)
    for (int n = 2; n < N - 1; ++n)
    {
        int k = 0;
        int tmpmedian = 0;
        //int window[9]={0};
        Mat window[9];
        for (int i = m - 1; i < m + 2; ++i){
            for (int j = n - 1; j < n + 2; ++j)
            {
                window[k++] = img_gray.at<uchar>(i, j);
            }
            std::sort(window.begin(), window.end());
            tmpmedian = window[5];
            fimg[m][n] = tmpmedian;
        }
    }
}

i'm a student and need this for my class project
and I appreciate your responses thanks alot

Body:
In your double for loop, try this.

int k = 0;
int tmpmedian = 0;
int window[9]={0};
for (int i = m - 1; i < m + 2; ++i)
    for (int j = n - 1; j < n + 2; ++j)
        window[k++] = img_gray.at<uchar>(i, j);
std::sort(std::begin(window), std::end(window));
tmpmedian = window[4];
fimg[m][n] = tmpmedian;

Mat window[9] declares an array of 9 Mat type object. I don't think you'd want that. You just need an array of 9 int values. So what you need is int window[9].

Your usage of std::begin() and std::end() is wrong. std::sort(std::begin(window), std::end(window)) is what you need.

Array indices are zero-based. So your median number is stored at window[4] not window[5].


问:
Alter table structure to match copy table
I have 2 tables corporate and corporate_copy. Initially they were same in structure but people started added new columns into corporate and forgot do do so for corporate_copy.

Somewhere in the application there is less used functionality that copies data from corporate to corporate_copy and that kept failing without anyone noticing. Now I have to add 28 columns (ofcourse with same type and length and constraints etc....).

I know it can be done in one ALTER TABLE statement but I still feel it is lengthy task.

Do we have any luxury that will make copy table same as main table by keeping data and adding default values in newly added columns?

I am asking much but is there anything like that?

答:
From SQL-Server 2015, you can use the following query to extract all different columns between 2 tables:

```<code>select distinct a.* from INFORMATION_SCHEMA.COLUMNS a
where a.column_name not in (select column_name from INFORMATION_SCHEMA.COLUMNS b
where b.table_name in ('tbl_A'))
and a.table_name in ('tbl_B')
order by a.column_name
</code>```

The output gives you enough information to create a simple script to add the columns which are missing:

For exmaple:

```<code>Alter table tbl_A ADD res.Column_Name res.Data_Type ....
</code>```

Body:
From SQL-Server 2015, you can use the following query to extract all different columns between 2 tables:

select distinct a.* from INFORMATION_SCHEMA.COLUMNS a
where a.column_name not in (select column_name from INFORMATION_SCHEMA.COLUMNS b
where b.table_name in ('tbl_A'))
and a.table_name in ('tbl_B')
order by a.column_name

The output gives you enough information to create a simple script to add the columns which are missing:

For exmaple:

Alter table tbl_A ADD res.Column_Name res.Data_Type ....


答:
I think, from what you do expect, you just want to print:

```<code>System.out.println("The total meal cost is " + Math.round(totalCost) + " dollars.");
</code>```

instead of.

```<code>System.out.println("The total meal cost is " +(int)totalCost + " dollars.");
</code>```

The first one will properly round based on the mathematical rules, the second one will just stripe of the floating point values. That´s why the last one results in 12 and not 13, because it doesn´t actually round.

Title: How to narrow down a rounding issue in a Java program?

Body:
I think, from what you do expect, you just want to print:

System.out.println("The total meal cost is " + Math.round(totalCost) + " dollars.");

instead of.

System.out.println("The total meal cost is " +(int)totalCost + " dollars.");

The first one will properly round based on the mathematical rules, the second one will just stripe of the floating point values. That´s why the last one results in 12 and not 13, because it doesn´t actually round.


答:
That should be possible using SELECT INTO, for example the following SQL statement creates a backup copy of corporate:

```<code>SELECT * INTO corporate_copy
FROM corporate ;
</code>```

Title: Alter table structure to match copy table

Body:
I have 2 tables corporate and corporate_copy. Initially they were same in structure but people started added new columns into corporate and forgot do do so for corporate_copy.

Somewhere in the application there is less used functionality that copies data from corporate to corporate_copy and that kept failing without anyone noticing. Now I have to add 28 columns (ofcourse with same type and length and constraints etc....).

I know it can be done in one ALTER TABLE statement but I still feel it is lengthy task.

Do we have any luxury that will make copy table same as main table by keeping data and adding default values in newly added columns?

I am asking much but is there anything like that?

Body:
That should be possible using SELECT INTO, for example the following SQL statement creates a backup copy of corporate:

SELECT * INTO corporate_copy
FROM corporate ;


问:
Is it a Security Issue in Codeigniter which Allow to Run Controller Functions using URL?
I am not sure that this is a security  issue or I understand something wrongly? That's why I ask this question.

As I understood, Anyone can run any controller function using URL. Assume that I have a controller function called delete in controller called user.

So anyone can run that function using

```<code>http://example.com/index.php/user/delete
</code>```

Is it a securty issue?

I mean in pure PHP, you can't run any function via URL even you know the custom function name.

But seems like anyone can run any function in Codeigniter Controller if they know the controller name and function name. Is it a security issue or I understand something wrongly?

答:
In the example you give of a delete method there is a potential for mischief. You don't show a parameter being sent to delete but one would be required in order to identify the user to be deleted. A hostile operator could call delete and try random user id values. To be "secure" some kind of authentication/permission system must be in place where the delete method does not proceed unless the user is known and has appropriate permission.

The same applies to any "add", "edit" and possibly "view" methods dealing with "users".

Really, any UI that deals with creating, updating, reading, and deleting (CRUD) any data should have an authentication/permissions system in place.

This need is not unique to CodeIgniter.

Body:
I am not sure that this is a security  issue or I understand something wrongly? That's why I ask this question.

As I understood, Anyone can run any controller function using URL. Assume that I have a controller function called delete in controller called user.

So anyone can run that function using

http://example.com/index.php/user/delete

Is it a securty issue?

I mean in pure PHP, you can't run any function via URL even you know the custom function name.

But seems like anyone can run any function in Codeigniter Controller if they know the controller name and function name. Is it a security issue or I understand something wrongly?


答:
A working solution is changing your output to

```<code>System.out.println("The total meal cost is " + (int) Math.ceil(totalCost) + " dollars.");
</code>```

Explanation can be found here

Body:
public class Rest {
    public static void main(String[] args) {
        double mealCost;
        int tipPercent;
        int taxPercent;
        double totalCost;

        Scanner scan = new Scanner(System.in);

        mealCost = scan.nextDouble();
        tipPercent = scan.nextInt();
        taxPercent = scan.nextInt();

        double tipInD = mealCost * (double)tipPercent / 100;
        double taxInD = mealCost * (double)taxPercent / 100;

        totalCost = (double)mealCost + (double)tipInD + (double)taxInD;

        System.out.println("The total meal cost is "+(int)totalCost+" dollars.");
    }
}

This is the program i have created and I have to pass 4 different input cases, 3 of which am passing with this code, but the fourth 1 am not able to.

input cases with expected o/p.

Input for 1st - 3rd cases

---------
12.00 20 8
----------
15.50 15 10
----------
20.75 10 3

Output for 1st - 3rd cases

---------
The total meal cost is 15 dollars.
---------
The total meal cost is 19 dollars.
---------
The total meal cost is 23 dollars.

For the 4th case, the code I have written is not able to give the wanted O/P for it.

Input

--------
10.25
17
5

Output Should Be

The total meal cost is 13 dollars.
And am Getting The total meal cost is 12 dollars.

Body:
A working solution is changing your output to

System.out.println("The total meal cost is " + (int) Math.ceil(totalCost) + " dollars.");

Explanation can be found here


问:
Doing operations with only Nth element of a list
I want to multiply only every second number on a list(0-100) but I just can't get it to work.</p>

答:
Use range() to generate the indexes of the entries you want to change...

```<code>numbers = [1, 2, 3, 4, 5, 6, 7, 8]

for i in range(1, len(numbers), 2):
    numbers[i] *= 2
</code>```

will result in numbers containing the list

```<code>[1, 4, 3, 8, 5, 12, 7, 16]
</code>```

Body:
Use range() to generate the indexes of the entries you want to change...

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

for i in range(1, len(numbers), 2):
    numbers[i] *= 2

will result in numbers containing the list

[1, 4, 3, 8, 5, 12, 7, 16]


问:
Round date long value
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

```<code>long time = 12136219;
Date date = new Date(time);
</code>```

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?

答: When you create a Date from a long, the long represents the number of milliseconds since Jan 1, 1970.  There are 60*1000 milliseconds in a minute.  That should be enough information to fashion the rounding algorithm you need.

Title: Round date long value

Body:
In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

long time = 12136219;
Date date = new Date(time);

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?


问:
Correct way of implementing Finalize and Dispose(When parent class implements IDisposable)
I was implementing Finalize and Dispose in my classes, I implemented IDisposable on my parent class and override the Dispose(bool) overload in my child classes. I was not sure

whether to use a duplicate isDisposed variable(as its already there in base class) or not?

Whether to implement a finalizer in child class too or not?

Both these things are done in example given here -

http://guides.brucejmack.biz/CodeRules/FxCop/Docs/Rules/Usage/DisposeMethodsShouldCallBaseClassDispose.html

Whereas example in this MSDN article doesn't have any of these two -
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

whereas this example in MSDN is not complete -
http://msdn.microsoft.com/en-us/library/ms182330.aspx

答:
1) No need to duplicate

2) Implementing a finalizer will help to dispose items that are not explicitly disposed. But is not guaranteed. It is a good practice to do.


问:
loading json from text file
I am trying to run this code but it creates error.

```<code>import json
import requests
import pprint
data = []
with open('data.txt') as o1:
  for line in o1:
    data.append(json.loads(line))
    print(data)
    print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())
</code>```

it shows

```<code>Value Error: No json object could be Decoded
</code>```

I am new to programming and not able to figure out what is the problem.

答:
i solved my problem using this:</p>

```<code>data =[]
with open('data.txt') as f:
   for line in f:
      data = json.loads(line)
      print(data)
      url = 'http://xyz.abcdfx.cn/devicedata'
      body_json=json.dumps(data)
      headers = {'Content-Type':'application/json'}
      d = requests.post(url, data = body_json, headers=headers)
      pprint.pprint(d.json())
</code>```

Title: loading json from text file

Body:
I am trying to run this code but it creates error.

import json
import requests
import pprint
data = []
with open('data.txt') as o1:
  for line in o1:
    data.append(json.loads(line))
    print(data)
    print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())

it shows

Value Error: No json object could be Decoded

I am new to programming and not able to figure out what is the problem.

Body:
i solved my problem using this:

data =[]
with open('data.txt') as f:
   for line in f:
      data = json.loads(line)
      print(data)
      url = 'http://xyz.abcdfx.cn/devicedata'
      body_json=json.dumps(data)
      headers = {'Content-Type':'application/json'}
      d = requests.post(url, data = body_json, headers=headers)
      pprint.pprint(d.json())


问:
I can't change chmod to 777 in Android programmatically
I have a rooted device, and want to change the chmod permission of an apk(Prueba.apk) that is inside /system/app , so to achieve that I am using the RootTools library with BusyBox. And my code is:

```<code>        Command comando = new Command(0, "chmod 777 /system/app/Prueba.apk");
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }
</code>```

But when I check, after running that code with a Root file explorer I see that the chmod permissions for Prueba.apk didn't change.

答:
The problem was that when I mounted the system partition as RW I did it like this:

```<code>        Command comando = new Command(0, "mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system/app";
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }
</code>```

But the correct way is making ALL system partition RW instead of just /system/app folder, so I changed the code to:

```<code>        Command comando = new Command(0, "mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system";
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }
</code>```

And then I could execute chmod 777 command perfectly.

Body:
I have a rooted device, and want to change the chmod permission of an apk(Prueba.apk) that is inside /system/app , so to achieve that I am using the RootTools library with BusyBox. And my code is:

        Command comando = new Command(0, "chmod 777 /system/app/Prueba.apk");
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }

But when I check, after running that code with a Root file explorer I see that the chmod permissions for Prueba.apk didn't change.

Body:
The problem was that when I mounted the system partition as RW I did it like this:

        Command comando = new Command(0, "mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system/app";
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }

But the correct way is making ALL system partition RW instead of just /system/app folder, so I changed the code to:

        Command comando = new Command(0, "mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system";
    try {
        RootTools.getShell(true).add(comando);
    } catch (IOException | RootDeniedException | TimeoutException ex) {
        ex.printStackTrace();
    }

And then I could execute chmod 777 command perfectly.


答:
Reset seconds and milliseconds with Calendar.set

```<code>Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MINUTES, calendar.get(Calendar.SECOND) >= 30 ? 1 : 0)
currentDate = cal.getTimeInMillis();
</code>```

Sets the given calendar field to the given value. The value is not interpreted by this method regardless of the leniency mode.

Title: Round date long value

Body:
Reset seconds and milliseconds with Calendar.set

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MINUTES, calendar.get(Calendar.SECOND) >= 30 ? 1 : 0)
currentDate = cal.getTimeInMillis();

Sets the given calendar field to the given value. The value is not interpreted by this method regardless of the leniency mode.


问:
css autoprefixer with webpack
I have been trying to configure webpack with LESS and Autoprefixer, but autoprefixer does not seem to work. My css or less files are not autoprefixed. Example:
display: flex stays display: flex

I have put my webpack config below:

```<code>var autoprefixer = require('autoprefixer');

module.exports = {
  entry: {
    bundle: "./index.jsx"
  },
  output: {
    path: __dirname,
    filename: "[name].js"
  },
  module: {
    loaders: [
      {
        test: /\.jsx$/,
        exclude: /(node_modules|bower_components)/,
        loaders: ['react-hot', 'babel-loader']
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader!less-loader")
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader")
      }

    ],
    postcss: function () {
      return [autoprefixer];
    }
  },
  plugins: [
    new webpack.BannerPlugin(banner),
    new ExtractTextPlugin("style.css")
  ],
  devtool: 'source-map',
  devServer: {
    stats: 'warnings-only',
  }
};
</code>```

答:
I was having a similar issue with Webpack 2.x.x and custom properties are no longer allowed in configuration. I found a solution on this other S.O post: Using auto prefixer with postcss in webpack 2.0. In case for some unknown reason this link would lead to a 404 I  compile the most relevant answers here:

Webpack 2.x.x introduced webpack.LoaderOptionsPlugin() plugin where you need to define all the loader option plugins. Like, autoprefixer is a plugin for postcss-loader. So, it has to go here.
New config should look like this:

```<code>module: {
  rules: [
    {
      test: /\.scss$/,
      loaders: ['style-loader', 'css-loader', 'sass-loader',
      'postcss-loader']
    }
  ]
},

plugins: [
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer(),
      ]
    }
  })
],
</code>```

This worked for me, but as mentioned by Kreig there is no need for LoaderOptionsPlugin(). You can now pass options directly to the loader declaration:

```<code>const autoprefixer = require('autoprefixer');

let settings = {
/*...*/
  module: {
    rules: [{
      test: /\.css$/,
        use: [
          /*...other loaders...*/
          {
            loader: 'postcss-loader',
              options: {
                plugins: function () {
                  return [autoprefixer]
                }
              }
          }
          /*...other loaders...*/
       ]
    }]
  }
}
/*...*/
</code>```

Thing is I've tried the 2nd with Webpack 2.5.1 but it failed. Credits goes to Pranesh Ravi and Kreig.

Title: css autoprefixer with webpack

Body:
I have been trying to configure webpack with LESS and Autoprefixer, but autoprefixer does not seem to work. My css or less files are not autoprefixed. Example:
display: flex stays display: flex

I have put my webpack config below:

var autoprefixer = require('autoprefixer');

module.exports = {
  entry: {
    bundle: "./index.jsx"
  },
  output: {
    path: __dirname,
    filename: "[name].js"
  },
  module: {
    loaders: [
      {
        test: /\.jsx$/,
        exclude: /(node_modules|bower_components)/,
        loaders: ['react-hot', 'babel-loader']
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader!less-loader")
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader")
      }

    ],
    postcss: function () {
      return [autoprefixer];
    }
  },
  plugins: [
    new webpack.BannerPlugin(banner),
    new ExtractTextPlugin("style.css")
  ],
  devtool: 'source-map',
  devServer: {
    stats: 'warnings-only',
  }
};

Body:
I was having a similar issue with Webpack 2.x.x and custom properties are no longer allowed in configuration. I found a solution on this other S.O post: Using auto prefixer with postcss in webpack 2.0. In case for some unknown reason this link would lead to a 404 I  compile the most relevant answers here:

Webpack 2.x.x introduced webpack.LoaderOptionsPlugin() plugin where you need to define all the loader option plugins. Like, autoprefixer is a plugin for postcss-loader. So, it has to go here.
New config should look like this:

module: {
  rules: [
    {
      test: /\.scss$/,
      loaders: ['style-loader', 'css-loader', 'sass-loader',
      'postcss-loader']
    }
  ]
},

plugins: [
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer(),
      ]
    }
  })
],

This worked for me, but as mentioned by Kreig there is no need for LoaderOptionsPlugin(). You can now pass options directly to the loader declaration:

const autoprefixer = require('autoprefixer');

let settings = {
/*...*/
  module: {
    rules: [{
      test: /\.css$/,
        use: [
          /*...other loaders...*/
          {
            loader: 'postcss-loader',
              options: {
                plugins: function () {
                  return [autoprefixer]
                }
              }
          }
          /*...other loaders...*/
       ]
    }]
  }
}
/*...*/

Thing is I've tried the 2nd with Webpack 2.5.1 but it failed. Credits goes to Pranesh Ravi and Kreig.


问:
Update Linked Server Tables Using Synonyms
I have a server in a remote location and Its now connected to my local server through Linked Server. How can I update a table at remote location without using stored procedures.

Would SQL Synonyms be any kind of help?

Does user need to have Write permission on the Remote Server?

Thanks in advance

答:
You would use an update statement. Not sure why the requirement to not use a stored procedure comes from. I am concerned that you believe that somehow a stored procedure would make this easier in some way.

1) Synonyms are not going to help or hinder this process. They are simply a way to shorthand an object name.

2) Of course the user for the linked server connection must have write permission to write data.


问:
XML and tree, line get out the tree
I want to transform my XML file into a tree in Java with the framework Vaadin. But with one line it get out the tree and I don't understand why, to understand I made a little one XML:

```<code><overlay>
    <type>bgp</type>
    <bgp>
        <bgp-asn>12</bgp-asn>
    </bgp>
</overlay>
<overlay-routing>
    <type>test</type>
    <b>
        <bgp-as>11</bgp-as>
    </b>
</overlay-routing>
</code>```

And here the result :

So you can see I just change the name of my line in XML and it works, but with the "bgp-asn" it doesn't work and I really don't understand. It is a key work for XML ? Or something like that ?
I can put my code :

```<code>private Component test(){
        VerticalLayout ver = new VerticalLayout();
        ver.setSizeFull();
        TextArea text = new TextArea();
        Button send = new Button("send");
        tre = new Tree();
        tre.setSizeFull();

        send.addClickListener(new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                if(text.isEmpty()){
                    return;
                }
                Node node = getData(text.getValue());
                loadTree(tre, null, node);
            }
        });

private Document getData(String data){
        data = "<capsule>" + data;
        data = data + "</capsule>";
        try {
            if(data == null){
                return null;
            } else {
                try{
                    builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                } catch (ParserConfigurationException e){
                    throw new RuntimeException("cannot create a data source", e);
                }
                return builder.parse(new ByteArrayInputStream(data.trim().getBytes("UTF-8")));
            }
            //return data == null ? null : builder.parse(new ByteArrayInputStream(data.trim().getBytes("UTF-8")));
        } catch (SAXException | IOException e) {
            throw new RuntimeException("cannot load data from content", e);
        }
    }
</code>```

and loadtree:

```<code>private void loadTree(Tree tree, Object parentID, Node element){

        if(tree == null || element == null){
            return;
        }
        final String itemID = (element.getNodeType() == Node.TEXT_NODE ? element.getNodeValue() : element.getNodeName()).trim();

        if(itemID.length() == 0){
            return;
        }
        tree.addItem(itemID);

        if(parentID != null){
            tree.setParent(itemID, parentID);
        }
        NodeList children = element.getChildNodes();
        System.out.println(parentID);
        for(int i = 0, n = children.getLength(); i < n; i++){

            loadTree(tree, itemID, children.item(i));
        }
        if(children.getLength() > 0){
            tree.expandItem(itemID);
        } else{
            tree.setChildrenAllowed(itemID, false);
        }
    }
</code>```

If you know what is wrong, it will be awesome !
Thank you !

答:
Ok, I know now, there was a problem with the value like bgp and the tag < bgp> my code did not make the difference. I have to add 2 lines to make it right. Here the good part for the function loadtree()

```<code>private void loadTree(Tree tree, Object parentID, Node element){

        if(tree == null || element == null){
            return;
        }

        final String itemID = (element.getNodeType() == Node.TEXT_NODE ? element.getNodeValue() : element.getNodeName()).trim();

        if (itemID.equals("#document")) {
            loadTree(tree, null, element.getChildNodes().item(0));
            return;
        }

        if(itemID.length() == 0){
            return;
        }
//add this two lines
        Object item = tree.addItem();
        tree.setItemCaption(item, itemID);

        if(parentID != null){
            tree.setParent(item, parentID);
        }

        NodeList children = element.getChildNodes();
        for(int i = 0, n = children.getLength(); i < n; i++){

            loadTree(tree, item, children.item(i));
        }

        if(itemID.equals("root")){
            tree.expandItem(item);
        }

        if(children.getLength() == 0){
            tree.setChildrenAllowed(item, false);
        }
    }
</code>```

And now it is perfect !
Thank you.

Title: XML and tree, line get out the tree

Body:
I want to transform my XML file into a tree in Java with the framework Vaadin. But with one line it get out the tree and I don't understand why, to understand I made a little one XML:

<overlay>
    <type>bgp</type>
    <bgp>
        <bgp-asn>12</bgp-asn>
    </bgp>
</overlay>
<overlay-routing>
    <type>test</type>

        <bgp-as>11</bgp-as>

</overlay-routing>

And here the result :

So you can see I just change the name of my line in XML and it works, but with the "bgp-asn" it doesn't work and I really don't understand. It is a key work for XML ? Or something like that ?
I can put my code :

private Component test(){
        VerticalLayout ver = new VerticalLayout();
        ver.setSizeFull();
        TextArea text = new TextArea();
        Button send = new Button("send");
        tre = new Tree();
        tre.setSizeFull();

        send.addClickListener(new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                if(text.isEmpty()){
                    return;
                }
                Node node = getData(text.getValue());
                loadTree(tre, null, node);
            }
        });

private Document getData(String data){
        data = "<capsule>" + data;
        data = data + "</capsule>";
        try {
            if(data == null){
                return null;
            } else {
                try{
                    builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                } catch (ParserConfigurationException e){
                    throw new RuntimeException("cannot create a data source", e);
                }
                return builder.parse(new ByteArrayInputStream(data.trim().getBytes("UTF-8")));
            }
            //return data == null ? null : builder.parse(new ByteArrayInputStream(data.trim().getBytes("UTF-8")));
        } catch (SAXException | IOException e) {
            throw new RuntimeException("cannot load data from content", e);
        }
    }

and loadtree:

private void loadTree(Tree tree, Object parentID, Node element){

        if(tree == null || element == null){
            return;
        }
        final String itemID = (element.getNodeType() == Node.TEXT_NODE ? element.getNodeValue() : element.getNodeName()).trim();

        if(itemID.length() == 0){
            return;
        }
        tree.addItem(itemID);

        if(parentID != null){
            tree.setParent(itemID, parentID);
        }
        NodeList children = element.getChildNodes();
        System.out.println(parentID);
        for(int i = 0, n = children.getLength(); i < n; i++){

            loadTree(tree, itemID, children.item(i));
        }
        if(children.getLength() > 0){
            tree.expandItem(itemID);
        } else{
            tree.setChildrenAllowed(itemID, false);
        }
    }

If you know what is wrong, it will be awesome !
Thank you !

Body:
Ok, I know now, there was a problem with the value like bgp and the tag < bgp> my code did not make the difference. I have to add 2 lines to make it right. Here the good part for the function loadtree()

private void loadTree(Tree tree, Object parentID, Node element){

        if(tree == null || element == null){
            return;
        }

        final String itemID = (element.getNodeType() == Node.TEXT_NODE ? element.getNodeValue() : element.getNodeName()).trim();

        if (itemID.equals("#document")) {
            loadTree(tree, null, element.getChildNodes().item(0));
            return;
        }

        if(itemID.length() == 0){
            return;
        }
//add this two lines
        Object item = tree.addItem();
        tree.setItemCaption(item, itemID);

        if(parentID != null){
            tree.setParent(item, parentID);
        }

        NodeList children = element.getChildNodes();
        for(int i = 0, n = children.getLength(); i < n; i++){

            loadTree(tree, item, children.item(i));
        }

        if(itemID.equals("root")){
            tree.expandItem(item);
        }

        if(children.getLength() == 0){
            tree.setChildrenAllowed(item, false);
        }
    }

And now it is perfect !
Thank you.


问:
Inheritance vs. Delegation
The code below shows how method m() can be reused by inheritance. How works for delegation? Thanks!</p>

```<code>  class A{
  int m();
  }

 class B extends A{}

 B b =new B()
 b.m();
</code>```

答:
```<code>class B {
    int m() {
        return new A().m();
    }
}
</code>```

or

```<code>class B {
    private A a = new A();
    int m() {
        return a.m();
    }
}
</code>```

or

```<code>class B {
    private A a;

    public B(A a) {
        this.a = a;
    }

    int m() {
        return a.m();
    }
}
</code>```

Title: Inheritance vs. Delegation

Body:
The code below shows how method m() can be reused by inheritance. How works for delegation? Thanks!

  class A{
  int m();
  }

 class B extends A{}

 B b =new B()
 b.m();

Body:
class B {
    int m() {
        return new A().m();
    }
}

or

class B {
    private A a = new A();
    int m() {
        return a.m();
    }
}

or

class B {
    private A a;

    public B(A a) {
        this.a = a;
    }

    int m() {
        return a.m();
    }
}


问:
yii2-app-advanced on single domain not work for me
I configured my yii2 advanced according to yii official wiki for using backend and frontend in a single domain on localhost.
I use the hard way and i modify file

```<code>frontend/config/main.php
</code>```

and

```<code>backend/config/main.php
</code>```

and added

```<code>.htaccess with mod_rewrite
</code>```

according to wiki.
when i go to http://localhost/ all things right.but when i go to http://localhost/site/about and other link, browser shown

```<code>Object not found!
</code>```

and when i want to go to http://localhost/backend/ browser redirect me to http://localhost/backend/site/login and show

```<code>Object not found!
</code>```

again.
i used this wiki for past yii2 projects without any problem. but now i can't use.
what is my wrong?
I am iranian and my english not very good. Forgive me for bad language.

答:
I had faced the same problem when I follow the yii2 hard way template then I made the following changes in config, vhost and .htaccess file.

/frontend/config/main.php

```<code>return  [
        'homeUrl' => '/',
        'components' => [
            'request' => [
                'baseUrl' => '',
            ],
            'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
            ],
        ],
    ];
</code>```

/backend/config/main.php

```<code>return  [
        'homeUrl' => '/admin',
        'components' => [
            'request' => [
                'baseUrl' => '/admin',
            ],
            'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
            ],
        ],
    ];
</code>```

.htaccess
You need to add below mentioned code in .htaccess file which is there in the root of your application. If you do not have one then you need to create .htaccess file in the root of you advance application.

```<code>Options FollowSymLinks
AddDefaultCharset utf-8

<ifmodule mod_rewrite.c>
RewriteEngine On

# the main rewrite rule for the frontend application
RewriteCond %{REQUEST_URI} !^/(backend/web|admin)
RewriteRule !^frontend/web /frontend/web%{REQUEST_URI} [L]

# redirect to the page without a trailing slash
#RewriteCond %{REQUEST_URI} ^/admin/$
#RewriteRule ^(admin)/ /$1 [L,R=301]
# the main rewrite rule for the backend application
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^admin(.*) /backend/web/$1 [L]

# if a directory or a file of the frontend application exists,
# use the request directly
RewriteCond %{REQUEST_URI} ^/frontend/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward the request to index.php
RewriteRule . /frontend/web/index.php [L]

# if a directory or a file of the backend application exists,
# use the request directly
RewriteCond %{REQUEST_URI} ^/backend/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward the request to index.php
RewriteRule . /backend/web/index.php [L]

RewriteCond %{REQUEST_URI} \.(htaccess|htpasswd|svn|git)
RewriteRule \.(htaccess|htpasswd|svn|git) - [F]
</ifmodule>
</code>```

vhost file

```<code><VirtualHost *:80>
DocumentRoot "path of your project" //no need to mention backend/frontend
ServerName "example.com"
<Directory "path of your project">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>
</code>```

Body:
I configured my yii2 advanced according to yii official wiki for using backend and frontend in a single domain on localhost.
I use the hard way and i modify file

frontend/config/main.php

and

backend/config/main.php

and added

.htaccess with mod_rewrite

according to wiki.
when i go to http://localhost/ all things right.but when i go to http://localhost/site/about and other link, browser shown

Object not found!

and when i want to go to http://localhost/backend/ browser redirect me to http://localhost/backend/site/login and show

Object not found!

again.
i used this wiki for past yii2 projects without any problem. but now i can't use.
what is my wrong?
I am iranian and my english not very good. Forgive me for bad language.

Body:
I had faced the same problem when I follow the yii2 hard way template then I made the following changes in config, vhost and .htaccess file.

/frontend/config/main.php

return  [
        'homeUrl' => '/',
        'components' => [
            'request' => [
                'baseUrl' => '',
            ],
            'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
            ],
        ],
    ];

/backend/config/main.php

return  [
        'homeUrl' => '/admin',
        'components' => [
            'request' => [
                'baseUrl' => '/admin',
            ],
            'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
            ],
        ],
    ];

.htaccess
You need to add below mentioned code in .htaccess file which is there in the root of your application. If you do not have one then you need to create .htaccess file in the root of you advance application.

Options FollowSymLinks
AddDefaultCharset utf-8

<ifmodule mod_rewrite.c>
RewriteEngine On

# the main rewrite rule for the frontend application
RewriteCond %{REQUEST_URI} !^/(backend/web|admin)
RewriteRule !^frontend/web /frontend/web%{REQUEST_URI} [L]

# redirect to the page without a trailing slash
#RewriteCond %{REQUEST_URI} ^/admin/$
#RewriteRule ^(admin)/ /$1 [L,R=301]
# the main rewrite rule for the backend application
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^admin(.*) /backend/web/$1 [L]

# if a directory or a file of the frontend application exists,
# use the request directly
RewriteCond %{REQUEST_URI} ^/frontend/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward the request to index.php
RewriteRule . /frontend/web/index.php [L]

# if a directory or a file of the backend application exists,
# use the request directly
RewriteCond %{REQUEST_URI} ^/backend/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward the request to index.php
RewriteRule . /backend/web/index.php [L]

RewriteCond %{REQUEST_URI} \.(htaccess|htpasswd|svn|git)
RewriteRule \.(htaccess|htpasswd|svn|git) - [F]
</ifmodule>

vhost file

<VirtualHost *:80>
DocumentRoot "path of your project" //no need to mention backend/frontend
ServerName "example.com"
<Directory "path of your project">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>


问:
Changing the format of mysql table using mysql query
I have the following table in mysql database

i want to get the result in the following format

答:
You can use this query:</p>

```<code>select
    customerName,
    coalesce(sum(case when month(`date`) = 1 then paidamount end), '-') as `January` ,
    coalesce(sum(case when month(`date`) = 2 then paidamount end), '-') as `February`,
    coalesce(sum(case when month(`date`) = 3 then paidamount end), '-') as `March`,
    coalesce(sum(case when month(`date`) = 4 then paidamount end), '-') as `April`,
    coalesce(sum(case when month(`date`) = 5 then paidamount end), '-') as `May`,
    coalesce(sum(case when month(`date`) = 6 then paidamount end), '-') as `June`,
    coalesce(sum(case when month(`date`) = 7 then paidamount end), '-') as `July`,
    coalesce(sum(case when month(`date`) = 8 then paidamount end), '-') as `August`,
    coalesce(sum(case when month(`date`) = 9 then paidamount end), '-') as `September`,
    coalesce(sum(case when month(`date`) = 10 then paidamount end), '-') as `October`,
    coalesce(sum(case when month(`date`) = 11 then paidamount end), '-') as `November`,
    coalesce(sum(case when month(`date`) = 12 then paidamount end), '-') as `December`
from test
group by customerName
</code>```

Body:
You can use this query:

select
    customerName,
    coalesce(sum(case when month(`date`) = 1 then paidamount end), '-') as `January` ,
    coalesce(sum(case when month(`date`) = 2 then paidamount end), '-') as `February`,
    coalesce(sum(case when month(`date`) = 3 then paidamount end), '-') as `March`,
    coalesce(sum(case when month(`date`) = 4 then paidamount end), '-') as `April`,
    coalesce(sum(case when month(`date`) = 5 then paidamount end), '-') as `May`,
    coalesce(sum(case when month(`date`) = 6 then paidamount end), '-') as `June`,
    coalesce(sum(case when month(`date`) = 7 then paidamount end), '-') as `July`,
    coalesce(sum(case when month(`date`) = 8 then paidamount end), '-') as `August`,
    coalesce(sum(case when month(`date`) = 9 then paidamount end), '-') as `September`,
    coalesce(sum(case when month(`date`) = 10 then paidamount end), '-') as `October`,
    coalesce(sum(case when month(`date`) = 11 then paidamount end), '-') as `November`,
    coalesce(sum(case when month(`date`) = 12 then paidamount end), '-') as `December`
from test
group by customerName


问:
Power BI connect to CRM 2016 Web API
I'm trying to use Power BI Desktop to connect to a CRM Online (2016 Spring Wave 1) instance using CRM's new Web API methods.

When I put my api into a browser like Chrome I get results back. For example if I use https://xxx.crm.dynamics.com/api/data/v8.0/my_records?$select=my_recordid I can see all the results being listed (in batches of 5000)

However, when I try the same thing in PowerBI I get an error telling me that a field already exists (see screenshot)

I've seen some approaches where the URL is wrapped

```<code>= Json.Document(Web.Contents("<same url as above>")
</code>```

but this doesn't seem like a good approach, and I don't know how to use this approach with paging.

So has anyone managed to get Power BI working with the new Web API calls?

答:
I'm rather late to this question, but I've had good success with the "Json.Document(Web.Contents())" method. The trick to the paging issue was wrapping the call in a recursive function. For convenience, I've wrapped that recursive function such that I can pass in the name of a Saved View/Advanced find and get the results of that query.

As a Gist: https://gist.github.com/d4hines/b5d9900fc1ea9d26311d2145505837cb

```<code>(OrgUrl as text, QueryName as text, UserView as logical) =>
let

GetQueryByName =
     //https://mycrm.mydomain.com/MYORG
    (OrgUrl as text, QueryName as text, UserView as logical) =>
        let
            QueryType = if UserView then "user" else "saved"
            ,return = OData.Feed(
                    OrgUrl & "/api/data/v8.0/" & QueryType & "queries?$select="& QueryType & "queryid&$filter=name eq '" & QueryName & "'"
                )[userqueryid]{0}

        in
            return,
QueryAll =
    (nextURL, prev) =>
        let
            prevList = if prev <> null then prev else {},
            responseData = Json.Document(Web.Contents(nextURL, [Headers=[Prefer="odata.include-annotations=""OData.Community.Display.V1.FormattedValue"""]])),
            return = if responseData[#"@odata.nextLink"]? <> null then @QueryAll(responseData[#"@odata.nextLink"], prevList & responseData[value]) else responseData[value] & prevList
        in return,
NamedQuery = OrgUrl & "/api/data/v8.0/contacts?userQuery=" & GetQueryByName(OrgUrl, QueryName, UserView),
return = Table.FromList(QueryAll(NamedQuery, null), Splitter.SplitByNothing(), null, null, ExtraValues.Error)
in return
</code>```

There are a bit more instructions on the gist if that helps. Hope it helps someone!

Title: Power BI connect to CRM 2016 Web API

Body:
I'm trying to use Power BI Desktop to connect to a CRM Online (2016 Spring Wave 1) instance using CRM's new Web API methods.

When I put my api into a browser like Chrome I get results back. For example if I use https://xxx.crm.dynamics.com/api/data/v8.0/my_records?$select=my_recordid I can see all the results being listed (in batches of 5000)

However, when I try the same thing in PowerBI I get an error telling me that a field already exists (see screenshot)

I've seen some approaches where the URL is wrapped

= Json.Document(Web.Contents("<same url as above>")

but this doesn't seem like a good approach, and I don't know how to use this approach with paging.

So has anyone managed to get Power BI working with the new Web API calls?

Body:
I'm rather late to this question, but I've had good success with the "Json.Document(Web.Contents())" method. The trick to the paging issue was wrapping the call in a recursive function. For convenience, I've wrapped that recursive function such that I can pass in the name of a Saved View/Advanced find and get the results of that query.

As a Gist: https://gist.github.com/d4hines/b5d9900fc1ea9d26311d2145505837cb

(OrgUrl as text, QueryName as text, UserView as logical) =>
let

GetQueryByName =
     //https://mycrm.mydomain.com/MYORG
    (OrgUrl as text, QueryName as text, UserView as logical) =>
        let
            QueryType = if UserView then "user" else "saved"
            ,return = OData.Feed(
                    OrgUrl & "/api/data/v8.0/" & QueryType & "queries?$select="& QueryType & "queryid&$filter=name eq '" & QueryName & "'"
                )[userqueryid]{0}

        in
            return,
QueryAll =
    (nextURL, prev) =>
        let
            prevList = if prev <> null then prev else {},
            responseData = Json.Document(Web.Contents(nextURL, [Headers=[Prefer="odata.include-annotations=""OData.Community.Display.V1.FormattedValue"""]])),
            return = if responseData[#"@odata.nextLink"]? <> null then @QueryAll(responseData[#"@odata.nextLink"], prevList & responseData[value]) else responseData[value] & prevList
        in return,
NamedQuery = OrgUrl & "/api/data/v8.0/contacts?userQuery=" & GetQueryByName(OrgUrl, QueryName, UserView),
return = Table.FromList(QueryAll(NamedQuery, null), Splitter.SplitByNothing(), null, null, ExtraValues.Error)
in return

There are a bit more instructions on the gist if that helps. Hope it helps someone!


问:
QueryDSL Paging Sorting duplicates
I have got an Entity A say Car with a OneToMany relationship to an Entity B say CarProperty.

My Car Repository extends QueryDslPredicateExecutor to support paging and sorting:

```<code>Page<T> findAll(Predicate predicate, Pageable pageable);
</code>```

I'm trying to execute a query where I sort the results, by a column of CarProperty, defining the sort on pageable variable.
However since it is a One To Many relationship between Car and CarProperty, I have returned duplicates of Car.
Is it possible to obtain distinct results on Car using this structure?

If it is not possible to use distinct on the Predicate, how could I represent the following query in the predicate (using exists to eliminate duplicates):

```<code>SELECT Car.*
FROM Car C LEFT JOIN CarProperty CP ON (C.ID = CP.CAR_ID)
WHERE EXISTS (SELECT 1
              FROM CarProperty CP2
              WHERE CP2.CAR_ID = C.ID AND CP2.ID = CP.ID)
ORDER BY CP.PROPERTY_NAME ASC;
</code>```

Thanks in advance

答:
You can use named entity graph to avoid duplicate records, in my case it  worked.

```<code>    @NamedEntityGraph(name = "Car.carProperty" ,attributeNodes = @NamedAttributeNode("carProperties"))
    @Entity
    public class Car {
        @OneToMany
        @JoinColumn(name = "carProperties")
        private List<CarProperty> carProperties;
    }
</code>```

and then override findall method

```<code>@EntityGraph(value = "Car.carProperty" , type = EntityGraphType.LOAD)
Page<Car> findAll(Predicate predicate, Pageable pageable);
</code>```

Title: QueryDSL Paging Sorting duplicates

Body:
I have got an Entity A say Car with a OneToMany relationship to an Entity B say CarProperty.

My Car Repository extends QueryDslPredicateExecutor to support paging and sorting:

Page<T> findAll(Predicate predicate, Pageable pageable);

I'm trying to execute a query where I sort the results, by a column of CarProperty, defining the sort on pageable variable.
However since it is a One To Many relationship between Car and CarProperty, I have returned duplicates of Car.
Is it possible to obtain distinct results on Car using this structure?

If it is not possible to use distinct on the Predicate, how could I represent the following query in the predicate (using exists to eliminate duplicates):

SELECT Car.*
FROM Car C LEFT JOIN CarProperty CP ON (C.ID = CP.CAR_ID)
WHERE EXISTS (SELECT 1
              FROM CarProperty CP2
              WHERE CP2.CAR_ID = C.ID AND CP2.ID = CP.ID)
ORDER BY CP.PROPERTY_NAME ASC;

Thanks in advance

Body:
You can use named entity graph to avoid duplicate records, in my case it  worked.

    @NamedEntityGraph(name = "Car.carProperty" ,attributeNodes = @NamedAttributeNode("carProperties"))
    @Entity
    public class Car {
        @OneToMany
        @JoinColumn(name = "carProperties")
        private List<CarProperty> carProperties;
    }

and then override findall method

@EntityGraph(value = "Car.carProperty" , type = EntityGraphType.LOAD)
Page<Car> findAll(Predicate predicate, Pageable pageable);


问:
Exit from Inno Setup installation from [Code]
Is it possible to exit the installation from a function in the [Code] section of an installer created with Inno Setup?

I'm not interested in setting the exit code, what I want to do is perform a custom check for a requirement, and exit the installation if that requirement was not previously installed.

答: Take a look at InitializeSetup and Abort in the InnoSetup help.  As Cody said, it is possible.  If you're having problems, post what you've done and the problem you're having.  </p>


答:
I think this is a general question about how to pass arguments to the function used with applymap. Applymap passes each element in each series in a dataframe to the function passed. This is automatically passes as the first argument. You can write a function that incorporates this first element (x in the example below) and other dataframes or arguments.

To call it, you can use a lambda function. An example is below.

```<code>import numpy as np
import pandas as pd
df  = pd.DataFrame(np.random.randn(3, 3))
peak = pd.DataFrame(np.random.randn(3, 3))
off_peak = pd.DataFrame(np.random.randn(3, 3))

def applymapFunction(x, df1, df2):
    if x > 0.5:
        return x * df1.mean()[0]
    else:
        return x * df2.mean()[0]

df.applymap(lambda x: applymapFunction(x, peak, off_peak))
</code>```

Title: How to pass dataframes to a function using applymap() in pandas?

Body:
I am trying to use applymap() functionality in pandas to apply a function to a whole dataframe. I have a dataframe df (a sample of it is following):

Time    2010-08-31  2010-09-30  2010-10-31  2010-11-30  2010-12-31 2011-01-31  2011-02-28 2011-03-31  2011-04-30
00:00   0.429188    0.302406    0.587415    0.227820    0.115938    0.170616    0.056256    0.078167    0.476515
00:30   0.340452    0.385037    0.218495    0.238118    0.134938    0.123279    0.054984    0.108111    0.173700
01:00   0.455451    0.433700    0.229352    0.253046    0.391425    0.313715    0.401116    0.123304    0.453640
01:30   0.601494    0.576142    0.425599    0.590769    0.486930    0.419002    0.560737    0.554705    0.544313
02:00   0.504342    0.584523    0.614539    0.375294    0.377951    0.342675    0.357372    0.367332    0.391336
02:30   0.527724    0.443303    0.457283    0.369515    0.392317    0.379410    0.391916    0.444807    0.491411
03:00   0.429236    0.531203    0.464098    0.370421    0.426875    0.360209    0.276282    0.179577    0.304990
03:30   0.442019    0.510604    0.314080    0.372268    0.443884    0.461649    0.390262    0.284042    0.417354

I also have two other frames, namely, df_peak and df_off_peak which are following:

df_peak = pd.DataFrame(np.random.randn(20,2), columns=list(['Peak Consumption', 'Loss']))
df_off_peak = pd.DataFrame(np.random.randn(20,2), columns=list(['Off Peak Consumption', 'Loss']))

I have written a following function in a separate file interpolate.py:

Function to calculate losses corresponding to consumption

def cost_consump(consump,df_peak,df_off_peak):
    if(consump >= 0.459):
        for i in range(0, len(df_peak)):
            if(df_peak["Peak_Consumption"][i] > consump):
                cost = df_peak["Loss"][i-1]
                return cost
                break;

    elif(consump <= 0.309):
        for i in range(0, len(df_off_peak)):
            if(df_off_peak["Off_Peak_Consumption"][i] > consump):
                cost = df_off_peak["Loss"][i-1]
                return cost
                break;

    return 0

Then I call the function cost_consump as following:

from interpolate import cost_consump
df1 = pd.DataFrame.copy(df,deep=True)

for i in range(0,48):
    for j in range(0,12):
        mean_consump = df.transpose().iloc[i,j]
        df1.transpose().iloc[i,j] =  cost_consump(mean_consump,df_loss_peak,df_loss_off_peak)

This works perfectly as I want. However I am curious if the job can be done by using applymap(). I tried to write following where I want to apply the function to dataframe df and save the resultant operation in df1.

Monthly_mean_cost = Monthly_mean_consump.transpose().applymap(cost_consump(**df_loss_peak,**df_loss_off_peak))

However, this requires me to pass two additional dataframes to the function which I am not sure how to do that.

I would appreciate any help.

Body:
I think this is a general question about how to pass arguments to the function used with applymap. Applymap passes each element in each series in a dataframe to the function passed. This is automatically passes as the first argument. You can write a function that incorporates this first element (x in the example below) and other dataframes or arguments.

To call it, you can use a lambda function. An example is below.

import numpy as np
import pandas as pd
df  = pd.DataFrame(np.random.randn(3, 3))
peak = pd.DataFrame(np.random.randn(3, 3))
off_peak = pd.DataFrame(np.random.randn(3, 3))

def applymapFunction(x, df1, df2):
    if x > 0.5:
        return x * df1.mean()[0]
    else:
        return x * df2.mean()[0]

df.applymap(lambda x: applymapFunction(x, peak, off_peak))


问:
How to Create Custom Action (Very Basic) in Alfresco
I want to create a Basic Action on Folder which would just Print some message in Logs in Alfresco</p>

答:
refer this documentation link for creating custom action in document library.

http://docs.alfresco.com/5.0/tasks/dev-extensions-share-tutorials-add-action-doclib.html


问:
SQLiteDataAdapter converts blank value to 0 - how to prevent that and get blank value?
I am using SQLiteDataAdapter, and in my table, there is one row which have blank value('') in it. While reading it from C#, i am getting 0 for the blank value. How to get blank value instead of 0 for blank values?

Column type is Integer, but it may vary based on table to table. And code is :

```<code>SQLiteDataReader r= command.ExecuteReader();
while (reader.Read())
{
    DataRow dataRow = new DataRow();
     for (int i = 0; i < l.Count; i++)
     {
          dataRow[listCols[i]] = r[i];
     }
     dt.Rows.Add(dataRow);
}
where 'l' is list of DataColumn
</code>```

答:
There's a workaround to manage null instances on integer columns, check this:
How to handle nullable integer columns in SQLite database</p>

Body:
I am using SQLiteDataAdapter, and in my table, there is one row which have blank value('') in it. While reading it from C#, i am getting 0 for the blank value. How to get blank value instead of 0 for blank values?

Column type is Integer, but it may vary based on table to table. And code is :

SQLiteDataReader r= command.ExecuteReader();
while (reader.Read())
{
    DataRow dataRow = new DataRow();
     for (int i = 0; i < l.Count; i++)
     {
          dataRow[listCols[i]] = r[i];
     }
     dt.Rows.Add(dataRow);
}
where 'l' is list of DataColumn


问:
Design-Time Errors in the Windows Forms Designer
I have this classes on the same namespace:

```<code>public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}
</code>```

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?

答:
As mentioned by @SLaks, you need the InitializeComponent in the constructor of your class.  I would actually have it in the no-parameter instance.  Then, in the constructor of you boolean, i would change to

```<code>public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm()
    {
        InitializeComponent();
    }

    public BaseForm(bool isNew) : this()
    {

        this.isNew = isNew;
    }
}
</code>```

So if you had other stuff you wanted performed within your BaseForm definition regardless of a parameerized startup, that too would be called.  This way, the InitializeComponent is triggeed in EITHER case.

Body:
I have this classes on the same namespace:

public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?

Body:
As mentioned by @SLaks, you need the InitializeComponent in the constructor of your class.  I would actually have it in the no-parameter instance.  Then, in the constructor of you boolean, i would change to

public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm()
    {
        InitializeComponent();
    }

    public BaseForm(bool isNew) : this()
    {

        this.isNew = isNew;
    }
}

So if you had other stuff you wanted performed within your BaseForm definition regardless of a parameerized startup, that too would be called.  This way, the InitializeComponent is triggeed in EITHER case.