问:
Firebase errors on page load after Angular upgrade
After upgrading to Angular 13 I'm having issues with auth mechanism. I'm using Nebular Auth over Firebase authentication with Azure. Currently on page load I'm getting this error:

```<code>zone.js:1063 Unhandled Promise rejection: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function
    at new UserImpl (index-342f2197.js:1599:62)
    at Function._fromJSON (index-342f2197.js:1736:22)
    at index-342f2197.js:1865:32
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (asyncToGenerator.js:3:1)
    at _next (asyncToGenerator.js:25:1)
    at ZoneDelegate.invoke (zone.js:372:1)
    at Zone.run (zone.js:134:1)
    at zone.js:1276:1
    at ZoneDelegate.invokeTask (zone.js:406:1) TypeError: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function
    at new UserImpl (http://localhost:4200/vendor.js:5601:60)
    at Function._fromJSON (http://localhost:4200/vendor.js:5831:18)
    at http://localhost:4200/vendor.js:6008:30
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (http://localhost:4200/vendor.js:184170:24)
    at _next (http://localhost:4200/vendor.js:184192:9)
    at ZoneDelegate.invoke (http://localhost:4200/polyfills.js:3497:26)
    at Zone.run (http://localhost:4200/polyfills.js:3259:43)
    at http://localhost:4200/polyfills.js:4401:36
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3531:31)
</code>```

It originates in firebase-auth.js. mentioned function is also declared there:

```<code>function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}
</code>```

package.json excerpt:

```<code>"dependencies": {
    "@angular/animations": "^13.2.1",
    "@angular/cdk": "^13.2.1",
    "@angular/common": "^13.2.1",
    "@angular/compiler": "^13.2.1",
    "@angular/core": "^13.2.1",
    "@angular/fire": "^7.2.0",
    "@angular/forms": "^13.2.1",
    "@angular/platform-browser": "^13.2.1",
    "@angular/platform-browser-dynamic": "^13.2.1",
    "@angular/router": "^13.2.1",
    "@nebular/auth": "^9.0.1",
    "@nebular/eva-icons": "9.0.1",
    "@nebular/firebase-auth": "^9.0.1",
    "@nebular/theme": "^9.0.1",
    "@ngrx/effects": "^13.0.2",
    "@ngrx/entity": "^13.0.2",
    "@ngrx/schematics": "^13.0.2",
    "@ngrx/store": "^13.0.2",
    "@ngrx/store-devtools": "^13.0.2",
    "eva-icons": "^1.1.2",
    "firebase": "^9.4.0",
(...)
</code>```

Nebular uses a backward-compatible version of Angular Fire (with compat packages).

答:
It turned out that the problem was with the unnecessary and incorrect config of typescript. In tsconfig.json paths I had this line
tslib" : ["node_modules/tslib/tslib.d.ts"] and that prevented proper helper resolution from tslib. Removal of this setting, which I found is no longer needed resolved the problem.

Body:
After upgrading to Angular 13 I'm having issues with auth mechanism. I'm using Nebular Auth over Firebase authentication with Azure. Currently on page load I'm getting this error:

zone.js:1063 Unhandled Promise rejection: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function
    at new UserImpl (index-342f2197.js:1599:62)
    at Function._fromJSON (index-342f2197.js:1736:22)
    at index-342f2197.js:1865:32
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (asyncToGenerator.js:3:1)
    at _next (asyncToGenerator.js:25:1)
    at ZoneDelegate.invoke (zone.js:372:1)
    at Zone.run (zone.js:134:1)
    at zone.js:1276:1
    at ZoneDelegate.invokeTask (zone.js:406:1) TypeError: (0 , tslib__WEBPACK_IMPORTED_MODULE_5__.__rest) is not a function
    at new UserImpl (http://localhost:4200/vendor.js:5601:60)
    at Function._fromJSON (http://localhost:4200/vendor.js:5831:18)
    at http://localhost:4200/vendor.js:6008:30
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (http://localhost:4200/vendor.js:184170:24)
    at _next (http://localhost:4200/vendor.js:184192:9)
    at ZoneDelegate.invoke (http://localhost:4200/polyfills.js:3497:26)
    at Zone.run (http://localhost:4200/polyfills.js:3259:43)
    at http://localhost:4200/polyfills.js:4401:36
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3531:31)

It originates in firebase-auth.js. mentioned function is also declared there:

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

package.json excerpt:

"dependencies": {
    "@angular/animations": "^13.2.1",
    "@angular/cdk": "^13.2.1",
    "@angular/common": "^13.2.1",
    "@angular/compiler": "^13.2.1",
    "@angular/core": "^13.2.1",
    "@angular/fire": "^7.2.0",
    "@angular/forms": "^13.2.1",
    "@angular/platform-browser": "^13.2.1",
    "@angular/platform-browser-dynamic": "^13.2.1",
    "@angular/router": "^13.2.1",
    "@nebular/auth": "^9.0.1",
    "@nebular/eva-icons": "9.0.1",
    "@nebular/firebase-auth": "^9.0.1",
    "@nebular/theme": "^9.0.1",
    "@ngrx/effects": "^13.0.2",
    "@ngrx/entity": "^13.0.2",
    "@ngrx/schematics": "^13.0.2",
    "@ngrx/store": "^13.0.2",
    "@ngrx/store-devtools": "^13.0.2",
    "eva-icons": "^1.1.2",
    "firebase": "^9.4.0",
(...)

Nebular uses a backward-compatible version of Angular Fire (with compat packages).


来源: stackexchange

问:
Unable to ingest data into Hive DB using Azure Data Factory with ODBC on Windows VM
I want to ingest CSV files to a Hive DB using a Data Factory pipeline. There is Hive connector available but it can only be used as a source and not as a sink. So as far as I know the only way to ingest data is using the ODBC connector in Data Factory.

My setup looks like this:
I'm using Azure Data Factory (V2) and an Azure Windows VM for the self-hosted Integration Runtime. I have set up the ODBC connector with the needed connection details for the Hive DB (the connection is working successfully). Also the ODBC connector will find any existing tables.

But when I trigger the pipeline I get following error:

```<code>Failure happened on 'Sink' side. ErrorCode=SystemErrorOdbcWriteError,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=ERROR [07009] [Microsoft][ODBC] (10670) Invalid descriptor index, descriptor record does not exist, or descriptor record was not properly initialized.,Source=Microsoft.DataTransfer.ClientLibrary.Odbc.OdbcConnector,''Type=Microsoft.DataTransfer.ClientLibrary.Odbc.Exceptions.OdbcException,Message=ERROR [07009] [Microsoft][ODBC] (10670) Invalid descriptor index, descriptor record does not exist, or descriptor record was not properly initialized.,Source=Microsoft Hive ODBC Driver,'
</code>```

Does anyone have an idea what is going wrong here?

Cheers,
Niklas

答: Problem solved: Ingest data into Hive tables via ODBC is not supported and also shouldn't be the way to go. Use Hive activity in ADF instead which will run a HiveQL script which will ingest the data.</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to ingest CSV files to a Hive DB using a Data Factory pipeline. There is Hive connector available but it can only be used as a source and not as a sink. So as far as I know the only way to ingest data is using the ODBC connector in Data Factory.

My setup looks like this:
I'm using Azure Data Factory (V2) and an Azure Windows VM for the self-hosted Integration Runtime. I have set up the ODBC connector with the needed connection details for the Hive DB (the connection is working successfully). Also the ODBC connector will find any existing tables.

But when I trigger the pipeline I get following error:

Failure happened on 'Sink' side. ErrorCode=SystemErrorOdbcWriteError,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=ERROR [07009] [Microsoft][ODBC] (10670) Invalid descriptor index, descriptor record does not exist, or descriptor record was not properly initialized.,Source=Microsoft.DataTransfer.ClientLibrary.Odbc.OdbcConnector,''Type=Microsoft.DataTransfer.ClientLibrary.Odbc.Exceptions.OdbcException,Message=ERROR [07009] [Microsoft][ODBC] (10670) Invalid descriptor index, descriptor record does not exist, or descriptor record was not properly initialized.,Source=Microsoft Hive ODBC Driver,'

Does anyone have an idea what is going wrong here?

Cheers,
Niklas


问:
Javascript for loop innerhtml doesn't work

    class GenerateArray {

        constructor() {
            this.arrayCode = document.getElementById('code');
            this.BaseCode = document.getElementById('preCode');
            this.startCode = document.getElementById('startC');
            this.endCode = document.getElementById('endC');
            this.question = "";
            this.prefix = "";
            this.description = "";
            this.answer = "";
            this.id = "";
            this.Name = "";
            this.answerDIV = "";
            this.count = 0;

        }

        generateQuestionPart() {

            this.question = document.createElement('input');
            this.question.setAttribute('type', 'text');
            this.question.id = 'question' + this.count;
            this.question.className = 'question';
            this.question.placeholder = 'What is the question?'

            this.prefix = document.createElement('input');
            this.prefix.setAttribute('type', 'text');
            this.prefix.className = 'prefix';
            this.prefix.id = 'prefix' + this.count;
            this.prefix.placeholder = 'The prefix of the question that belongs to the link'

            this.description = document.createElement('input');
            this.description.setAttribute('type', 'text');
            this.description.id = 'description' + this.count;
            this.description.className = 'description';
            this.description.placeholder = 'Add the description that is going to be in the info pop up';

            this.answerDIV = document.createElement('div');
            this.answerDIV.className = 'answerDIV' + this.count;
            this.answerDIV.id = 'AnswerDivId';

            this.answer = document.createElement('button');
            this.answer.setAttribute('type', 'button');
            this.answer.id = 'answer';
            this.answer.className = 'answerN' + this.count;
            this.answer.innerHTML = 'Add Answer';
            this.answer.onclick = function (e) {
                for (let i = 0; i < NewArray.count; i++) {
                    if (e.target.className.endsWith(i)) {
                        NewArray.id = document.createElement('input');
                        NewArray.id.setAttribute('type', 'text');
                        NewArray.id.id = 'id' + i;
                        NewArray.id.classList.add('id');
                        NewArray.id.placeholder = 'Add the ID of the answer';

                        NewArray.Name = document.createElement('input');
                        NewArray.Name.setAttribute('type', 'text');
                        NewArray.Name.id = 'Name' + i;
                        NewArray.Name.className = 'name';
                        NewArray.Name.placeholder = 'Add the text that is on the answer button';
                        // console.log(e.target.className);

                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
                    }
                }
            }

            document.getElementsByClassName('create')[0].appendChild(this.question);
            document.getElementsByClassName('create')[0].appendChild(this.prefix);
            document.getElementsByClassName('create')[0].appendChild(this.description);
            document.getElementsByClassName('create')[0].appendChild(this.answerDIV);
            document.getElementsByClassName('create')[0].appendChild(this.answer);
            this.count++;
            // console.log(NewArray.answer.length)
        }

        writeArray() {
            let basis = document.createElement('p');
            basis.innerHTML =
                "    class QuizPart {\n" +
                "        constructor(questionText, chosenAnswer, prefix, questionDescription) {\n" +
                "            this.questionText = questionText;\n" +
                "            this.chosenAnswer = chosenAnswer;\n" +
                "            this.prefix = prefix;\n" +
                "            this.questionDescription = questionDescription;\n" +
                "        }\n" +
                "    }\n" +
                "\n" +
                "    class ChosenAnswer {\n" +
                "        constructor(id, name) {\n" +
                "            this.id = id;\n" +
                "            this.name = name;\n" +
                "        }\n" +
                "    }";

            this.BaseCode.appendChild(basis);

            let startC = document.createElement('p');
            startC.innerHTML = "let Quiz = [";

            for (let i = 0; i < this.count; i++) {
                let code = document.createElement('p');

                let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";

                let answers = document.querySelectorAll("input#Name" + i)
                console.log(answers.length);

                for (let y = 0; y < answers.length; y++) {
                    output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
                }

                output += "], '" + document.getElementById('prefix' + i).value + "',";
                output += "'" + document.getElementById('description' + i).value + "',";

                code.innerHTML = output;

                this.arrayCode.appendChild(code);
            }
            let endC = document.createElement('p');
            endC.innerHTML = "]"

            this.startCode.appendChild(startC);
            this.endCode.appendChild(endC);
            // console.log(this.count.length);
        }
    }

    NewArray = new GenerateArray();
    NewArray.generateQuestionPart();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0;
    padding: 0;
}
.container{
    height: 1000px;
    width: 800px;
    position: relative;
    margin-top: 5px;
    left: 50%;
    -ms-transform: translate(-50%, 5%);
    transform: translate(-50%, 5%);
}

.QPB{
    width: 50px;
    height: 50px;
    margin-bottom: 10px;
    background-color: orange;
    font-size: 40px;
}

.question{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

#answer{
    width: 100px;
    height: 35px;
    margin-bottom: 50px;
}

.prefix{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

.description{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

.id{
    position: relative;
    width: 90%;
    height: 20px;
    margin-bottom: 10px;
    margin-left: 10%;
}

.name{
    position: relative;
    width: 90%;
    height: 20px;
    margin-bottom: 20px;
    margin-left: 10%;
}

.CreateArray{
    width: 100px;
    height: 35px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="./style.css">
    <title>Hoi</title>

        <button id="QuestionPartBtn" class="QPB" type="button" onclick="NewArray.generateQuestionPart()">+</button>

        <button id="CreateArray" class="CreateArray" type="button" onclick="NewArray.writeArray()">Create Array</button>

```
</div>
</div>
</p>
<p>I created this system that makes an array with information that a user fills in in input fields.
The input fields are dynamically generated, so I use a for loop to show them all in an innerHTML that eventually creates the array.</p>
<p>My code:</p>
```            this.answerDIV = document.createElement('div');
            this.answerDIV.className = 'answerDIV' + this.count;
            this.answerDIV.id = 'AnswerDivId';

            this.answer = document.createElement('button');
            this.answer.setAttribute('type', 'button');
            this.answer.id = 'answer';
            this.answer.className = 'answerN' + this.count;
            this.answer.innerHTML = 'Add Answer';
            this.answer.onclick = function (e) {
                for (let i = 0; i < NewArray.count; i++) {
                    if (e.target.className.endsWith(i)) {
                        NewArray.id = document.createElement('input');
                        NewArray.id.setAttribute('type', 'text');
                        NewArray.id.id = 'id' + i;
                        NewArray.id.classList.add('id');
                        NewArray.id.placeholder = 'Add the ID of the answer';

                        NewArray.Name = document.createElement('input');
                        NewArray.Name.setAttribute('type', 'text');
                        NewArray.Name.id = 'Name' + i;
                        NewArray.Name.className = 'name';
                        NewArray.Name.placeholder = 'Add the text that is on the answer button';
                        // console.log(e.target.className);

                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
                    }
                }
            }
```
<p>For loop:</p>
```            for (let i = 0; i < this.count; i++) {
                let code = document.createElement('p');

                let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";

                let answers = document.querySelectorAll("input#Name" + i)
                console.log(answers.length);

                for (let y = 0; y < answers.length; y++) {
                    output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
                }

                output += "], '" + document.getElementById('prefix' + i).value + "',";
                output += "'" + document.getElementById('description' + i).value + "',";

                code.innerHTML = output;

                this.arrayCode.appendChild(code);
            }
```

The problem is with the second loop. Whenever I create 3 input fields for one question and I generate the innerHTML code it does show me all 3, except that they are all the first input field and the second and third aren't used as seen in the following screenshot:The problem
if i change i to y: Problem 2

(My FiddleJS link):https://jsfiddle.net/thijsl0705/1s98gumk/1/

答:
I entered a,b,c then add answer, d,e then hit the plus sign and add f,g,h,i,j then create array. then hit the plus sign and add 1,2,3,4,5 and create the array and get:

let Quiz = [

let Quiz = [

new QuizPart('a', [new ChosenAnswer('d', 'e'),], 'b','c',

new QuizPart('f', [new ChosenAnswer('i', 'j'),], 'g','h',

new QuizPart('a', [new ChosenAnswer('d', 'e'),], 'b','c',

new QuizPart('f', [new ChosenAnswer('i', 'j'),], 'g','h',

new QuizPart('1', [new ChosenAnswer('4', '5'),], '2','3',

]

]

what exactly is the problem?  what do you want to do?  Looks like you might be missing a closing ) for each new QuizPart

Body:
    class GenerateArray {

        constructor() {
            this.arrayCode = document.getElementById('code');
            this.BaseCode = document.getElementById('preCode');
            this.startCode = document.getElementById('startC');
            this.endCode = document.getElementById('endC');
            this.question = "";
            this.prefix = "";
            this.description = "";
            this.answer = "";
            this.id = "";
            this.Name = "";
            this.answerDIV = "";
            this.count = 0;

        }

        generateQuestionPart() {

            this.question = document.createElement('input');
            this.question.setAttribute('type', 'text');
            this.question.id = 'question' + this.count;
            this.question.className = 'question';
            this.question.placeholder = 'What is the question?'

            this.prefix = document.createElement('input');
            this.prefix.setAttribute('type', 'text');
            this.prefix.className = 'prefix';
            this.prefix.id = 'prefix' + this.count;
            this.prefix.placeholder = 'The prefix of the question that belongs to the link'

            this.description = document.createElement('input');
            this.description.setAttribute('type', 'text');
            this.description.id = 'description' + this.count;
            this.description.className = 'description';
            this.description.placeholder = 'Add the description that is going to be in the info pop up';

            this.answerDIV = document.createElement('div');
            this.answerDIV.className = 'answerDIV' + this.count;
            this.answerDIV.id = 'AnswerDivId';

            this.answer = document.createElement('button');
            this.answer.setAttribute('type', 'button');
            this.answer.id = 'answer';
            this.answer.className = 'answerN' + this.count;
            this.answer.innerHTML = 'Add Answer';
            this.answer.onclick = function (e) {
                for (let i = 0; i < NewArray.count; i++) {
                    if (e.target.className.endsWith(i)) {
                        NewArray.id = document.createElement('input');
                        NewArray.id.setAttribute('type', 'text');
                        NewArray.id.id = 'id' + i;
                        NewArray.id.classList.add('id');
                        NewArray.id.placeholder = 'Add the ID of the answer';

                        NewArray.Name = document.createElement('input');
                        NewArray.Name.setAttribute('type', 'text');
                        NewArray.Name.id = 'Name' + i;
                        NewArray.Name.className = 'name';
                        NewArray.Name.placeholder = 'Add the text that is on the answer button';
                        // console.log(e.target.className);

                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
                    }
                }
            }

            document.getElementsByClassName('create')[0].appendChild(this.question);
            document.getElementsByClassName('create')[0].appendChild(this.prefix);
            document.getElementsByClassName('create')[0].appendChild(this.description);
            document.getElementsByClassName('create')[0].appendChild(this.answerDIV);
            document.getElementsByClassName('create')[0].appendChild(this.answer);
            this.count++;
            // console.log(NewArray.answer.length)
        }

        writeArray() {
            let basis = document.createElement('p');
            basis.innerHTML =
                "    class QuizPart {\n" +
                "        constructor(questionText, chosenAnswer, prefix, questionDescription) {\n" +
                "            this.questionText = questionText;\n" +
                "            this.chosenAnswer = chosenAnswer;\n" +
                "            this.prefix = prefix;\n" +
                "            this.questionDescription = questionDescription;\n" +
                "        }\n" +
                "    }\n" +
                "\n" +
                "    class ChosenAnswer {\n" +
                "        constructor(id, name) {\n" +
                "            this.id = id;\n" +
                "            this.name = name;\n" +
                "        }\n" +
                "    }";

            this.BaseCode.appendChild(basis);

            let startC = document.createElement('p');
            startC.innerHTML = "let Quiz = [";

            for (let i = 0; i < this.count; i++) {
                let code = document.createElement('p');

                let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";

                let answers = document.querySelectorAll("input#Name" + i)
                console.log(answers.length);

                for (let y = 0; y < answers.length; y++) {
                    output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
                }

                output += "], '" + document.getElementById('prefix' + i).value + "',";
                output += "'" + document.getElementById('description' + i).value + "',";

                code.innerHTML = output;

                this.arrayCode.appendChild(code);
            }
            let endC = document.createElement('p');
            endC.innerHTML = "]"

            this.startCode.appendChild(startC);
            this.endCode.appendChild(endC);
            // console.log(this.count.length);
        }
    }

    NewArray = new GenerateArray();
    NewArray.generateQuestionPart();

body {
    margin: 0;
    padding: 0;
}
.container{
    height: 1000px;
    width: 800px;
    position: relative;
    margin-top: 5px;
    left: 50%;
    -ms-transform: translate(-50%, 5%);
    transform: translate(-50%, 5%);
}

.QPB{
    width: 50px;
    height: 50px;
    margin-bottom: 10px;
    background-color: orange;
    font-size: 40px;
}

.question{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

#answer{
    width: 100px;
    height: 35px;
    margin-bottom: 50px;
}

.prefix{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

.description{
    width: 100%;
    height: 20px;
    margin-bottom: 10px;
}

.id{
    position: relative;
    width: 90%;
    height: 20px;
    margin-bottom: 10px;
    margin-left: 10%;
}

.name{
    position: relative;
    width: 90%;
    height: 20px;
    margin-bottom: 20px;
    margin-left: 10%;
}

.CreateArray{
    width: 100px;
    height: 35px;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="./style.css">
    <title>Hoi</title>

        <button id="QuestionPartBtn" class="QPB" type="button" onclick="NewArray.generateQuestionPart()">+</button>

        <button id="CreateArray" class="CreateArray" type="button" onclick="NewArray.writeArray()">Create Array</button>

I created this system that makes an array with information that a user fills in in input fields.
The input fields are dynamically generated, so I use a for loop to show them all in an innerHTML that eventually creates the array.

My code:

            this.answerDIV = document.createElement('div');
            this.answerDIV.className = 'answerDIV' + this.count;
            this.answerDIV.id = 'AnswerDivId';

            this.answer = document.createElement('button');
            this.answer.setAttribute('type', 'button');
            this.answer.id = 'answer';
            this.answer.className = 'answerN' + this.count;
            this.answer.innerHTML = 'Add Answer';
            this.answer.onclick = function (e) {
                for (let i = 0; i < NewArray.count; i++) {
                    if (e.target.className.endsWith(i)) {
                        NewArray.id = document.createElement('input');
                        NewArray.id.setAttribute('type', 'text');
                        NewArray.id.id = 'id' + i;
                        NewArray.id.classList.add('id');
                        NewArray.id.placeholder = 'Add the ID of the answer';

                        NewArray.Name = document.createElement('input');
                        NewArray.Name.setAttribute('type', 'text');
                        NewArray.Name.id = 'Name' + i;
                        NewArray.Name.className = 'name';
                        NewArray.Name.placeholder = 'Add the text that is on the answer button';
                        // console.log(e.target.className);

                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
                        document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
                    }
                }
            }

For loop:

            for (let i = 0; i < this.count; i++) {
                let code = document.createElement('p');

                let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";

                let answers = document.querySelectorAll("input#Name" + i)
                console.log(answers.length);

                for (let y = 0; y < answers.length; y++) {
                    output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
                }

                output += "], '" + document.getElementById('prefix' + i).value + "',";
                output += "'" + document.getElementById('description' + i).value + "',";

                code.innerHTML = output;

                this.arrayCode.appendChild(code);
            }

The problem is with the second loop. Whenever I create 3 input fields for one question and I generate the innerHTML code it does show me all 3, except that they are all the first input field and the second and third aren't used as seen in the following screenshot:The problem
if i change i to y: Problem 2

(My FiddleJS link):https://jsfiddle.net/thijsl0705/1s98gumk/1/


问:
How to integrate Bootstrap into an angular CLI project
I'm relatively new to integrating bootstrap into angular and I started by running the
npm i --save bootstrap@3 command which downloaded the required files into the node_modules folder of my angular project.

However, when I went to the angular.json file to input the relative path into the "styles" section, I got the following error:

```<code> "styles": [
              "src/node_modules/boostrap/dist/css"
            ],
</code>```

ERROR in multi ./src/node_modules/boostrap/dist/css
  Module not found: Error: Can't resolve
  'C:\Users\User\Desktop\ShoppingOnline\client\yoavonlineshop\src\node_modules\boostrap\dist\css' in 'C:\Users\User\Desktop\ShoppingOnline\client\yoavonlineshop'

I made sure to use backslash.
The angular node modules folder is outside the src folder. Do I need to go up one tier? ../?
The output path is:

```<code>"outputPath": "dist/YoavOnlineShop",
</code>```

edit: Thank you guys, it doesn't produce an error now. However, the styles of bootstrap aren't being applied. Do I need to add anything into the app.module or the specific components?

Before integrating bootstrap like above, I used CDN and it worked fine but now I think I broke it.

答:
to install bootstrap jquery popper.js and font-awesome
we need to tape this request

npm install bootstrap jquery popper.js and font-awesome

and in angular.json we put the relative path of all our elements

```<code>"root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/salam-angular",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

"styles": [
              "src/styles.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/font-awesome/css/font-awesome.min.css"
            ],
            "scripts": [
              "./node_modules/bootstrap/dist/js/bootstrap.min.js",
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/popper.js/dist/popper.min.js"
            ]
</code>```

Body:
I'm relatively new to integrating bootstrap into angular and I started by running the
npm i --save bootstrap@3 command which downloaded the required files into the node_modules folder of my angular project.

However, when I went to the angular.json file to input the relative path into the "styles" section, I got the following error:

 "styles": [
              "src/node_modules/boostrap/dist/css"
            ],

ERROR in multi ./src/node_modules/boostrap/dist/css
  Module not found: Error: Can't resolve
  'C:\Users\User\Desktop\ShoppingOnline\client\yoavonlineshop\src\node_modules\boostrap\dist\css' in 'C:\Users\User\Desktop\ShoppingOnline\client\yoavonlineshop'

I made sure to use backslash.
The angular node modules folder is outside the src folder. Do I need to go up one tier? ../?
The output path is:

"outputPath": "dist/YoavOnlineShop",

edit: Thank you guys, it doesn't produce an error now. However, the styles of bootstrap aren't being applied. Do I need to add anything into the app.module or the specific components?

Before integrating bootstrap like above, I used CDN and it worked fine but now I think I broke it.

Body:
to install bootstrap jquery popper.js and font-awesome
we need to tape this request

npm install bootstrap jquery popper.js and font-awesome

and in angular.json we put the relative path of all our elements

"root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/salam-angular",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

"styles": [
              "src/styles.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/font-awesome/css/font-awesome.min.css"
            ],
            "scripts": [
              "./node_modules/bootstrap/dist/js/bootstrap.min.js",
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/popper.js/dist/popper.min.js"
            ]


问:
How to limit the number of selected checkboxes?
I have the following HTML:

Which level would you like? (Select 3 Levels)

   <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7

```

Live site:

http://www.chineselearnonline.com/amember/signup20.php

How can I do it so that the user can only select 3 of those checkboxes?

答:
This method works well with checkboxes in a container, such as bootstrap checkbox</p>
```<code>    const checkedLimmit = 2;

    function ValidateCheckBoxGroup(container) {

        if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
        } else {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
        }
    }

    $(function () {
        // validate containers on page load
        $('div.checkbox-group').each(function () {
            ValidateCheckBoxGroup($(this));
        });

        // set checkbox events
        $('div.checkbox-group input[type="checkbox"]').change(function () {
            ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
        });
    });
</code>```

Body:
I have the following HTML:

Which level would you like? (Select 3 Levels)

   <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6

   <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7

Live site:

http://www.chineselearnonline.com/amember/signup20.php

How can I do it so that the user can only select 3 of those checkboxes?

Body:
This method works well with checkboxes in a container, such as bootstrap checkbox

    const checkedLimmit = 2;

    function ValidateCheckBoxGroup(container) {

        if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
        } else {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
        }
    }

    $(function () {
        // validate containers on page load
        $('div.checkbox-group').each(function () {
            ValidateCheckBoxGroup($(this));
        });

        // set checkbox events
        $('div.checkbox-group input[type="checkbox"]').change(function () {
            ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
        });
    });


问:
Changing card style when clicked
I am mapping data into a card, onClick of the card, it shows that it is active by background color change and input box being checked. This is my code.
I am mapping data into a card, so i am rendering a list of card.  onClick of the card, it shows that it is active by change in background color and input box being checked.it is checked when i click it but when it navigates to a new route per id, it is unchecked. This is code of the card component.</p>
```<code>import React, { useState } from "react";
import { useHistory } from "react-router";
import styled from "styled-components";

export default function Card(props) {
  const {item,id} = props;

  const [checked, setChecked] = useState(false);
  const [background, setBackground] = useState("#F3F1FA");
  const [cardBorder, setCardBorder] = useState("transparent");
  const history = useHistory();

  const CheckBox = () => {
    setChecked(!checked);
    if (checked === true) {
      setBackground("#F3F1FA");
      setCardBorder("transparent");
    } else {
      setBackground("#fff");
      setCardBorder("2px solid #7f67ce");
    }
  };

  return (
    <CardWrapper
      onClick={()=>{
      CheckBox();
      // console.log(props.id)
      history.push(`/invoice/${id}`)
    }}
      background={background}
      cardBorder={cardBorder}
    >
     <div> Content </div>
      <Check>
        <input
          type="checkbox"
          checked={checked}
          value={checked}
          onChange={() => CheckBox}
        />
      </Check>
    </CardWrapper>
  );
}

const CardWrapper = styled.button`
  background-color: ${(props) => props.background};
  border: ${(props) => props.cardBorder};
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 347px;
  height: 129px;
  border-radius: 16px;
  color: #7f67ce;
  padding-left: 25px;
  padding-right: 25px;
  text-align: left;
  margin-top:10px;
  margin-bottom:10px;
  img {
    padding-bottom: 15px;
  }
  @media(max-width:1200px){
    width:300px;
  }
  @media(max-width:1200px){
    width:280px;
  }
  :first-child{
    margin-top:0px;
  }

`;
</code>```

答:
You want your data to be persistent across app so you need to use one of:

React Context API

Redux

Save to local storage / session storage and then on useEffect, first render to initialize your data with the saved one

Title: Changing card style when clicked

Body:
I am mapping data into a card, onClick of the card, it shows that it is active by background color change and input box being checked. This is my code.
I am mapping data into a card, so i am rendering a list of card.  onClick of the card, it shows that it is active by change in background color and input box being checked.it is checked when i click it but when it navigates to a new route per id, it is unchecked. This is code of the card component.

import React, { useState } from "react";
import { useHistory } from "react-router";
import styled from "styled-components";

export default function Card(props) {
  const {item,id} = props;

  const [checked, setChecked] = useState(false);
  const [background, setBackground] = useState("#F3F1FA");
  const [cardBorder, setCardBorder] = useState("transparent");
  const history = useHistory();

  const CheckBox = () => {
    setChecked(!checked);
    if (checked === true) {
      setBackground("#F3F1FA");
      setCardBorder("transparent");
    } else {
      setBackground("#fff");
      setCardBorder("2px solid #7f67ce");
    }
  };

  return (
    <CardWrapper
      onClick={()=>{
      CheckBox();
      // console.log(props.id)
      history.push(`/invoice/${id}`)
    }}
      background={background}
      cardBorder={cardBorder}
    >

 Content

      <Check>
        <input
          type="checkbox"
          checked={checked}
          value={checked}
          onChange={() => CheckBox}
        />
      </Check>
    </CardWrapper>
  );
}

const CardWrapper = styled.button`
  background-color: ${(props) => props.background};
  border: ${(props) => props.cardBorder};
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 347px;
  height: 129px;
  border-radius: 16px;
  color: #7f67ce;
  padding-left: 25px;
  padding-right: 25px;
  text-align: left;
  margin-top:10px;
  margin-bottom:10px;
  img {
    padding-bottom: 15px;
  }
  @media(max-width:1200px){
    width:300px;
  }
  @media(max-width:1200px){
    width:280px;
  }
  :first-child{
    margin-top:0px;
  }

`;


问:
Python: String formatter to get underlined headline
To structure my console output, I want to print some information and I would like to start with an underlined headline.
But how to do it nicely without creating an extra variable?

Right now I do it like this:

```<code>print("{:s}\n{:s}\n".format("This is an underlined headline.", len("This is an underlined headline.") * "-"))
</code>```

what gives me the desired output:

```<code>This is an underlined headline.
-------------------------------
</code>```

But that code is bad. Is there some better format string to achieve that?

```<code>print("{0:s}\n?????\n".format("This is an underlined headline.", "-"))
</code>```

Thank you :)

答:
snakecharmerb's answer works for me, but doesn't underline the last character, here is quick and inelegant fix:</p>
```<code>def underline(input):
    return '{:s}'.format('\u0332'.join(input+' '))[:-1]
</code>```

Body:
To structure my console output, I want to print some information and I would like to start with an underlined headline.
But how to do it nicely without creating an extra variable?

Right now I do it like this:

print("{:s}\n{:s}\n".format("This is an underlined headline.", len("This is an underlined headline.") * "-"))

what gives me the desired output:

This is an underlined headline.
-------------------------------

But that code is bad. Is there some better format string to achieve that?

print("{0:s}\n?????\n".format("This is an underlined headline.", "-"))

Thank you :)

Body:
snakecharmerb's answer works for me, but doesn't underline the last character, here is quick and inelegant fix:

def underline(input):
    return '{:s}'.format('\u0332'.join(input+' '))[:-1]


问:
How to merge dicts, collecting values from matching keys?
I have multiple dicts (or sequences of key-value pairs) like this:

```<code>d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}
</code>```

How can I efficiently get a result like this, as a new dict?

```<code>d = {key1: (x1, x2), key2: (y1, y2)}
</code>```

See also: How can one make a dictionary with duplicate keys in Python?.

答:
There is a great library funcy doing what you need in a just one, short line.

from funcy import join_with
from pprint import pprint

d1 = {"key1": "x1", "key2": "y1"}
d2 = {"key1": "x2", "key2": "y2"}

list_of_dicts = [d1, d2]

merged_dict = join_with(tuple, list_of_dicts)

pprint(merged_dict)
```
<p>Output:</p>
```{'key1': ('x1', 'x2'), 'key2': ('y1', 'y2')}
```

More info here: funcy -> join_with.

Body:
I have multiple dicts (or sequences of key-value pairs) like this:

d1 = {key1: x1, key2: y1}
d2 = {key1: x2, key2: y2}

How can I efficiently get a result like this, as a new dict?

d = {key1: (x1, x2), key2: (y1, y2)}

See also: How can one make a dictionary with duplicate keys in Python?.

Body:
There is a great library funcy doing what you need in a just one, short line.

from funcy import join_with
from pprint import pprint

d1 = {"key1": "x1", "key2": "y1"}
d2 = {"key1": "x2", "key2": "y2"}

list_of_dicts = [d1, d2]

merged_dict = join_with(tuple, list_of_dicts)

pprint(merged_dict)

Output:

{'key1': ('x1', 'x2'), 'key2': ('y1', 'y2')}

More info here: funcy -> join_with.


问:
Assembly 'System.Web.Http, ...' uses 'Newtonsoft.Json, Version=6.0.0.0...' which has a higher version than referenced assembly
I'm getting the following error when I Rebuild my project.

```<code>Assembly 'System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' which has a higher version than referenced assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'    D:\Development\MyProject\bin\System.Web.Http.dll
</code>```

I have already uninstalled and installed the latest version of Newtonsoft.Json (9.0.1) using Manage NuGet Packages in VS 2013. Why is it still referencing version 6.0.0.0 (or is it 4.5.0.0)?

My web.config shows the following:

```<code><dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
   <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0"/>
</dependentAssembly>
</code>```

What else should I do to resolve this? Thanks.

答:
I've just had this issue, and spent way too much time fixing it.

What clinched it for me was realising that the publish stage of my API didn't publish the web.config in the root folder of the API, but in the bin folder.

Moving the web.config to the root fixed the issue as IIS can then set up the API correctly, rather than falling back to host/machine configs (which don't include the rebinding instructions)

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the following error when I Rebuild my project.

Assembly 'System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' which has a higher version than referenced assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'    D:\Development\MyProject\bin\System.Web.Http.dll

I have already uninstalled and installed the latest version of Newtonsoft.Json (9.0.1) using Manage NuGet Packages in VS 2013. Why is it still referencing version 6.0.0.0 (or is it 4.5.0.0)?

My web.config shows the following:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
   <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0"/>
</dependentAssembly>

What else should I do to resolve this? Thanks.


问:
wrong addition of float type
Today I'm facing a really weird issue. I'm working at a simple project to display some data in a table with billing information provided by a REST-API. Because of the missing backend I backed up on a random generated array. That's working pretty perfect and everything just looks fine. BUT... one small thing seems like witchcraft, I simply want to sum up every billing to display the total amount on top of the table, but Typescript seems to have a really really weird way of handling float/int/string type conversion, I think. Here is a small Pic of my console log, it displays the row object and the sum.

I want to sum up every value and for gods sake I don't know how Typescript is adding up 3876.61 plus 8.03 to 3884.6400000000003, but... how can I get rid of that? Is rounding the only possible solution?

答:
Like Aleksi said, using | number pipe takes care of it.

number1: {{number1}} + number2 {{number2}} = {{number1 + number2 | number }}

number1: 3876.61 + number2 8.03 = 3,884.64

https://stackblitz.com/edit/angular-ivy-kf8hct?file=src%2Fapp%2Fapp.component.html

Title: wrong addition of float type


问:
How to get pressed char from System.Windows.Input.KeyEventArgs?
I have System.Windows.Input.KeyEventArgs e variable. I want to get real char. For example, i press } button on keyboard. And normally it returns string like  oem.. but i want to get } char. How to do ?

[EDIT] I use this in TextBox .

答:
You have e.Key property you can use for just that. Here's a link to msdn.

Edit:

I didn't realize you need the actual char. You can take a look here They say that in WPF you can do it using some Win32 APIs, while in Silverlight it seems rather difficult. Also you can look at KeyInterop.VirtualKeyFromKey - you can convert the WPF Key enum into a WinForms Keys enumeration, which does give you some more information. I haven't tried any of the solutions, so I don't know if any of them will work.

And one last thing. Why do you need the char from the KeyDown/Up event? Are you sure you can't use the TextChanged event instead? It will be much easier to get the exact char, if you can.


问:
Android RemoteServiceExeption: Context.startForegroundService() did not then call Service.startForeground()
I know, there are already many questions about this error. But I tried many solutions and nothing worked for me. I have a Notification Service in my application with a timer in it and crashlytics reports hundreds of crashes (android 8 - 12) like this:

ForegroundServiceDidNotStartInTimeException:

```<code>Fatal Exception: android.app.ForegroundServiceDidNotStartInTimeException
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{cac9d0b u0 com.malmatech.eggtimer/.NotificationUtil}

android.app.ActivityThread.throwRemoteServiceException (ActivityThread.java:2134)
android.app.ActivityThread.access$2900 (ActivityThread.java:309)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:2363)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loopOnce (Looper.java:226)
android.os.Looper.loop (Looper.java:313)
android.app.ActivityThread.main (ActivityThread.java:8582)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:563)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)
</code>```

and RemoteServiceException:

```<code>Fatal Exception: android.app.RemoteServiceException
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{d760a21 u0 com.malmatech.eggtimer/.NotificationUtil}

android.app.ActivityThread$H.handleMessage (ActivityThread.java:2313)
android.os.Handler.dispatchMessage (Handler.java:107)
android.os.Looper.loop (Looper.java:213)
android.app.ActivityThread.main (ActivityThread.java:8178)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:513)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1101)
</code>```

I double checked my code and searched the web but didn't find anything and never get these exceptions on my own devices or emulators...

The Notification is only shown, when a timer is running and the application is closed. In the onPause() of my TimerActivity I start the service:

```<code>if (timerState == TimerState.Running){
    timer.cancel()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        MyContext.getContext().startForegroundService(Intent(this, NotificationUtil::class.java))
    } else {
        startService(Intent(this, NotificationUtil::class.java))
    }
}
</code>```

In onResume() I stop the service:

```<code>try {
    MyContext.getContext().stopService(
        Intent(
            MyContext.getContext(),
            NotificationUtil::class.java
        )
    )
} catch (ex: Exception) {
    ex.printStackTrace()
}
</code>```

And here is my service class, I cut out some irrelevant code but everything for managing the notification should be included.

```<code>class NotificationUtil : Service() {
override fun onBind(intent: Intent?): IBinder? {
    return null
}

var eggCount = 1
private var secondsRemaining: Long = 0
private lateinit var timer: CountDownTimer
// some more, irrelevant for question

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    showNotification()
    log("onStartCommand executed with startId: $startId")
    if (intent != null) {
        val action = intent.action
        log("using an intent with action $action")
    } else {
        log("with a null intent. It has been probably restarted by the system.")
    }
    // by returning this we make sure the service is restarted if the system kills the service
    return START_STICKY
}

override fun onCreate() {
    super.onCreate()

    //irrelevant Code - getting an array from SharedPreferences and setting up textToSpeech

    showNotification()
    startTimer()
}

override fun onDestroy() {
    super.onDestroy()
    hideNotification()
    timer.cancel()
}

fun showNotification(done: Boolean = false) {
    val nBuilder = NotificationCompat.Builder(applicationContext, "menu_timer")
        .setSmallIcon(R.drawable.ic_notification_res_specific)
        .setOngoing(true)
        .setAutoCancel(true)
        .setDefaults(0)
        .setContentIntent(
            getPendingIntentWithStack(
                applicationContext,
                TimerActivity::class.java
            )
        )
        .setPriority(PRIORITY_MAX)
        .setVisibility(VISIBILITY_PUBLIC)
        .setNotificationSilent()

    if (!done) {

        //irrelecantCode, setting ginishedStr and finishedIndividualString

        nBuilder.setContentTitle(getString(R.string.eggTimerRunning))
        if (eggCount > 1) {
            nBuilder.setStyle(
                NotificationCompat.BigTextStyle().bigText(
                    getString(R.string.remainingTimeNotification) + " $finishedStr\n" + getString(
                        R.string.nextEggNotification
                    ) + " $finishedIndividualString"
                )
            )
                .setContentText(
                    getString(R.string.remainingTimeNotification) + " $finishedStr\n" + getString(
                        R.string.nextEggNotification
                    ) + " $finishedIndividualString"
                )
        } else {
            nBuilder.setStyle(
                NotificationCompat.BigTextStyle()
                    .bigText(getString(R.string.remainingTimeNotification) + " $finishedStr")
            )
                .setContentText(getString(R.string.remainingTimeNotification) + " $finishedStr")
        }
    } else {
        nBuilder.setContentTitle(getString(R.string.eggTimerDone))
            .setStyle(
                NotificationCompat.BigTextStyle().bigText(getString(R.string.BonAppetite))
            )
            .setContentText(getString(R.string.BonAppetite))
    }

    //irrelevant code

    val nManager =
        applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    nManager.createNotificationChannel("menu_timer", "Timer App Timer", true)

    nManager.notify(135678, nBuilder.build())

    val notification: Notification = nBuilder.build()
    startForeground(135678, notification)
}

private fun hideNotification() {
    val nManager =
        applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    nManager.cancel(135678)
}

private fun startTimer() {
    timer = object : CountDownTimer(secondsRemaining * 1000, 1000) {
        override fun onFinish() = onTimerFinished()

        override fun onTick(millisUntilFinished: Long) {
            secondsRemaining = millisUntilFinished / 1000
            showNotification()
        }
    }.start()
}

private fun onTimerFinished(ring: Boolean = true) {
    if (ring) {
        //irrelevant code, ring and vibrate if timer is finished
    }
    showNotification(true)
}

@TargetApi(26)
private fun NotificationManager.createNotificationChannel(
    channelID: String,
    channelName: String,
    playSound: Boolean
) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelImportance = if (playSound) NotificationManager.IMPORTANCE_DEFAULT
        else NotificationManager.IMPORTANCE_LOW
        val nChannel = NotificationChannel(channelID, channelName, channelImportance)
        nChannel.enableLights(true)
        nChannel.lightColor = Color.BLUE
        this.createNotificationChannel(nChannel)
    }
}

private fun <T> getPendingIntentWithStack(
    context: Context,
    javaClass: Class<T>
): PendingIntent {
    val resultIntent = Intent(context, javaClass)
    resultIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP

    val stackBuilder = TaskStackBuilder.create(context)
    stackBuilder.addParentStack(javaClass)
    stackBuilder.addNextIntent(resultIntent)

    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
    } else {
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
    }
}
}
</code>```

Thank you so much in advance, I tried fixing the bug for weeks now but it's hard to fix it, because everything works for myself.

答:
So I've almost fixed the problem and no longer get hundreds of crashes every week, but only about one every two days.

Solution is this, when starting the foreground service: Just wait for the main looper in the main thread and then start it. It is much more common, that the 5s until the service needs to be started are enough now.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Handler(Looper.getMainLooper()).post{
        MyContext.getContext().startForegroundService(Intent(this, NotificationUtil::class.java))
    }
} else {
            startService(Intent(this, NotificationUtil::class.java))
}
</code>```

Body:
I know, there are already many questions about this error. But I tried many solutions and nothing worked for me. I have a Notification Service in my application with a timer in it and crashlytics reports hundreds of crashes (android 8 - 12) like this:

ForegroundServiceDidNotStartInTimeException:

Fatal Exception: android.app.ForegroundServiceDidNotStartInTimeException
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{cac9d0b u0 com.malmatech.eggtimer/.NotificationUtil}

android.app.ActivityThread.throwRemoteServiceException (ActivityThread.java:2134)
android.app.ActivityThread.access$2900 (ActivityThread.java:309)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:2363)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loopOnce (Looper.java:226)
android.os.Looper.loop (Looper.java:313)
android.app.ActivityThread.main (ActivityThread.java:8582)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:563)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1133)

and RemoteServiceException:

Fatal Exception: android.app.RemoteServiceException
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{d760a21 u0 com.malmatech.eggtimer/.NotificationUtil}

android.app.ActivityThread$H.handleMessage (ActivityThread.java:2313)
android.os.Handler.dispatchMessage (Handler.java:107)
android.os.Looper.loop (Looper.java:213)
android.app.ActivityThread.main (ActivityThread.java:8178)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:513)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1101)

I double checked my code and searched the web but didn't find anything and never get these exceptions on my own devices or emulators...

The Notification is only shown, when a timer is running and the application is closed. In the onPause() of my TimerActivity I start the service:

if (timerState == TimerState.Running){
    timer.cancel()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        MyContext.getContext().startForegroundService(Intent(this, NotificationUtil::class.java))
    } else {
        startService(Intent(this, NotificationUtil::class.java))
    }
}

In onResume() I stop the service:

try {
    MyContext.getContext().stopService(
        Intent(
            MyContext.getContext(),
            NotificationUtil::class.java
        )
    )
} catch (ex: Exception) {
    ex.printStackTrace()
}

And here is my service class, I cut out some irrelevant code but everything for managing the notification should be included.

class NotificationUtil : Service() {
override fun onBind(intent: Intent?): IBinder? {
    return null
}

var eggCount = 1
private var secondsRemaining: Long = 0
private lateinit var timer: CountDownTimer
// some more, irrelevant for question

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    showNotification()
    log("onStartCommand executed with startId: $startId")
    if (intent != null) {
        val action = intent.action
        log("using an intent with action $action")
    } else {
        log("with a null intent. It has been probably restarted by the system.")
    }
    // by returning this we make sure the service is restarted if the system kills the service
    return START_STICKY
}

override fun onCreate() {
    super.onCreate()

    //irrelevant Code - getting an array from SharedPreferences and setting up textToSpeech

    showNotification()
    startTimer()
}

override fun onDestroy() {
    super.onDestroy()
    hideNotification()
    timer.cancel()
}

fun showNotification(done: Boolean = false) {
    val nBuilder = NotificationCompat.Builder(applicationContext, "menu_timer")
        .setSmallIcon(R.drawable.ic_notification_res_specific)
        .setOngoing(true)
        .setAutoCancel(true)
        .setDefaults(0)
        .setContentIntent(
            getPendingIntentWithStack(
                applicationContext,
                TimerActivity::class.java
            )
        )
        .setPriority(PRIORITY_MAX)
        .setVisibility(VISIBILITY_PUBLIC)
        .setNotificationSilent()

    if (!done) {

        //irrelecantCode, setting ginishedStr and finishedIndividualString

        nBuilder.setContentTitle(getString(R.string.eggTimerRunning))
        if (eggCount > 1) {
            nBuilder.setStyle(
                NotificationCompat.BigTextStyle().bigText(
                    getString(R.string.remainingTimeNotification) + " $finishedStr\n" + getString(
                        R.string.nextEggNotification
                    ) + " $finishedIndividualString"
                )
            )
                .setContentText(
                    getString(R.string.remainingTimeNotification) + " $finishedStr\n" + getString(
                        R.string.nextEggNotification
                    ) + " $finishedIndividualString"
                )
        } else {
            nBuilder.setStyle(
                NotificationCompat.BigTextStyle()
                    .bigText(getString(R.string.remainingTimeNotification) + " $finishedStr")
            )
                .setContentText(getString(R.string.remainingTimeNotification) + " $finishedStr")
        }
    } else {
        nBuilder.setContentTitle(getString(R.string.eggTimerDone))
            .setStyle(
                NotificationCompat.BigTextStyle().bigText(getString(R.string.BonAppetite))
            )
            .setContentText(getString(R.string.BonAppetite))
    }

    //irrelevant code

    val nManager =
        applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    nManager.createNotificationChannel("menu_timer", "Timer App Timer", true)

    nManager.notify(135678, nBuilder.build())

    val notification: Notification = nBuilder.build()
    startForeground(135678, notification)
}

private fun hideNotification() {
    val nManager =
        applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    nManager.cancel(135678)
}

private fun startTimer() {
    timer = object : CountDownTimer(secondsRemaining * 1000, 1000) {
        override fun onFinish() = onTimerFinished()

        override fun onTick(millisUntilFinished: Long) {
            secondsRemaining = millisUntilFinished / 1000
            showNotification()
        }
    }.start()
}

private fun onTimerFinished(ring: Boolean = true) {
    if (ring) {
        //irrelevant code, ring and vibrate if timer is finished
    }
    showNotification(true)
}

@TargetApi(26)
private fun NotificationManager.createNotificationChannel(
    channelID: String,
    channelName: String,
    playSound: Boolean
) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelImportance = if (playSound) NotificationManager.IMPORTANCE_DEFAULT
        else NotificationManager.IMPORTANCE_LOW
        val nChannel = NotificationChannel(channelID, channelName, channelImportance)
        nChannel.enableLights(true)
        nChannel.lightColor = Color.BLUE
        this.createNotificationChannel(nChannel)
    }
}

private fun <T> getPendingIntentWithStack(
    context: Context,
    javaClass: Class<T>
): PendingIntent {
    val resultIntent = Intent(context, javaClass)
    resultIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP

    val stackBuilder = TaskStackBuilder.create(context)
    stackBuilder.addParentStack(javaClass)
    stackBuilder.addNextIntent(resultIntent)

    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
    } else {
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
    }
}
}

Thank you so much in advance, I tried fixing the bug for weeks now but it's hard to fix it, because everything works for myself.

Body:
So I've almost fixed the problem and no longer get hundreds of crashes every week, but only about one every two days.

Solution is this, when starting the foreground service: Just wait for the main looper in the main thread and then start it. It is much more common, that the 5s until the service needs to be started are enough now.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Handler(Looper.getMainLooper()).post{
        MyContext.getContext().startForegroundService(Intent(this, NotificationUtil::class.java))
    }
} else {
            startService(Intent(this, NotificationUtil::class.java))
}


问:
Create adjacency matrix from a path given as a vector of nodes in base R
Is there a compact and elegant way to create an adjacency matrix given a vector of the form shown (see code excerpt) in base R?

I give my best attempt below. Ideally, I would like to create the already-populated adjacency matrix in a single step as opposed to having to create the matrix data structure then fill it.

p <- 25 # Cardinality of vertex set; Number of nodes

hypothesis_path <- c(17, 7, 6, 1) # path in this form

path_to_D <- function(hypothesis_path, p) {
  path_len <- length(hypothesis_path) - 1
  idx_path <- t(sapply(1:path_len, function(i) hypothesis_path[i:(i+1)]))
  D <- matrix(0, p, p); D[idx_path] <- 1
  D
}

D <- path_to_D(hypothesis_path, p)

which(D == 1, arr.ind = TRUE)

# Desired indices of adjacency matrix are populated (with ones)
#      row col
# [1,]   6   1
# [2,]   7   6
# [3,]  17   7
```

Acceptable answers will avoid use of igraph or similar and will use the path vector in the form given. That said, advice and alternatives are of course always welcomed and appreciated.

答:
You can use a sparse matrix from the Matrix package. It is not base R but a very common package.

library(Matrix)

hypothesis_path <- c(17, 7, 6, 1)

D <- sparseMatrix(i = hypothesis_path[-length(hypothesis_path)],
                  j = hypothesis_path[-1])

which(D == 1, arr.ind = TRUE)
     row col
[1,]   6   1
[2,]   7   6
[3,]  17   7

```

Body:
Is there a compact and elegant way to create an adjacency matrix given a vector of the form shown (see code excerpt) in base R?

I give my best attempt below. Ideally, I would like to create the already-populated adjacency matrix in a single step as opposed to having to create the matrix data structure then fill it.

p <- 25 # Cardinality of vertex set; Number of nodes

hypothesis_path <- c(17, 7, 6, 1) # path in this form

path_to_D <- function(hypothesis_path, p) {
  path_len <- length(hypothesis_path) - 1
  idx_path <- t(sapply(1:path_len, function(i) hypothesis_path[i:(i+1)]))
  D <- matrix(0, p, p); D[idx_path] <- 1
  D
}

D <- path_to_D(hypothesis_path, p)

which(D == 1, arr.ind = TRUE)

# Desired indices of adjacency matrix are populated (with ones)
#      row col
# [1,]   6   1
# [2,]   7   6
# [3,]  17   7

Acceptable answers will avoid use of igraph or similar and will use the path vector in the form given. That said, advice and alternatives are of course always welcomed and appreciated.


问:
PHP SESSIONS: how do I store the quantities alongside the products which the user has added to their cart?
I have been trying to find this out for weeks and I'm not seeing it. how do I store the quantities alongside the products which the user has added to their cart? I need to have this because I need the users to be able to update the quantity from the items.

already tried a few things such as creating an array and trying to store quantity in a array but it only remembers the last number that the user put in. This is because its a post request. and to fix that I need to store quantities alongs side the products in cart. and thats where I'm stuck.

I tried:

```<code>if(isset($_POST['quantity'])){
    $quantity = $_POST['quantity'];
    $_SESSION['basket'][] = $quantity;
}
</code>```

but this put the last item a lot in the shopping cart
like this:

then I tried:

```<code>if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
    $_SESSION['quantity'] = $_POST['quantity'];
//           //$qty = $_SESSION["qty"] + 1;
     if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
           if ($_POST['broodnaam'] == $row['broodnaam']){
                $quantity = $_POST['quantity'];
//                    //array_push($_SESSION['qty'], $quantity);
//                 //    var_dump($_SESSION['qty']);
           }
     }
}
</code>```

but this only updates the last updated item from the cart.
I really don't know how to fix this can someone help me

code: ( part of the code as I don't feel like I need to share the styling and sessions_start() part

```<code><?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
  if( in_array( $broodjes ,$_SESSION['basket']) )
  {
  }else{
     $_SESSION['basket'][] = $broodjes;
  }
}else{
  $_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
    //echo "Key = $key; value = $value; <br>";
    $sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $value);
    $stmt->execute();
    $result = $stmt->get_result();
    if($row = $result->fetch_assoc()){
        //session for quantity
        $_SESSION["qty"] = array();
        echo '<div class="cart-items">';
        echo '<div class="cart-row">';
        echo '<div class="cart-item cart-column">';
        echo $row['broodnaam'];
        echo '</div>';
        echo '<div class="cart-item cart-column">';
        echo '€ ' . $row['prijs'];
        echo '</div>';
        //quantity
        echo '<div class="cart-item cart-column">';
        echo '<form method="POST" action="">';
        echo '<div class="col-xs-4">';
        echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
        echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" value="1" min="1" max="'.$row['voorraad'].'">';
        echo '</div>';
        echo '</form>';
        echo '</div>';
        //ik moet de quantity ergens in opslaan , denk in db, om zo nog de voorraad te verminderen
        if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
            $_SESSION['quantity'] = $_POST['quantity'];
            //           //$qty = $_SESSION["qty"] + 1;
            if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
                if ($_POST['broodnaam'] == $row['broodnaam']){
                    $quantity = $_POST['quantity'];
                    ////array_push($_SESSION['qty'], $quantity);
                    ////    var_dump($_SESSION['qty']);
                }
            }
        }
        echo '<div class="cart-item cart-column">';
        $rowtotaal = $row['prijs'] * $quantity;
        $sumtotal += $rowtotaal;
        echo $rowtotaal;
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }
}
?> <br />
<div class="cart-total">
    <strong class="cart-total-title">Total</strong>
    <span class="cart-total-price"> € <?php   echo $sumtotal;?></span>
</div>
<br/>
</code>```

答:
what you need is a unique column in your products' table.

generally, the unique column is either id or alias.

Then when you need to add an item to the cart:

```<code>// supposing you have the product id in the $pid variable and quantity in the $qty variable
$_SESSION['cart'][$pid] = $qty;
</code>```

Then when you need to access it you can easily loop through the session's cart.

```<code>foreach($_SESSION['cart'] as $product => $qty) {
  // do something with the product and quantity.
}
</code>```

how this works is, it creates an item in the cart array with the index of the product's unique column value and the item's value would be the quantity of the product added to the cart.

Body:
I have been trying to find this out for weeks and I'm not seeing it. how do I store the quantities alongside the products which the user has added to their cart? I need to have this because I need the users to be able to update the quantity from the items.

already tried a few things such as creating an array and trying to store quantity in a array but it only remembers the last number that the user put in. This is because its a post request. and to fix that I need to store quantities alongs side the products in cart. and thats where I'm stuck.

I tried:

if(isset($_POST['quantity'])){
    $quantity = $_POST['quantity'];
    $_SESSION['basket'][] = $quantity;
}

but this put the last item a lot in the shopping cart
like this:

then I tried:

if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
    $_SESSION['quantity'] = $_POST['quantity'];
//           //$qty = $_SESSION["qty"] + 1;
     if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
           if ($_POST['broodnaam'] == $row['broodnaam']){
                $quantity = $_POST['quantity'];
//                    //array_push($_SESSION['qty'], $quantity);
//                 //    var_dump($_SESSION['qty']);
           }
     }
}

but this only updates the last updated item from the cart.
I really don't know how to fix this can someone help me

code: ( part of the code as I don't feel like I need to share the styling and sessions_start() part

<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
  if( in_array( $broodjes ,$_SESSION['basket']) )
  {
  }else{
     $_SESSION['basket'][] = $broodjes;
  }
}else{
  $_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
    //echo "Key = $key; value = $value;
";
    $sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $value);
    $stmt->execute();
    $result = $stmt->get_result();
    if($row = $result->fetch_assoc()){
        //session for quantity
        $_SESSION["qty"] = array();
        echo '
';
        echo '
';
        echo '
';
        echo $row['broodnaam'];
        echo '
';
        echo '
';
        echo '€ ' . $row['prijs'];
        echo '
';
        //quantity
        echo '
';
        echo '<form method="POST" action="">';
        echo '
';
        echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
        echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" value="1" min="1" max="'.$row['voorraad'].'">';
        echo '
';
        echo '</form>';
        echo '
';
        //ik moet de quantity ergens in opslaan , denk in db, om zo nog de voorraad te verminderen
        if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
            $_SESSION['quantity'] = $_POST['quantity'];
            //           //$qty = $_SESSION["qty"] + 1;
            if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
                if ($_POST['broodnaam'] == $row['broodnaam']){
                    $quantity = $_POST['quantity'];
                    ////array_push($_SESSION['qty'], $quantity);
                    ////    var_dump($_SESSION['qty']);
                }
            }
        }
        echo '
';
        $rowtotaal = $row['prijs'] * $quantity;
        $sumtotal += $rowtotaal;
        echo $rowtotaal;
        echo '
';
        echo '
';
        echo '
';
    }
}
?>

    Total
     € <?php   echo $sumtotal;?>

Body:
what you need is a unique column in your products' table.

generally, the unique column is either id or alias.

Then when you need to add an item to the cart:

// supposing you have the product id in the $pid variable and quantity in the $qty variable
$_SESSION['cart'][$pid] = $qty;

Then when you need to access it you can easily loop through the session's cart.

foreach($_SESSION['cart'] as $product => $qty) {
  // do something with the product and quantity.
}

how this works is, it creates an item in the cart array with the index of the product's unique column value and the item's value would be the quantity of the product added to the cart.


问:
Angular Rxjs. don't close the subscription after reaching the error, but log the error in Angular's error handler
community.
I have one problem. I need to log an error in Angular's error handler without closing the stream subscription when an error occurs.

I have the following data stream:

```<code>/**DATA Provider Service*/
 getData(settings): Observable<any> {
  return HttpClientGET$(settings).pipe(
/***/
   map(response => transformMethod(response)),
/***/
   tap(convertedData => sendData(convertedData))
 );
}

sendData(data: any): void {
  this.replaySubject.next(data);
}

getConvertedData(): Observable<any> {
  this.replaySubject.asObservable();
}
</code>```
```<code> /**Parent Component*/

ngOnInit(): void {
 this.changePositionStream$.pipe(
  switchMap((settings) => this.dataService.getData(settings))
).subscribe();
}
</code>```
```<code>/**Child - Data Component*/

ngONInit(): void {
  this.service.getConvertedData().subscribe();
}
</code>```

Issue - an error can be caught in the Angular error handler when the error stream doesn't interrupt or use the throwError(). But when an error is thrown the subscription is closing.

How do I log an error without closing the data subscription?

答:
You can use RxJS materialize to handle errors and discard them:

```<code>export const catchAndDefaultTo = <T, K>(defaultValue?: K): MonoTypeOperatorFunction<T | K> => pipe(
  materialize(),
  map(n => n.kind !== 'C'
    ? new Notification('N', n.value || defaultValue)
    : n
  ),
  dematerialize(),
)
</code>```

Error notification does not have a value so n.value will not be set here and it will create a next notification instead with whatever is set as defaultValue. Error notification is now "discarded" and a next notification is send instead thus it will not close the stream.

I am not sure what part of your stream you want to handle so I assume somewhere here:

```<code>ngOnInit(): void {
  this.changePositionStream$.pipe(
    switchMap((settings) => this.dataService.getData(settings)),
    catchAndDefaultTo(undefined)
  ).subscribe();
}
</code>```

I am not 100% sure what materialize does but how I see it let's you manipulate every notification (next, error and complete) that goes through your stream.

Body:
community.
I have one problem. I need to log an error in Angular's error handler without closing the stream subscription when an error occurs.

I have the following data stream:

/**DATA Provider Service*/
 getData(settings): Observable<any> {
  return HttpClientGET$(settings).pipe(
/***/
   map(response => transformMethod(response)),
/***/
   tap(convertedData => sendData(convertedData))
 );
}

sendData(data: any): void {
  this.replaySubject.next(data);
}

getConvertedData(): Observable<any> {
  this.replaySubject.asObservable();
}

 /**Parent Component*/

ngOnInit(): void {
 this.changePositionStream$.pipe(
  switchMap((settings) => this.dataService.getData(settings))
).subscribe();
}

/**Child - Data Component*/

ngONInit(): void {
  this.service.getConvertedData().subscribe();
}

Issue - an error can be caught in the Angular error handler when the error stream doesn't interrupt or use the throwError(). But when an error is thrown the subscription is closing.

How do I log an error without closing the data subscription?

Body:
You can use RxJS materialize to handle errors and discard them:

export const catchAndDefaultTo = <T, K>(defaultValue?: K): MonoTypeOperatorFunction<T | K> => pipe(
  materialize(),
  map(n => n.kind !== 'C'
    ? new Notification('N', n.value || defaultValue)
    : n
  ),
  dematerialize(),
)

Error notification does not have a value so n.value will not be set here and it will create a next notification instead with whatever is set as defaultValue. Error notification is now "discarded" and a next notification is send instead thus it will not close the stream.

I am not sure what part of your stream you want to handle so I assume somewhere here:

ngOnInit(): void {
  this.changePositionStream$.pipe(
    switchMap((settings) => this.dataService.getData(settings)),
    catchAndDefaultTo(undefined)
  ).subscribe();
}

I am not 100% sure what materialize does but how I see it let's you manipulate every notification (next, error and complete) that goes through your stream.


问:
How can I Get a List in cshtml.cs
I'm using a razor pages. I have on list of permissions, and this list have prop of treeview.

```<code>permissions.Add(new Paccess { id = "All", name = "Acesso Total", expanded = true, haschildren = true, ischecked = true });
permissions.Add(new Paccess { id = "G", name = "Geral", expanded = false, haschildren = false, ischecked = true, parent = "All" });
permissions.Add(new Paccess { id = "U", name = "Gestão de Utilizadores", expanded = false, haschildren = false, ischecked = true, parent = "All" });
permissions.Add(new Paccess { id = "E", name = "Gestão de Equipamentos", expanded = false, haschildren = false, ischecked = true, parent = "All" });
</code>```

In my cshtml I have this treeView

```<code><ejs-dialog id="default_dialog" isModal="true" width="500px" visible="false" showCloseIcon="true" header="Acessos">
    <e-content-template>
        <form method="post" style="padding:1em">
            <ejs-treeview id="listdata" name="permissions" TValue="Paccess" showCheckBox="true" nodeClicked="nodeCheck" autoCheck="true">
                <e-treeview-fields TValue="Paccess" dataSource="@Model.permissions" text="name" name="permissions" id="id" parentId="parent" hasChildren="haschildren" expanded="expanded" IsChecked="ischecked"></e-treeview-fields>
            </ejs-treeview>
            <button class="button special pull-right" asp-page-handler="Save">Teste</button>
        </form>
    </e-content-template>
</ejs-dialog>
</code>```

I want, when I click in Teste, get the list in my cshtml.cs.

Paccess class:

```<code>public class Paccess
{
    public string? id { get; set; }
    public string? name { get; set; }
    public bool haschildren { get; set; }
    public string? parent { get; set; }
    public bool expanded { get; set; }
    public bool ischecked { get; set; }
}
</code>```

答:
In TreeView, we have getTreeData method which will retrieve the updated data source of TreeView. If you pass the ID of TreeView node as arguments for this method, then it will return the updated data source of the corresponding node otherwise it will return the entire updated data source of TreeView. Check the below code snippet.</p>
```<code><button class="button special pull-right" id="normalbtn" asp-page-handler="Save">Teste</button>
...
document.getElementById('normalbtn').onclick = function () {
    var treeview = document.getElementById("listdata").ej2_instances[0];
    //Here you can get the updated datasource.
    var data = treeview.getTreeData();
}
</code>```

Title: How can I Get a List in cshtml.cs

Body:
I'm using a razor pages. I have on list of permissions, and this list have prop of treeview.

permissions.Add(new Paccess { id = "All", name = "Acesso Total", expanded = true, haschildren = true, ischecked = true });
permissions.Add(new Paccess { id = "G", name = "Geral", expanded = false, haschildren = false, ischecked = true, parent = "All" });
permissions.Add(new Paccess { id = "U", name = "Gestão de Utilizadores", expanded = false, haschildren = false, ischecked = true, parent = "All" });
permissions.Add(new Paccess { id = "E", name = "Gestão de Equipamentos", expanded = false, haschildren = false, ischecked = true, parent = "All" });

In my cshtml I have this treeView

<ejs-dialog id="default_dialog" isModal="true" width="500px" visible="false" showCloseIcon="true" header="Acessos">
    <e-content-template>
        <form method="post" style="padding:1em">
            <ejs-treeview id="listdata" name="permissions" TValue="Paccess" showCheckBox="true" nodeClicked="nodeCheck" autoCheck="true">
                <e-treeview-fields TValue="Paccess" dataSource="@Model.permissions" text="name" name="permissions" id="id" parentId="parent" hasChildren="haschildren" expanded="expanded" IsChecked="ischecked"></e-treeview-fields>
            </ejs-treeview>
            <button class="button special pull-right" asp-page-handler="Save">Teste</button>
        </form>
    </e-content-template>
</ejs-dialog>

I want, when I click in Teste, get the list in my cshtml.cs.

Paccess class:

public class Paccess
{
    public string? id { get; set; }
    public string? name { get; set; }
    public bool haschildren { get; set; }
    public string? parent { get; set; }
    public bool expanded { get; set; }
    public bool ischecked { get; set; }
}

Body:
In TreeView, we have getTreeData method which will retrieve the updated data source of TreeView. If you pass the ID of TreeView node as arguments for this method, then it will return the updated data source of the corresponding node otherwise it will return the entire updated data source of TreeView. Check the below code snippet.

<button class="button special pull-right" id="normalbtn" asp-page-handler="Save">Teste</button>
...
document.getElementById('normalbtn').onclick = function () {
    var treeview = document.getElementById("listdata").ej2_instances[0];
    //Here you can get the updated datasource.
    var data = treeview.getTreeData();
}


问:
what is the purpose of dbus interface xml file?
I am reading D-Bus API Design Guidelines:

Interface files for public API should be installed to $(datadir)/dbus-1/interfaces so that other services can load them.

OK... in order to understand how these interface files work, I open the file /usr/share/dbus-1/interfaces/org.gnome.Shell.Screenshot.xml (I'm using Ubuntu 20.04)

```<code><node>
  <interface name="org.gnome.Shell.Screenshot">
  ...
    <method name="PickColor">
      <arg type="a{sv}" direction="out" name="result"/>
    </method>
</code>```

Well, I see the interface name, I see the method name, but that is not enough. If I want to call this method using dbus-send

```<code>$ dbus-send --print-reply --dest=<service.name> </path/to/object> org.gnome.Shell.Screenshot.PickColor
</code>```

I need <service.name> and <path/to/object>, which this xml-file does not provide.

The queston is: what is the purpose of this file if it does not provide full information about the service interface? Is it used by dbus-daemon or by any other programs? Are such files really needed for something? Should I make a conclusion that an xml-file, which does not provide a path to object in , is incomplete? Should such file also mention a service known name (org.gnome.Shell.Screenshot in this case)?

答:
The answer is in the name: it’s a D-Bus interface file. It defines an interface, not an instantiation of that interface. There may be zero or more instantiations of an interface in D-Bus, and they may be dynamic. So their paths can’t be specified in an XML file.

If D-Bus was designed now, perhaps this XML file would have been structured or implemented differently. But this is what there is.

Body:
I am reading D-Bus API Design Guidelines:

Interface files for public API should be installed to $(datadir)/dbus-1/interfaces so that other services can load them.

OK... in order to understand how these interface files work, I open the file /usr/share/dbus-1/interfaces/org.gnome.Shell.Screenshot.xml (I'm using Ubuntu 20.04)

<node>
  <interface name="org.gnome.Shell.Screenshot">
  ...
    <method name="PickColor">
      <arg type="a{sv}" direction="out" name="result"/>
    </method>

Well, I see the interface name, I see the method name, but that is not enough. If I want to call this method using dbus-send

$ dbus-send --print-reply --dest=<service.name> </path/to/object> org.gnome.Shell.Screenshot.PickColor

I need <service.name> and <path/to/object>, which this xml-file does not provide.

The queston is: what is the purpose of this file if it does not provide full information about the service interface? Is it used by dbus-daemon or by any other programs? Are such files really needed for something? Should I make a conclusion that an xml-file, which does not provide a path to object in , is incomplete? Should such file also mention a service known name (org.gnome.Shell.Screenshot in this case)?


问:
VS Code Java appears to be compiling on every keystroke
I have been using VS Code with Java for a few months learning the basics. I am not able to update the app myself it is controlled by the company I work for.

Last Friday the IDE seemed to be trying to compile/build on every single key stroke. If I were to simply type something like:

```<code>int x;
</code>```

this will generate a Problem on:

i is not defined

in is not defined

int declared with no variable name.

declaration missing ';'

These 'problems' can take minutes for VS Code to catch up on and realise that statement is valid. There is no intellisense possible either with this so typing 'x.' anything raises more errors. I have searched for this issue and tried turning off auto save, build on save, java.autobuilder to off and the issues remain.

The Java Build Status has a wheel constantly turning and is constantly outputting:

4c8c5808 Building [Done]

84f654df Building [Done]
Over and over again.

VS Code Version 1.60.0

JDK 16.0.2

Only installed the Microsoft Java Extensions.

答: To correct this behavior, you will need to turn the Visual Studio Code auto-save feature. You can find this setting under File > AutoSave.</p>

Body:
I have been using VS Code with Java for a few months learning the basics. I am not able to update the app myself it is controlled by the company I work for.

Last Friday the IDE seemed to be trying to compile/build on every single key stroke. If I were to simply type something like:

int x;

this will generate a Problem on:

i is not defined

in is not defined

int declared with no variable name.

declaration missing ';'

These 'problems' can take minutes for VS Code to catch up on and realise that statement is valid. There is no intellisense possible either with this so typing 'x.' anything raises more errors. I have searched for this issue and tried turning off auto save, build on save, java.autobuilder to off and the issues remain.

The Java Build Status has a wheel constantly turning and is constantly outputting:

4c8c5808 Building [Done]

84f654df Building [Done]
Over and over again.

VS Code Version 1.60.0

JDK 16.0.2

Only installed the Microsoft Java Extensions.


问:
Whitespace at top and within body div tags
Can someone please just tell me what my sorry, stupid eyes are missing?

Whitespace appears at the top of my browser window, and between two div tag containers (all browsers.)

p, body, html, every div, all margin:0px;

Gracias.

答: The margin top of your menu-container div has margin-top: 20px; I saw that using FireBug.


问:
How to access inner array in out side of nestes for loop
I want make code in which we have to add inputs and it show output at very after all inputs are performed.
But i don't know how can i access the contents of variable in for loop in outer side.

My code is given below

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

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][]A =new int[T][N];

        //I know here No issue with T but how can i acces N and C?

        //here code to show output of given inputs.....
....
..

    }
}

</code>```

Ex:-

```<code>Input:--

2 //test cases

3  //items

1  2  3  //costs

4  //items

1 2 3 4  //costs

Ouput:---perfectly as in input.
</code>```

答:
If I right understand what do you want, you should declare N and C at procedure begin:</p>
```<code>import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        int N=0;
        int C=0;
        for(int i=0;i<T;i++)
        {
            N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][][]A =new int[T][N][C];

        //Now here T,N and C are accessible

        //here code to show output of given inputs.....
....
..

    }
}
</code>```

Body:
I want make code in which we have to add inputs and it show output at very after all inputs are performed.
But i don't know how can i access the contents of variable in for loop in outer side.

My code is given below

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        for(int i=0;i<T;i++)
        {
            int N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                int C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][]A =new int[T][N];

        //I know here No issue with T but how can i acces N and C?

        //here code to show output of given inputs.....
....
..

    }
}

Ex:-

Input:--

2 //test cases

3  //items

1  2  3  //costs

4  //items

1 2 3 4  //costs

Ouput:---perfectly as in input.

Body:
If I right understand what do you want, you should declare N and C at procedure begin:

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();   //How many  Input case?
        int N=0;
        int C=0;
        for(int i=0;i<T;i++)
        {
            N=sc.nextInt();        //How many items in each cases?
            for(int j=0;j<N;j++)
            {
                C=sc.nextInt();   //How much cost of each items?
            }
        }
        int [][][]A =new int[T][N][C];

        //Now here T,N and C are accessible

        //here code to show output of given inputs.....
....
..

    }
}