问:
Get respectives values from Django annotate method
I have the following query:

```<code>result = data.values('collaborator').annotate(amount=Count('cc'))
top = result.order_by('-amount')[:3]
</code>```

This one, get the collaborator field from data, data is a Django Queryset, i am trying to make like a GROUP BY query, and it's functional, but when i call the .values() method on the top variable, it's returning all the models instances as dicts into a queryset, i need the annotate method result as a list of dicts:
The following is the top variable content on shell:

```<code><QuerySet [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]>
</code>```

But when i make list(top.values()) i get the following result:

```<code>[{'name': 'Alyse Caffin', 'cc': '1043346592', 'location': 'Wu’an', 'gender': 'MASCULINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '6', 'status': 'ESPERADO', 'amount': 1}, {'name': 'Barthel Hanlin', 'cc': '1043238706', 'location': 'General Santos', 'gender': 'MASCULINO', 'voting_place': 'Colegio San José – Compañía de Jesús Barranquilla', 'table_number': '10', 'status': 'PENDIENTE', 'amount': 1}, {'name': 'Harv Gertz', 'cc': '1043550513', 'location': 'Makueni', 'gender': 'FEMENINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '7', 'status': 'ESPERADO', 'amount': 1}]
</code>```

I just want the result to be like:

```<code>[{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]
</code>```

答:
there is something wrong, maybe a typo (also it seems you do not show the full query... something like data=yourmodel.objects.filter... is missing before):

The output of list(top.values()) returns a completely different model's fields then what you post as top Queryset- are you sure you really did:

```<code>result = data.values('collaborator').annotate(amount=Count('cc'))
top = result.order_by('-amount')[:3]
list(top.values())
</code>```

because it should deliver what you expect (provided that data is a Queryset)

Body:
I have the following query:

result = data.values('collaborator').annotate(amount=Count('cc'))
top = result.order_by('-amount')[:3]

This one, get the collaborator field from data, data is a Django Queryset, i am trying to make like a GROUP BY query, and it's functional, but when i call the .values() method on the top variable, it's returning all the models instances as dicts into a queryset, i need the annotate method result as a list of dicts:
The following is the top variable content on shell:

<QuerySet [{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]>

But when i make list(top.values()) i get the following result:

[{'name': 'Alyse Caffin', 'cc': '1043346592', 'location': 'Wu’an', 'gender': 'MASCULINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '6', 'status': 'ESPERADO', 'amount': 1}, {'name': 'Barthel Hanlin', 'cc': '1043238706', 'location': 'General Santos', 'gender': 'MASCULINO', 'voting_place': 'Colegio San José – Compañía de Jesús Barranquilla', 'table_number': '10', 'status': 'PENDIENTE', 'amount': 1}, {'name': 'Harv Gertz', 'cc': '1043550513', 'location': 'Makueni', 'gender': 'FEMENINO', 'voting_place': 'Corporación Educativa American School Barranquilla', 'table_number': '7', 'status': 'ESPERADO', 'amount': 1}]

I just want the result to be like:

[{'collaborator': '1092788966', 'amount': 20}, {'collaborator': '1083692812', 'amount': 20}, {'collaborator': '1083572767', 'amount': 20}]

Body:
there is something wrong, maybe a typo (also it seems you do not show the full query... something like data=yourmodel.objects.filter... is missing before):

The output of list(top.values()) returns a completely different model's fields then what you post as top Queryset- are you sure you really did:

result = data.values('collaborator').annotate(amount=Count('cc'))
top = result.order_by('-amount')[:3]
list(top.values())

because it should deliver what you expect (provided that data is a Queryset)


来源: stackexchange

问:
not losing state when refresh webpage
I made a Simple WebApp in React.js, that can add food to a cart and see it or finally order it.
when I add food, my cart updates and can see data but when I refresh the page, data will be gone
how can save data and when I refresh the page still can see it.</p>

答: If you need to save the state of your shopping cart somewhere you can do that server side. You can store it in Session state. When you refresh you refill the page from Session state.</p>

ContentLicense: CC BY-SA 4.0

Title: not losing state when refresh webpage


问:
Displaying large amount of data
I am working on a mobile application using Bluetooth sensor. My goal is to visualize Bluetooth data on graph. I have 3 different pages on my mobile application:

First page having 3 channels (you can imagine it as as 1 graph and 3 signals, thus 3 curves)

Second page having 8 channels

Third page having 3 channels

The moment I have many channels (like at the second page, 8 channels) the display is slowing down. It is so slow that I cannot even switch between pages. Like if I am clicking but nothing is happening, totally freezed.

I am guessing it is because of the display library that I am using. For those who already have experienced the same issue, any suggestions about real-time charts in Flutter? I have already tested Syncfusion and it is indeed freezing.

Thank you very much.

答:
We tried to replicate the reported scenario by creating the chart based on the shared information i.e., in first page and third page, we have a chart with 3 series, in the second page we have a chart with 8 series. And updated the charts for every 300ms, and we ran the application more than an hour, unfortunately the app didn’t get freeze. We have tried by adding the data to the chart and not removed any data in the above case.

For better performance we suggest using the fast line series and for updating the data source use the updateDataSource and not use set state. The set state will render the re-render the chart, the updateDataSource method will skip old data points processing, unnecessary bounds calculation, etc. For more information on these, find the user guide below.

https://help.syncfusion.com/flutter/cartesian-charts/chart-types/fast-line-chart https://help.syncfusion.com/flutter/cartesian-charts/methods#updatedatasource

We have also attached the sample below which we have used for testing,

Sample link https://www.syncfusion.com/downloads/support/directtrac/general/ze/stackoverflow1887344518.zip

Also, if you are using large data set, we suggest using the on-demand loading feature. For more information this, find the user guide and sample below. If this suits to your requirement, you can make use of this.

UG: https://help.syncfusion.com/flutter/cartesian-charts/on-demand-loading
Demo: https://flutter.syncfusion.com/#/cartesian-charts/infinite-scrolling

Title: Displaying large amount of data


问:
CSS gaps between image links for no reason
I've been trying to get this horizontal navigation sorted for the past few hours now and nothing is working. I've tried reset.css stylesheets, *{padding: 0; margin: 0) etc. and I still have gaps inbetween my image links.

You see, the navigation is made up of an unordered list of image links displayed inline, but there are gaps in between each image, left, right, top and bottom and I can't see why. It's the same in all browsers.

Here is a link to the page, and so source: Beansheaf Temporary

Link to css: http://pentathlongb-yorkshire.co.uk/tomsmith/Beansheaf/styles/fund2.css

The rest of the site is obviously still not done, it's just the navigation I'm worried about right now.

答:
the gap below images links is due to the image being aligned with base text line by default, you can solve it simply declaring

```<code>li img {
    vertical-align:bottom;
}
</code>```

magic!

ContentLicense: CC BY-SA 3.0

Body:
the gap below images links is due to the image being aligned with base text line by default, you can solve it simply declaring

li img {
    vertical-align:bottom;
}

magic!


问:
read fucntion in C uint_8 and char array buffer differences
in some code seen online, i saw that in read function in C, someone uses a uint8_t array for buffer insted of a char array buffer.
what are the differences?
thanks

答:
The C standard allows char to be signed or unsigned. It also allows it to be more than eight bits.

uint8_t, if it is defined, is unsigned and eight bits. This allows programmers to be completely sure of the type that will be used. In particular, signed char types sometimes cause problems with bitwise and shift operations, due to how these operations are defined (or are not defined) when negative values are involved.


问:
How to create an interactive pie chart with javascript, html, css?
How to create a pie chart widget where the user can change the distribution of the pie chart by dragging the borders of the wedges?

Is there a package with such a widget in react?

答: Personally i have never seen a pie with draggable border to change the distribution. I have worked with ApexCharts (https://apexcharts.com/react-chart-demos/pie-charts/update-donut/). Each part of the pie is basicaly a number so, you can create for example a slider for each part and dynamicly update the part of the chart.


问:
How to include a css file using R code in the yaml header?
How to include a css file using R code in the yaml header?

I have the following directory tree

```<code>./
./include/
./include/css/
./include/css/style.css
./docs
./docs/report/
./docs/report/report.Rmd
</code>```

and I have tried

```<code>css: "`r library(here); here('include/css/style.css')`"
</code>```

but it didn't work and gives the following error

File r here::here('include/css/style.css') not found in resource
path Error: pandoc document conversion failed with error 99

答:
I am new, so can't comment on your post yet.

I use this example for my bookdown documents:

https://bookdown.org/yihui/rmarkdown-cookbook/html-css.html

This works well, but I put all my css files on the same directory along with markdown and yml files.

If you want to use your directory structure, maybe a relative path might work.
Here is an example I found:

https://github.com/fletcher/MultiMarkdown/issues/47

Good luck!

Body:
How to include a css file using R code in the yaml header?

I have the following directory tree

./
./include/
./include/css/
./include/css/style.css
./docs
./docs/report/
./docs/report/report.Rmd

and I have tried

css: "`r library(here); here('include/css/style.css')`"

but it didn't work and gives the following error

File r here::here('include/css/style.css') not found in resource
path Error: pandoc document conversion failed with error 99


问:
change Dom elements to be invisible
I need to make the variables "answer" and "submit" invisible and I tried to do that on lines 21-22 in the javascript file but it doesn't work
how can I make them invisible ?

javascript and html code:

let question = document.getElementById("question");
let answer = document.getElementById("answer");
let submit = document.getElementById("submit");

//create an array of questions
let questions = ["What type of file do you need to open javascript file ?", "question 2", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10"];

//create an array of answers
let answers = ["js", "answer 2", "answer 3", "answer 4", "answer 5", "answer 6", "answer 7", "answer 8", "answer 9", "answer 10"];

// set the question varible to the first question in the array
let questionNumber = 0;
question.innerText = questions[questionNumber];

let points = 0;
let counter = 0;

submit.addEventListener("click", function(){
    if(counter == questions.length - 1){
        question.innerText = "You got " + points + " out of " + questions.length * 10 + " points";
        answer.style.display = "none";
        submit.style.display = "none";
    }
    answer = document.getElementById("answer").value;
    if(answer == answers[questionNumber]){
        points +=10;
        console.log("correct");
    }
    else{
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        if(points < 10){
            points = 0;
        }
        else{
            points -= 10;
        }
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    counter++;
    question.innerText = questions[questionNumber];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <span id="question"></span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
  </div></code>```

答: After answer = document.getElementById("answer").value; you have to set the display to none, or you can use visibility to hidden

Title: change Dom elements to be invisible

Body:
I need to make the variables "answer" and "submit" invisible and I tried to do that on lines 21-22 in the javascript file but it doesn't work
how can I make them invisible ?

javascript and html code:

let question = document.getElementById("question");
let answer = document.getElementById("answer");
let submit = document.getElementById("submit");

//create an array of questions
let questions = ["What type of file do you need to open javascript file ?", "question 2", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10"];

//create an array of answers
let answers = ["js", "answer 2", "answer 3", "answer 4", "answer 5", "answer 6", "answer 7", "answer 8", "answer 9", "answer 10"];

// set the question varible to the first question in the array
let questionNumber = 0;
question.innerText = questions[questionNumber];

let points = 0;
let counter = 0;

submit.addEventListener("click", function(){
    if(counter == questions.length - 1){
        question.innerText = "You got " + points + " out of " + questions.length * 10 + " points";
        answer.style.display = "none";
        submit.style.display = "none";
    }
    answer = document.getElementById("answer").value;
    if(answer == answers[questionNumber]){
        points +=10;
        console.log("correct");
    }
    else{
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        if(points < 10){
            points = 0;
        }
        else{
            points -= 10;
        }
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    counter++;
    question.innerText = questions[questionNumber];
});

      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">

    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>


问:
Python PyQtGraph - how to use setTicks?
I want to display xticks only at the locations of data points (so the xticks == wavelengths). How can I do this?

Here is my code:

```<code>from PyQt6.QtWidgets import QApplication
import pyqtgraph as pg

app = QApplication([])

wavelengths = [610, 680, 730, 760, 810, 860]
data = [239.23, 233.81, 187.27, 176.41, 172.35, 173.78]

pw = pg.plot(wavelengths, data, symbol="o")
pw.getPlotItem().getAxis('bottom').setTicks([wavelengths])

app.exec()
</code>```

I tried using AxisItem.setTicks(), but it results in an error:

```<code>    for val, strn in level:
TypeError: cannot unpack non-iterable int object
Traceback (most recent call last):
  File "/home/jure/.local/share/virtualenvs/serial-plotting-gui-dWOiQ7Th/lib/python3.10/site-packages/pyqtgraph/graphicsItems/AxisItem.py", line 608, in paint
    specs = self.generateDrawSpecs(painter)
  File "/home/jure/.local/share/virtualenvs/serial-plotting-gui-dWOiQ7Th/lib/python3.10/site-packages/pyqtgraph/graphicsItems/AxisItem.py", line 936, in generateDrawSpecs
</code>```

P.S. I also tried this SO answer, but it doesn't work for me

答:
It's always bit tricky with ticks in pyqtgraph. It works with tick spacing between two ticks on the axis. On top of it, it defines levels of MajorTick, MinorTicks and so on. With setTicks You have to specify list of levels (we have only MajorTicks) and each level with list of (tick value, "tick string").

So in order for Your example to work, You have to use such a list as a parameter for setTicks method.

Here is Your modified code:

```<code>from PyQt6.QtWidgets import QApplication
import pyqtgraph as pg

app = QApplication([])

wavelengths = [610, 680, 730, 760, 810, 860]
data = [239.23, 233.81, 187.27, 176.41, 172.35, 173.78]

pw = pg.plot(wavelengths, data, symbol="o")

pw.getPlotItem().getAxis('bottom').setTicks([[(wavelength, str(wavelength)) for wavelength in wavelengths]])

app.exec()
</code>```

Title: Python PyQtGraph - how to use setTicks?

Body:
I want to display xticks only at the locations of data points (so the xticks == wavelengths). How can I do this?

Here is my code:

from PyQt6.QtWidgets import QApplication
import pyqtgraph as pg

app = QApplication([])

wavelengths = [610, 680, 730, 760, 810, 860]
data = [239.23, 233.81, 187.27, 176.41, 172.35, 173.78]

pw = pg.plot(wavelengths, data, symbol="o")
pw.getPlotItem().getAxis('bottom').setTicks([wavelengths])

app.exec()

I tried using AxisItem.setTicks(), but it results in an error:

    for val, strn in level:
TypeError: cannot unpack non-iterable int object
Traceback (most recent call last):
  File "/home/jure/.local/share/virtualenvs/serial-plotting-gui-dWOiQ7Th/lib/python3.10/site-packages/pyqtgraph/graphicsItems/AxisItem.py", line 608, in paint
    specs = self.generateDrawSpecs(painter)
  File "/home/jure/.local/share/virtualenvs/serial-plotting-gui-dWOiQ7Th/lib/python3.10/site-packages/pyqtgraph/graphicsItems/AxisItem.py", line 936, in generateDrawSpecs

P.S. I also tried this SO answer, but it doesn't work for me

Body:
It's always bit tricky with ticks in pyqtgraph. It works with tick spacing between two ticks on the axis. On top of it, it defines levels of MajorTick, MinorTicks and so on. With setTicks You have to specify list of levels (we have only MajorTicks) and each level with list of (tick value, "tick string").

So in order for Your example to work, You have to use such a list as a parameter for setTicks method.

Here is Your modified code:

from PyQt6.QtWidgets import QApplication
import pyqtgraph as pg

app = QApplication([])

wavelengths = [610, 680, 730, 760, 810, 860]
data = [239.23, 233.81, 187.27, 176.41, 172.35, 173.78]

pw = pg.plot(wavelengths, data, symbol="o")

pw.getPlotItem().getAxis('bottom').setTicks([[(wavelength, str(wavelength)) for wavelength in wavelengths]])

app.exec()


问:
Obtain the password of ASPNET account
Is there any way to obtain (not change) the password of the ASPNET account on a Windows Server 2003 server?  I need to snyc my workstation's ASPNET account password with the one on the server I am trying to connect to.

I am trying to trouble shoot the following issue with my ASP.NET application.

答: The only way to obtain an NT service account password is to ask someone who knows.  If the person who ought to know doesn't then that same person ought to be able to reset it for you.  In other words you should probably talk to your network administrator.</p>

OwnerDisplayName: Michael Kniskern

ContentLicense: CC BY-SA 2.5

Title: Obtain the password of ASPNET account

OwnerDisplayName: Andrew Hare


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答:
Please dear God!  I can't believe that none of the answers so far have pointed out the massive SQL injection vector in the original code; to be honest it's better for the safety of your database that the if block isn't working as you originally intended!

You must sanatize, escape and clean up all data that comes from the user; failing to do this will leave your database wide open for SQL injection attacks.  If this is new to you then I suggest you read up on some articles and possibly invest in a book on the subject.

PHP includes a function which will sanatize values for you called mysql_real_escape_string(), you should modify your SQL statement to read:

```<code>$clean_id = mysql_real_escape_string($id);
$clean_url = mysql_real_escape_string($url);

$insert  = "INSERT INTO tab (id,url) VALUES ('$clean_id','$clean_url')";
</code>```

To avoid having to remember such things I suggest you look into database abstraction layers which will handle this for you; MDB2 is a popular package although there are plenty of others out there such as doctrine.

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

Body:
Please dear God!  I can't believe that none of the answers so far have pointed out the massive SQL injection vector in the original code; to be honest it's better for the safety of your database that the if block isn't working as you originally intended!

You must sanatize, escape and clean up all data that comes from the user; failing to do this will leave your database wide open for SQL injection attacks.  If this is new to you then I suggest you read up on some articles and possibly invest in a book on the subject.

PHP includes a function which will sanatize values for you called mysql_real_escape_string(), you should modify your SQL statement to read:

$clean_id = mysql_real_escape_string($id);
$clean_url = mysql_real_escape_string($url);

$insert  = "INSERT INTO tab (id,url) VALUES ('$clean_id','$clean_url')";

To avoid having to remember such things I suggest you look into database abstraction layers which will handle this for you; MDB2 is a popular package although there are plenty of others out there such as doctrine.


答:
The element selection variables should be set as const because the elements don't change only their content does. This would prevent mistakes as you had in your code, which is stated in the next paragraph.

In event listener function I changed the answer variable to answerValue because you cant change a const set to the element. So you need to store that data into a different name. In your code you were trying to call the style property on a value and not the element. This is because you changed the answer from the element to the value on each call of the function.

const question = document.getElementById("question");
const answer = document.getElementById("answer");
const submit = document.getElementById("submit");

//create an array of questions
let questions = ["What type of file do you need to open javascript file ?", "question 2", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10"];

//create an array of answers
let answers = ["js", "answer 2", "answer 3", "answer 4", "answer 5", "answer 6", "answer 7", "answer 8", "answer 9", "answer 10"];

// set the question varible to the first question in the array
let questionNumber = 0;
question.innerText = questions[questionNumber];

let points = 0;
let counter = 0;

submit.addEventListener("click", function () {
    if (counter == questions.length - 1) {
        question.innerText = "You got " + points + " out of " + questions.length * 10 + " points";
        answer.style.display = "none";
        submit.style.display = "none";
    }
    // here I changed it to call the answer element and get its value and store it into "answerValue" instead of replacing the answer element.
    const answerValue = answer.value;
    if (answerValue == answers[questionNumber]) {
        points += 10;
        console.log("correct");
    }
    else {
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        if (points < 10) {
            points = 0;
        }
        else {
            points -= 10;
        }
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    counter++;
    question.innerText = questions[questionNumber];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <span id="question"></span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
  </div></code>```

Title: change Dom elements to be invisible

Body:
The element selection variables should be set as const because the elements don't change only their content does. This would prevent mistakes as you had in your code, which is stated in the next paragraph.

In event listener function I changed the answer variable to answerValue because you cant change a const set to the element. So you need to store that data into a different name. In your code you were trying to call the style property on a value and not the element. This is because you changed the answer from the element to the value on each call of the function.

const question = document.getElementById("question");
const answer = document.getElementById("answer");
const submit = document.getElementById("submit");

//create an array of questions
let questions = ["What type of file do you need to open javascript file ?", "question 2", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10"];

//create an array of answers
let answers = ["js", "answer 2", "answer 3", "answer 4", "answer 5", "answer 6", "answer 7", "answer 8", "answer 9", "answer 10"];

// set the question varible to the first question in the array
let questionNumber = 0;
question.innerText = questions[questionNumber];

let points = 0;
let counter = 0;

submit.addEventListener("click", function () {
    if (counter == questions.length - 1) {
        question.innerText = "You got " + points + " out of " + questions.length * 10 + " points";
        answer.style.display = "none";
        submit.style.display = "none";
    }
    // here I changed it to call the answer element and get its value and store it into "answerValue" instead of replacing the answer element.
    const answerValue = answer.value;
    if (answerValue == answers[questionNumber]) {
        points += 10;
        console.log("correct");
    }
    else {
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        if (points < 10) {
            points = 0;
        }
        else {
            points -= 10;
        }
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    counter++;
    question.innerText = questions[questionNumber];
});

<div class="container">
    <span id="question"></span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
  </div>


问:
Trying to make a simple MUD like game but having issues with nested loops
So I'm a total noob so far and taking a course in JavaScript. I'm supposed to create a simple game with various choices using if, switch and while.

So I got my game going, but it won't recognize user input at some times, and I think it has to do with the way I've nested loops. The following code is inside first a switch and then a while loop. :

```<code>answer = prompt ("Välj SLÅSS eller PRATA?").toLowerCase();

if (answer ==="slåss")
{
  console.log("Du närmar dig modigt besten");
  alt = prompt("Använder du magi eller ditt vapen?").toLowerCase;

 if (alt ==="magi") // this wont work, if I type in magi the code below won't trigger
 {
  console.log("Du kastar en eldboll som visar sig vara supereffektiv. Trollet dör.");
  console.log ("Skattkistan var bakom trollet! Grattis! Du klarade spelet.");
  skog=false;
  break;

}

 if(alt==="vapen") // this wont work, if I type in "vapen" the code below won't trigger
 {
  console.log("Du har inte en chans mot trollets styrka i närkamp och dör. Spelet är över.");
  skog=false;
  break;

}

 else
 {
  console.log("Ange ett giltigt alternativ");

 }
}
</code>```

I also have an issue where I want a if statement to check if a earlier declared variable is true while also seeing if the user entered string is correct. I've writte this as follows :

```<code>else if (stark===true && answer === "prata")
</code>```

//here I want you to loose if you choose this option and picked "prata" and "stark" earlier at the start.

答:
you're missing () after toLowerCase:

```<code>  alt = prompt("Använder du magi eller ditt vapen?").toLowerCase;
</code>```

Your code was setting the variable to (lots of terminology here, sorry) a reference to the function toLowerCase instead of calling the function and getting its result.

Your second part of the question, about logical flow, seems like it can be solved by restructuring the code. There's an idea of "variable scoping" that will be helpful to you here. Since this is homework, I won't rewrite it for you, but see about declaring those variables as global with var at the beginning (as a first step for a beginner--I recognize that global variables are not great programming practice).

Body:
So I'm a total noob so far and taking a course in JavaScript. I'm supposed to create a simple game with various choices using if, switch and while.

So I got my game going, but it won't recognize user input at some times, and I think it has to do with the way I've nested loops. The following code is inside first a switch and then a while loop. :

answer = prompt ("Välj SLÅSS eller PRATA?").toLowerCase();

if (answer ==="slåss")
{
  console.log("Du närmar dig modigt besten");
  alt = prompt("Använder du magi eller ditt vapen?").toLowerCase;

 if (alt ==="magi") // this wont work, if I type in magi the code below won't trigger
 {
  console.log("Du kastar en eldboll som visar sig vara supereffektiv. Trollet dör.");
  console.log ("Skattkistan var bakom trollet! Grattis! Du klarade spelet.");
  skog=false;
  break;

}

 if(alt==="vapen") // this wont work, if I type in "vapen" the code below won't trigger
 {
  console.log("Du har inte en chans mot trollets styrka i närkamp och dör. Spelet är över.");
  skog=false;
  break;

}

 else
 {
  console.log("Ange ett giltigt alternativ");

 }
}

I also have an issue where I want a if statement to check if a earlier declared variable is true while also seeing if the user entered string is correct. I've writte this as follows :

else if (stark===true && answer === "prata")

//here I want you to loose if you choose this option and picked "prata" and "stark" earlier at the start.

Body:
you're missing () after toLowerCase:

  alt = prompt("Använder du magi eller ditt vapen?").toLowerCase;

Your code was setting the variable to (lots of terminology here, sorry) a reference to the function toLowerCase instead of calling the function and getting its result.

Your second part of the question, about logical flow, seems like it can be solved by restructuring the code. There's an idea of "variable scoping" that will be helpful to you here. Since this is homework, I won't rewrite it for you, but see about declaring those variables as global with var at the beginning (as a first step for a beginner--I recognize that global variables are not great programming practice).


问:
Is there a function (pandas or otherwise) to interpolate quarterly data to monthly while matching averages within each quarter?
I have a dataframe with quarterly forecasts that I would like to interpolate to monthly, but with a few caveats: The monthly data in each quarter should average to the quarterly forecast, and the monthly data should trend towards the next quarterly forecast. We currently use an old linear excel macro to do this, but I'm trying to automate workflows in python. If it is possible to do with a cubic spline instead of linearly that would be preferable?

As an example of the forecast vs interpolated data:

```<code># Example
df = pd.DataFrame({
    "Date": ["2019-01-01","2019-02-01","2019-03-01","2019-04-01","2019-05-01","2019-06-01","2019-07-01","2019-08-01","2019-09-01","2019-10-01","2019-11-01","2019-12-01"],
     "Forecast": [0.8,np.nan,np.nan,1.87,np.nan,np.nan,0.07,np.nan,np.nan,-0.73,np.nan,np.nan],
     "Interpolated":[0.11,0.8,1.49,1.97,2.04,1.58,0.8,0,-0.57,-0.83,-0.76,-0.61]
})
</code>```

And verifying that the average within each quarter does approximately match the quarterly forecast

```<code>df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df['Interpolated'].resample('Q').mean()
</code>```

A regular cubic spline gets the shaping, but I don't believe that it matches the average within each quarter - are there any obvious functions out there that I've missed? Appreciate any and all help you can give. The date that the forecast data can be on is flexible - I just put in the first month of the quarter for the purposes of this example.

答:
Welcome to Stack Overflow. Nice first question with reproducible example!

This is not an answer, but a long comment.

Since we have one value and need to keep the average, you can't do much.
You can have like two very high values, and 1 extremely low to match the average.
I would like to have them linear with the second value identical to the forecast - that is the easiest, too.
Basically, I would do something that fits the purpose of the data. Do you need them to just look beautiful in chart? Pick something with nice curves. Do you need to analyze them later somehow statistically? Do something that resamples the data series' behaviour.

That being said, creating your own interpolation function would be an interesting journey, but it is not an easy task.
It requires some mathematics, like constructing an approximation from piecewise polynomials, splines, etc.. See more here (archived) and in Ding et al. (2007 - doi:10.1016/j.jmaa.2006.02.051)

Body:
I have a dataframe with quarterly forecasts that I would like to interpolate to monthly, but with a few caveats: The monthly data in each quarter should average to the quarterly forecast, and the monthly data should trend towards the next quarterly forecast. We currently use an old linear excel macro to do this, but I'm trying to automate workflows in python. If it is possible to do with a cubic spline instead of linearly that would be preferable?

As an example of the forecast vs interpolated data:

# Example
df = pd.DataFrame({
    "Date": ["2019-01-01","2019-02-01","2019-03-01","2019-04-01","2019-05-01","2019-06-01","2019-07-01","2019-08-01","2019-09-01","2019-10-01","2019-11-01","2019-12-01"],
     "Forecast": [0.8,np.nan,np.nan,1.87,np.nan,np.nan,0.07,np.nan,np.nan,-0.73,np.nan,np.nan],
     "Interpolated":[0.11,0.8,1.49,1.97,2.04,1.58,0.8,0,-0.57,-0.83,-0.76,-0.61]
})

And verifying that the average within each quarter does approximately match the quarterly forecast

df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df['Interpolated'].resample('Q').mean()

A regular cubic spline gets the shaping, but I don't believe that it matches the average within each quarter - are there any obvious functions out there that I've missed? Appreciate any and all help you can give. The date that the forecast data can be on is flexible - I just put in the first month of the quarter for the purposes of this example.


答:
You have different solutions to store your data:

LocalStorage with no expiration time

SessionStorage is cleared when the page session ends

Redux is a predictable state container

React Context is designed to share data that can be considered globally for a tree of React components

Title: not losing state when refresh webpage

Body:
I made a Simple WebApp in React.js, that can add food to a cart and see it or finally order it.
when I add food, my cart updates and can see data but when I refresh the page, data will be gone
how can save data and when I refresh the page still can see it.


问:
How to work with RFID reader/writer in Java
I bought a USB RFID reader/writer to develop an attendance application. Along with the device they given VB example to read/write RFID tags. But I want to do this in Java. Is there any way to start programming which read/write the RFID tags.

And one more thing I want to know, does RFID reader continuously read the RFID tags when ever they come into reader range? If it is, how to get the tag data?

答:
I bought a USB RFID reader/writer to develop an attendance application. Along with the device they given VB example to read/write RFID tags. But i want to do this in java. Is there any way to start programing which read/write the RFID tags.

I would suggest getting started by googling for java USB APIs. I stumbled on this one: http://jusb.sourceforge.net/ and it doesn't look too bad.

If the reader is actually run through a serial converter (look it up in the manual) you could use rxtx library to connect to this device.

And one more thing i want to know, does RFID reader continuously read the RFID tags when ever they come into reader range? If it is, how to get the tag data?

Once you have the USB-Port managed, you read its input stream and get a stream of bytes. The manufacturer of the reader should have a description on how to parse these bytes into actual tagcodes. Or just re-engineer the VB code.


问:
Split CSV file into 2 lists depending on value
I have a UTF-8 encoded CSV file like this..

```<code>"id","name","type","price"
"23","item1","t-shirt","37"
"56","item66","jumper","3"
"366","item7","jumper","55"
"745","item 9","t-shirt","45"
"3245","item 12","t-shirt","67"
"654","item 88","jumper","66"
"2","item 99","jumper","77"
</code>```

And using python I am trying to split it into 2 lists based on type to give me an output like this..

```<code>File 1
id   | name    | type    | price
--------------------------------
23   | item1   | t-shirt | 37
745  | item 9  | t-shirt | 45
3245 | item 12 | t-shirt | 67

File 2
id   | name    | type    | price
--------------------------------
56   | item66  | jumper  | 3
366  | item7   | jumper  | 55
654  | item 88 | jumper  | 66
2    | item 99 | jumper  | 77
</code>```

I have this so far

```<code>list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:

    csv_reader = csv.reader(csv_file, delimiter='\t')

        for row in csv_reader:

            if row['type'] == 't-shirt':
                list1.append(row)
            elif row['type'] == 't-shirt':
                list2.append(row)

</code>```

But this is giving me the following error...

```<code>TypeError: list indices must be integers or slices, not str
</code>```

Where am I going wrong?

答:
Another alternative is to use pandas.</p>
```<code>def sort_by_type(file):
    import pandas as pd
    table = pd.read_csv(file)
    File_1 = table[table["type"]=="jumper"]
    File_2 = table[table["type"]=="t-shirt"]
    return File_1, File_2

File_1, File_2 = sort_by_type(file)
File_1

    id  name    type    price
1   56  item66  jumper  3
2   366 item7   jumper  55
5   654 item88  jumper  66
6   2   item99  jumper  77

File_2

    id      name    type    price
 0  23      item1   t-shirt 37
 3  745     item 9  t-shirt 45
 4  3245    item 12 t-shirt 67
</code>```

Body:
I have a UTF-8 encoded CSV file like this..

"id","name","type","price"
"23","item1","t-shirt","37"
"56","item66","jumper","3"
"366","item7","jumper","55"
"745","item 9","t-shirt","45"
"3245","item 12","t-shirt","67"
"654","item 88","jumper","66"
"2","item 99","jumper","77"

And using python I am trying to split it into 2 lists based on type to give me an output like this..

File 1
id   | name    | type    | price
--------------------------------
23   | item1   | t-shirt | 37
745  | item 9  | t-shirt | 45
3245 | item 12 | t-shirt | 67

File 2
id   | name    | type    | price
--------------------------------
56   | item66  | jumper  | 3
366  | item7   | jumper  | 55
654  | item 88 | jumper  | 66
2    | item 99 | jumper  | 77

I have this so far

list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:

    csv_reader = csv.reader(csv_file, delimiter='\t')

        for row in csv_reader:

            if row['type'] == 't-shirt':
                list1.append(row)
            elif row['type'] == 't-shirt':
                list2.append(row)

But this is giving me the following error...

TypeError: list indices must be integers or slices, not str

Where am I going wrong?

Body:
Another alternative is to use pandas.

def sort_by_type(file):
    import pandas as pd
    table = pd.read_csv(file)
    File_1 = table[table["type"]=="jumper"]
    File_2 = table[table["type"]=="t-shirt"]
    return File_1, File_2

File_1, File_2 = sort_by_type(file)
File_1

    id  name    type    price
1   56  item66  jumper  3
2   366 item7   jumper  55
5   654 item88  jumper  66
6   2   item99  jumper  77

File_2

    id      name    type    price
 0  23      item1   t-shirt 37
 3  745     item 9  t-shirt 45
 4  3245    item 12 t-shirt 67


问:
Positioning an image on top of text
How can I position an image on top text. Like in the image given

答:
You can also use the position css property for this, you can wrap these two tags with a div and use the css flex methods.

CSS Flex Example:

```<code><div style="display:flex; flex-direction:column"><img src="IMG_URL" alt="..." style="align-self:flex-end"><p>Dex Activity<p/></div>
</code>```

Title: Positioning an image on top of text

Body:
You can also use the position css property for this, you can wrap these two tags with a div and use the css flex methods.

CSS Flex Example:

<div style="display:flex; flex-direction:column"><img src="IMG_URL" alt="..." style="align-self:flex-end"><p>Dex Activity<p/></div>


问:
How to get a native UITableView with UITableViewCellStyleSubtitle in React Native?
I want to build something like this with React Native:

(image source https://developer.apple.com/design/human-interface-guidelines/ios/views/tables/)
How can this be done in React Native? Do I need 3rd party libraries for that or is it possible with the "core" React Native?

答:
React Native bridges to UIView and UIScrollView but not UITableView. The reason for this is that

UITableView API is not well suited for the asynchronous nature of ReactNative, and the resulting code was pretty gross

https://github.com/facebook/react-native/issues/332#issuecomment-86991307

The only solutions are to

use a component that wraps native UITableView (e.g. react-native-tableview)

use a component that mimics the look-and-feel of UITableView (e.g. [react-native-tableview-simple])(https://github.com/Purii/react-native-tableview-simple)

depart from UITableView and implement your own visual design (using pure RN FlatList or e.g. Nativebase FlatList)

ask/help RN to provide an official component for bridging to native iOS UITableView (and Android ListView).

The first is of course great in terms of UX but is not cross-platform (also apparently no longer actively maintained). The second will make your app look dated when Apple inevitably evolves the native appearance in new versions of iOS. So personally I would shy away from either of those.


问:
Determining if a knight can pass through all cells in a 2d array - if so print board
I need an advice regarding this problem called "Knight Path".
Given an n*n board whose cells are initialized to 0, I need to determine, given an arbitrary Knight's position, if the knight can pass through every cell on the board exactly once, where every cell the Knight had visited will be marked as counter, counting from: 1 - n^2.
If a path is possible, I need to print the board. I need to print all the valid boards.
The knight, for those who do not know the rules for chess, can move either up or down one square vertically and over two squares horizontally OR up or down two squares vertically and over one square horizontally.

For example given a 5*5 board, starting at (0,0) the method should print:

```<code>{{1,16,11,6,21},
{10,5,20,15,12},
{17,2,13,22,7},
{4,9,24,19,14},
{25,18,3,8,23}};
</code>```

The above out put would be one of few, as there could be different other ways considering different initial positions.
I've written the below code but it doesn't print anything. I need to spot the logic flaws here so I can make it work.

```<code>public class KnightDemo {

    static int counter = 1;
    public static void KnightPath(int[][] b, int i, int j) {
        b[i][j] = counter;
        if (counter == b.length * b[0].length) {
            printMatrix(b);
            return;
        } else {
            counter++;

            if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
                KnightPath(b, i - 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j + 1) && b[i - 1][j + 1] == 0) {
                KnightPath(b, i - 2, j + 1);
            } else {
                return;
            }
            if (isValid(b, i - 1, j - 2) && b[i - 1][j - 2] == 0) {
                KnightPath(b, i - 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j - 1) && b[i - 2][j - 1] == 0) {
                KnightPath(b, i - 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 2, j - 1) && b[i + 2][j - 1] == 0) {
                KnightPath(b, i + 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 1, j - 2) && b[i + 1][j - 2] == 0) {
                KnightPath(b, i + 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i + 1, j + 2) && b[i + 1][j + 2] == 0) {
                KnightPath(b, i + 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i + 2, j + 1) && b[i + 2][j + 1] == 0) {
                KnightPath(b, i + 2, j + 1);
            } else {
                return;
            }

        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        if (i > a.length - 1 || i < 0 || j > a[0].length - 1 || j < 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                KnightPath(b, i, j);
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] rows: matrix) {
            StringBuilder buff = new StringBuilder();
            buff.append("[");
            for (int i = 0; i < rows.length; i++) {
                int value = rows[i];
                buff.append(value);
                if (i < rows.length - 1) {
                    buff.append(", ");
                }
            }
            buff.append("]");
            System.out.println(buff.toString());
        }
    }
}
</code>```

The output is

```<code>[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[21, 22, 23, 24, 25]
</code>```

答:
To solve for all paths, you need to reset the placed values of paths you've exhausted so that newer paths can access them.  Additionally, your counter should reflect how deep you've gone, so that if you back out to try another path, your counter should roll back, too.  I would recommend passing a counter as a parameter rather than using a static counter.  Also, if you want to try all valid possibilities, then you need to avoid those return statements whenever one possibility is deemed invalid.</p>
```<code>public static void KnightPath(int[][] b, int i, int j, int counter) {
    ...
        if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
            KnightPath(b, i - 1, j + 2, counter+1);
        }
    ...
    b[i][j] = 0;
}

public static void main(String[] args) {
    ...
            KnightPath(b, i, j, 1);
    ...
}
</code>```

Body:
I need an advice regarding this problem called "Knight Path".
Given an n*n board whose cells are initialized to 0, I need to determine, given an arbitrary Knight's position, if the knight can pass through every cell on the board exactly once, where every cell the Knight had visited will be marked as counter, counting from: 1 - n^2.
If a path is possible, I need to print the board. I need to print all the valid boards.
The knight, for those who do not know the rules for chess, can move either up or down one square vertically and over two squares horizontally OR up or down two squares vertically and over one square horizontally.

For example given a 5*5 board, starting at (0,0) the method should print:

{{1,16,11,6,21},
{10,5,20,15,12},
{17,2,13,22,7},
{4,9,24,19,14},
{25,18,3,8,23}};

The above out put would be one of few, as there could be different other ways considering different initial positions.
I've written the below code but it doesn't print anything. I need to spot the logic flaws here so I can make it work.

public class KnightDemo {

    static int counter = 1;
    public static void KnightPath(int[][] b, int i, int j) {
        b[i][j] = counter;
        if (counter == b.length * b[0].length) {
            printMatrix(b);
            return;
        } else {
            counter++;

            if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
                KnightPath(b, i - 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j + 1) && b[i - 1][j + 1] == 0) {
                KnightPath(b, i - 2, j + 1);
            } else {
                return;
            }
            if (isValid(b, i - 1, j - 2) && b[i - 1][j - 2] == 0) {
                KnightPath(b, i - 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j - 1) && b[i - 2][j - 1] == 0) {
                KnightPath(b, i - 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 2, j - 1) && b[i + 2][j - 1] == 0) {
                KnightPath(b, i + 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 1, j - 2) && b[i + 1][j - 2] == 0) {
                KnightPath(b, i + 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i + 1, j + 2) && b[i + 1][j + 2] == 0) {
                KnightPath(b, i + 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i + 2, j + 1) && b[i + 2][j + 1] == 0) {
                KnightPath(b, i + 2, j + 1);
            } else {
                return;
            }

        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        if (i > a.length - 1 || i < 0 || j > a[0].length - 1 || j < 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                KnightPath(b, i, j);
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] rows: matrix) {
            StringBuilder buff = new StringBuilder();
            buff.append("[");
            for (int i = 0; i < rows.length; i++) {
                int value = rows[i];
                buff.append(value);
                if (i < rows.length - 1) {
                    buff.append(", ");
                }
            }
            buff.append("]");
            System.out.println(buff.toString());
        }
    }
}

The output is

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[21, 22, 23, 24, 25]

Body:
To solve for all paths, you need to reset the placed values of paths you've exhausted so that newer paths can access them.  Additionally, your counter should reflect how deep you've gone, so that if you back out to try another path, your counter should roll back, too.  I would recommend passing a counter as a parameter rather than using a static counter.  Also, if you want to try all valid possibilities, then you need to avoid those return statements whenever one possibility is deemed invalid.

public static void KnightPath(int[][] b, int i, int j, int counter) {
    ...
        if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
            KnightPath(b, i - 1, j + 2, counter+1);
        }
    ...
    b[i][j] = 0;
}

public static void main(String[] args) {
    ...
            KnightPath(b, i, j, 1);
    ...
}


问:
string concatenation and addition
When I try to do addition:

```<code>let x = "5" + 2 + 3;
//output 523

let x = 2 + 3 + "5";
// output 55
</code>```

I know JavaScript concatenates the integers, but I was expecting "55" in both cases.

As 2+3 will be added to 5 and then concatenated to "5". Please can someone explain to me
what is happening under the hood.

I am new to JavaScript.

答:
The pluses are evaluated from left to right.
So first "5"+2 is evaluated (result is "52"), and then "52"+3 gives "523".

Title: string concatenation and addition

Body:
When I try to do addition:

let x = "5" + 2 + 3;
//output 523

let x = 2 + 3 + "5";
// output 55

I know JavaScript concatenates the integers, but I was expecting "55" in both cases.

As 2+3 will be added to 5 and then concatenated to "5". Please can someone explain to me
what is happening under the hood.

I am new to JavaScript.


问:
How to prove that another definition of permutation is the same as the Default Permutation Library for COQ
I need to proove that a secondary definition of permutation is equivalent to the default definition of permutation in Coq:

Down bellow is the default Permutation definition in Coq

```<code>Inductive Permutation : list A -> list A -> Prop :=
| perm_nil: Permutation [] []
| perm_skip x l l' : Permutation l l' -> Permutation (x::l) (x::l')
| perm_swap x y l : Permutation (y::x::l) (x::y::l)
| perm_trans l l' l'' :
    Permutation l l' -> Permutation l' l'' -> Permutation l l''.
</code>```

I need to prove that the above mentioned definition is equivalent to the following definition:

```<code>Definition perm l l' := forall x, occurences_number x l = occurences_number x l'.
</code>```

Which as you have noticed uses the definition occurences_number down bellow:

```<code>Fixpoint occurences_number x l := match l with
                       | nil => 0
                       | h::tl => if (x =? h) then S(occurences_number x tl) else occurences_number x tl
                       end.
</code>```

What I need to prove indeed is the following:

```<code>Lemma permutation_to_perm: forall l l', Permutation l l' -> perm l l'.
</code>```

Down bellow is my incomplete proof

```<code>Proof.
 induction l.
 - admit.
 - intros l' Hequiv.
   generalize dependent a.
   generalize dependent l.
   case l'.
   + Admitted.
</code>```

答:
Here is a proof that follows the strategy I outlined above:</p>
```<code>Lemma Permutation_to_perm l l' : Permutation l l' -> perm l l'.
Proof.
intros H. induction H as [| x l1 l2 _ IH | x y l | l1 l2 l3 _ IH1 _ IH2 ].
- intros ?; reflexivity.
- intros y. simpl. now rewrite IH.
- intros z. simpl. now destruct (z =? y), (z =? x).
- intros ?. now rewrite IH1.
Qed.
</code>```

Body:
I need to proove that a secondary definition of permutation is equivalent to the default definition of permutation in Coq:

Down bellow is the default Permutation definition in Coq

Inductive Permutation : list A -> list A -> Prop :=
| perm_nil: Permutation [] []
| perm_skip x l l' : Permutation l l' -> Permutation (x::l) (x::l')
| perm_swap x y l : Permutation (y::x::l) (x::y::l)
| perm_trans l l' l'' :
    Permutation l l' -> Permutation l' l'' -> Permutation l l''.

I need to prove that the above mentioned definition is equivalent to the following definition:

Definition perm l l' := forall x, occurences_number x l = occurences_number x l'.

Which as you have noticed uses the definition occurences_number down bellow:

Fixpoint occurences_number x l := match l with
                       | nil => 0
                       | h::tl => if (x =? h) then S(occurences_number x tl) else occurences_number x tl
                       end.

What I need to prove indeed is the following:

Lemma permutation_to_perm: forall l l', Permutation l l' -> perm l l'.

Down bellow is my incomplete proof

Proof.
 induction l.
 - admit.
 - intros l' Hequiv.
   generalize dependent a.
   generalize dependent l.
   case l'.
   + Admitted.

Body:
Here is a proof that follows the strategy I outlined above:

Lemma Permutation_to_perm l l' : Permutation l l' -> perm l l'.
Proof.
intros H. induction H as [| x l1 l2 _ IH | x y l | l1 l2 l3 _ IH1 _ IH2 ].
- intros ?; reflexivity.
- intros y. simpl. now rewrite IH.
- intros z. simpl. now destruct (z =? y), (z =? x).
- intros ?. now rewrite IH1.
Qed.


问:
How to use an object outside of scope of a loop in javascript
The following function compares a value against an array and goes through the elements of the array until finds an element that is smaller than the comparison value. As a result it should return the index of that element where condition was met. In this example it should return the index of 4 (with value of 5). I store this index in lowestNumberIndex but can only access it within the scope of last if() function. How can I access it outside the for loop? Notice that I have initiated the object outside of the for loop.

```<code>function findLowerIndex () {

  let firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let compareValue = [6];

  var lowerNumber = null;
  var lowestNumberIndex = null;

  for (i=firstArray.length-1; i>0; i--) {
    lowerNumber = firstArray[i];
    if (lowerNumber < compareValue) {
      lowestNumberIndex = i;
      return;
    }
  }
}
</code>```

In case you are wondering, I need to have the for loop in reverse format because this is part of a larger code and the dataset is organized in a way that doing it backwards ensures efficiency of run.

答:
You could take the index for looping and as result. For the comparing value use the value without wrapping it in an array.

function findLowerIndex() {
    const
        firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        compareValue = 6;

    let index = firstArray.length;

    while (index--) {
        if (firstArray[index] < compareValue) break;
    }
    // use the found index
    return index;
}

console.log(findLowerIndex());```

Body:
The following function compares a value against an array and goes through the elements of the array until finds an element that is smaller than the comparison value. As a result it should return the index of that element where condition was met. In this example it should return the index of 4 (with value of 5). I store this index in lowestNumberIndex but can only access it within the scope of last if() function. How can I access it outside the for loop? Notice that I have initiated the object outside of the for loop.

function findLowerIndex () {

  let firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let compareValue = [6];

  var lowerNumber = null;
  var lowestNumberIndex = null;

  for (i=firstArray.length-1; i>0; i--) {
    lowerNumber = firstArray[i];
    if (lowerNumber < compareValue) {
      lowestNumberIndex = i;
      return;
    }
  }
}

In case you are wondering, I need to have the for loop in reverse format because this is part of a larger code and the dataset is organized in a way that doing it backwards ensures efficiency of run.


问:
MacOS SourceTree clear credential helper for generic remote repository
System:

MacOS Catalina 10.15.5
SourceTree v4.0.1

Issue:

I have a local repository that I've cloned from Github. That repository also exists in another remote (it's actually git repo for an Azure Function, so not one of the other usual suspects e.g. Bitbucket), and I'm simply trying to set up that remote so I can fetch/push/etc to it.

I've done this on a previous machine, and I'm getting re-set up for development on a new MacBook, so it's something that I've done before, but I just made a simple copy/paste mistake that I can't seem to undo.

In SourceTree, I went to the menu to add a remote and only input the remote URL:

After I okayed that, I went to the list of remotes, right click the new addition to the list, and attempted a fetch. This prompted me for a username and then a password. I incorrectly copy/pasted one of the two values, but that seems to be stuck now with no way of simply deleting it.

Now, when I try to fetch (or do anything) with that particular remote, I continually get a 403 Forbidden response.

```<code>git --no-optional-locks -c color.branch=false -c color.diff=false -c color.status=false -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree fetch remote-name
fatal: unable to access 'https://actual-remote-url/git.git/: The requested URL returned error: 403
</code>```

I've searched most of the other SO posts here about removing the individual entries from Keychain Access as well as removing the files from Application Support.

I had SourceTree open when I removed the keys directly from the Keychain, so that may have had an impact, but after removing them and trying to fetch from the remote again, I simply got the same 403 error as before (rather than it asking for the credentials).

The same happened after clearing the Application Support folder for SourceTree. It re-asked me my credentials for the Github remote, but it didn't ask me anything for the new remote. When I tried to fetch, I got the same 403 error as before.

Switching between the Embedded Git and System Git seems to have no effect at all.

I've gone around the horn and back trying to solve this (an absolutely ridiculous 3 hours at this point TO ADD A REMOTE) and have also tried:

Trashing and Reinstalling Sourcetree

Playing with the security command line tool (the CLI for Keychain) to see if I could find a hidden reference anywhere to the remote that was hanging in limbo

Fiddling with credential-helper stuff (mostly throwing stuff at the wall and nothing sticking)

Restarting the machine

But, absolutely nothing I try yields the username/password prompt again and I always receive the 403.

My best guess is that this is somehow related to the -c credential.helper=sourcetree bit in the git command that Sourcetree initially issued. Is there a separate credential store that is keeping my old creds around?

A bit of testing seems to indicate that this is the case. I have yet another remote where the same repository is hosted, and when I set that up (no flubbing on the username/password), and then remove the credentials that are saved to Keychain, a subsequent fetch doesn't ask me for my credentials. But, where in the *?!$ are they?? (and how do I clear them??)

答:
I had exactly the same issue, hopefully my solution works for you too.
Try to follow this article https://docs.aws.amazon.com/codecommit/latest/userguide/troubleshooting-ch.html#troubleshooting-macoshttps

Go to Access Control and remove git-credential-osxkeychain from git-codecommit

After hours of research this article is the only one that provided the solution to add empty helper and somehow that solved it for me.

```<code>[credential]

  helper =

  helper = !aws --profile CodeCommitProfile codecommit credential-helper $@

  UseHttpPath = true

</code>```

Body:
System:

MacOS Catalina 10.15.5
SourceTree v4.0.1

Issue:

I have a local repository that I've cloned from Github. That repository also exists in another remote (it's actually git repo for an Azure Function, so not one of the other usual suspects e.g. Bitbucket), and I'm simply trying to set up that remote so I can fetch/push/etc to it.

I've done this on a previous machine, and I'm getting re-set up for development on a new MacBook, so it's something that I've done before, but I just made a simple copy/paste mistake that I can't seem to undo.

In SourceTree, I went to the menu to add a remote and only input the remote URL:

After I okayed that, I went to the list of remotes, right click the new addition to the list, and attempted a fetch. This prompted me for a username and then a password. I incorrectly copy/pasted one of the two values, but that seems to be stuck now with no way of simply deleting it.

Now, when I try to fetch (or do anything) with that particular remote, I continually get a 403 Forbidden response.

git --no-optional-locks -c color.branch=false -c color.diff=false -c color.status=false -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree fetch remote-name
fatal: unable to access 'https://actual-remote-url/git.git/: The requested URL returned error: 403

I've searched most of the other SO posts here about removing the individual entries from Keychain Access as well as removing the files from Application Support.

I had SourceTree open when I removed the keys directly from the Keychain, so that may have had an impact, but after removing them and trying to fetch from the remote again, I simply got the same 403 error as before (rather than it asking for the credentials).

The same happened after clearing the Application Support folder for SourceTree. It re-asked me my credentials for the Github remote, but it didn't ask me anything for the new remote. When I tried to fetch, I got the same 403 error as before.

Switching between the Embedded Git and System Git seems to have no effect at all.

I've gone around the horn and back trying to solve this (an absolutely ridiculous 3 hours at this point TO ADD A REMOTE) and have also tried:

Trashing and Reinstalling Sourcetree

Playing with the security command line tool (the CLI for Keychain) to see if I could find a hidden reference anywhere to the remote that was hanging in limbo

Fiddling with credential-helper stuff (mostly throwing stuff at the wall and nothing sticking)

Restarting the machine

But, absolutely nothing I try yields the username/password prompt again and I always receive the 403.

My best guess is that this is somehow related to the -c credential.helper=sourcetree bit in the git command that Sourcetree initially issued. Is there a separate credential store that is keeping my old creds around?

A bit of testing seems to indicate that this is the case. I have yet another remote where the same repository is hosted, and when I set that up (no flubbing on the username/password), and then remove the credentials that are saved to Keychain, a subsequent fetch doesn't ask me for my credentials. But, where in the *?!$ are they?? (and how do I clear them??)

Body:
I had exactly the same issue, hopefully my solution works for you too.
Try to follow this article https://docs.aws.amazon.com/codecommit/latest/userguide/troubleshooting-ch.html#troubleshooting-macoshttps

Go to Access Control and remove git-credential-osxkeychain from git-codecommit

After hours of research this article is the only one that provided the solution to add empty helper and somehow that solved it for me.

[credential]

  helper =

  helper = !aws --profile CodeCommitProfile codecommit credential-helper $@

  UseHttpPath = true


问:
How to upload video to youtube?

Possible Duplicate:

  How do I upload a video to YouTube from within an iOS application?

Is there any way to implement functionality to upload video in youtube in iPhone? If so, how? Thanks in advance.

答: use the Youtube API and check the GDATA Objective-C Client here, also see this SO answer.</p>

Title: How to upload video to youtube?


问:
How to rotate API and application keys in Datadog
In Datadog, I have a couple of API and Application keys that are actively being used by internal applications, most of the keys are owned by individual persons, who are no longer in the team. Now how do I rotate them and transfer them to a service account instead of an individual person without downtime or less downtime? Any suggestions or ideas?</p>

答:
API keys do not need to be replaced when a user is deleted. They belong to your entire account, and if the creator of the tag is deleted, the API key still works just fine. API keys are like the password to your organization, and are used for submitting data.

https://docs.datadoghq.com/account_management/api-app-keys/#api-keys

Application keys are used for automating behaviors in your account. Anything a user can do in the account like create a dashboard or edit a monitor, the application key will be required for when using the API. Application keys are tied to a specific user and will inherit all the permissions of that user. So if that user does not have the ability to edit dashboards, neither will the Application Key.

You can avoid the issue of general automation tasks being tied to a specific human by utilizing service accounts. Service accounts are meant to be robotic users, which can be provided roles and create application keys. They should be linked to a common distribution list that your team has access to so it's not tied to a single person.


问:
I’m having trouble finding the bug
I am trying to line up this list item directly underneath the hours div tag. My list item is pushed just a little to the right, and I cant seem to find out why. My HTML and CSS skills are beginner.

I did follow from a YouTube video, but don't know what I did wrong.

#hero h2{
  display: block;
  width: fit-content;
  font-size: 2rem;
  position: relative;

}

#hero ul li{
  display: block;
  width: fit-content;
  font-size: 1.5rem;
  position: relative;
}

.hours ul {
  margin: 0;
  padding: 0;
}

.hours li{
  list-style: none;
}

.hours li {
  text-decoration: none;
  color: black;
  padding: .5rem;
  display: block;

}
```
<pre class="lang-html prettyprint-override"><code>    <section id="hero">
  <div class="hero container">
    <div class="">
      <h2>Hours</h2>
      <div class="hours">
       <ul>
        <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
      </ul>
     </div>
    </div>
  </section>
</code>```

答:
Your .hours li have padding: .5rem that's why.

You might set padding:.5rem 0 to align better.

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 20px;
}

#hero h2 {
  display: block;
  width: fit-content;
  font-size: 2rem;
  position: relative;
}

#hero ul li {
  display: block;
  width: fit-content;
  font-size: 1.5rem;
  position: relative;
}

.hours ul {
  margin: 0;
  padding: 0;
}

.hours li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.hours li {
  text-decoration: none;
  color: black;
  padding: .5rem 0;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="hero">
  <div class="hero container">
    <div class="">
      <h2>Hours</h2>
      <div class="hours">
        <ul>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
        </ul>
      </div>
    </div>
</section></code>```

Title: I’m having trouble finding the bug

Body:
I am trying to line up this list item directly underneath the hours div tag. My list item is pushed just a little to the right, and I cant seem to find out why. My HTML and CSS skills are beginner.

I did follow from a YouTube video, but don't know what I did wrong.

#hero h2{
  display: block;
  width: fit-content;
  font-size: 2rem;
  position: relative;

}

#hero ul li{
  display: block;
  width: fit-content;
  font-size: 1.5rem;
  position: relative;
}

.hours ul {
  margin: 0;
  padding: 0;
}

.hours li{
  list-style: none;
}

.hours li {
  text-decoration: none;
  color: black;
  padding: .5rem;
  display: block;

}

Hours

Mon-thurs: 9am - 5pm

Body:
Your .hours li have padding: .5rem that's why.

You might set padding:.5rem 0 to align better.

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 20px;
}

#hero h2 {
  display: block;
  width: fit-content;
  font-size: 2rem;
  position: relative;
}

#hero ul li {
  display: block;
  width: fit-content;
  font-size: 1.5rem;
  position: relative;
}

.hours ul {
  margin: 0;
  padding: 0;
}

.hours li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.hours li {
  text-decoration: none;
  color: black;
  padding: .5rem 0;
  display: block;
}

<section id="hero">
  <div class="hero container">
    <div class="">
      <h2>Hours</h2>
      <div class="hours">
        <ul>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
          <li><b>Mon-thurs: </b>9am - 5pm<span></span></li>
        </ul>
      </div>
    </div>
</section>


问:
error with appending to a file and using an array
I have written this code:

```<code>    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)
</code>```

and I get the error :

```<code>  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'
</code>```

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance

答:
You've got things out of order in your __init__:

```<code>  def __init__(self, *component, **kwargs):

    self.name = kwargs.get('name')
    self.component = component

    self.lines = kwargs.get('lines', [])
</code>```

Will work. You need lines and name to be after the * item that collects the component.

In Python 2, you can't then have named attributes after a *, so you need to instead use **kwargs and get('name') and get('lines') from the kwargs.

get just returns None if you don't supply a default, so you'll get self.name = None here. If you want to specify a default name, you can do

```<code>    self.name = kwargs.get('name', 'defaultname')
</code>```

like I did for lines.

Body:
I have written this code:

    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)

and I get the error :

  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance

Body:
You've got things out of order in your __init__:

  def __init__(self, *component, **kwargs):

    self.name = kwargs.get('name')
    self.component = component

    self.lines = kwargs.get('lines', [])

Will work. You need lines and name to be after the * item that collects the component.

In Python 2, you can't then have named attributes after a *, so you need to instead use **kwargs and get('name') and get('lines') from the kwargs.

get just returns None if you don't supply a default, so you'll get self.name = None here. If you want to specify a default name, you can do

    self.name = kwargs.get('name', 'defaultname')

like I did for lines.


问:
How to build a release mode without a key in flutter - Flutter debug mode is so slow
Whenever I try to test my app with flutter run command it's so laggy and slow and I can't determine how is my app performance in a release mode. However for building the app in release mode for android we need to make a key for the app and it doesn't show most of the Log files and Prints.

So the question is, Is there any way to run the app in release mode format but with debug features?

答:
Short Answer:

There are 3 different build modes in flutter:

Debug
: This is the most common mode we always test the apps. If you are using Android Studio you can find its button on the top panel (a green play button).

```<code>flutter run
</code>```

Release
: This mode is for deploying the app on market places.

Note: This mode needs a key generated for android release mode.

```<code>flutter run --release
</code>```

Profile
: This is the mode you are looking for. In profile mode, some debugging ability is maintained—enough to profile your app’s performance and also it has the performance as the release mode.

```<code>flutter run --profile
</code>```

Long Answer:

Debug:

In debug mode, the app is set up for debugging on the physical device,
emulator, or simulator.

Debug mode for mobile apps mean that:

Assertions are enabled.
Service extensions are enabled.
Compilation is optimized for fast development and run cycles (but not for execution speed, binary size, or deployment).
Debugging is enabled, and tools supporting source level debugging (such as DevTools) can connect to the process.

Debug mode for a web app means that:

The build is not minified and tree shaking has not been performed.
The app is compiled with the dartdevc compiler for easier debugging.

By default, flutter run compiles to debug mode. Your IDE supports this
mode. Android Studio, for example, provides a Run > Debug… menu
option, as well as a green bug icon overlayed with a small triangle on
the project page.

Release:

Use release mode for deploying the app, when you want maximum
optimization and minimal footprint size. For mobile, release mode
(which is not supported on the simulator or emulator), means that:

Assertions are disabled.
Debugging information is stripped out.
Debugging is disabled.
Compilation is optimized for fast startup, fast execution, and small package sizes.
Service extensions are disabled.

Release mode for a web app means that:

The build is minified and tree shaking has been performed.
The app is compiled with the dart2js compiler for best performance.

Profile:

In profile mode, some debugging ability is maintained—enough to
profile your app’s performance. Profile mode is disabled on the
emulator and simulator, because their behavior is not representative
of real performance. On mobile, profile mode is similar to release
mode, with the following differences:

Some service extensions, such as the one that enables the performance overlay, are enabled.
Tracing is enabled, and tools supporting source-level debugging (such as DevTools) can connect to the process.

Profile mode for a web app means that:

The build is not minified but tree shaking has been performed.
The app is compiled with the dart2js compiler.

You can find the docs on flutter official website here: Flutter's build modes

Body:
Short Answer:

There are 3 different build modes in flutter:

Debug
: This is the most common mode we always test the apps. If you are using Android Studio you can find its button on the top panel (a green play button).

flutter run

Release
: This mode is for deploying the app on market places.

Note: This mode needs a key generated for android release mode.

flutter run --release

Profile
: This is the mode you are looking for. In profile mode, some debugging ability is maintained—enough to profile your app’s performance and also it has the performance as the release mode.

flutter run --profile

Long Answer:

Debug:

In debug mode, the app is set up for debugging on the physical device,
emulator, or simulator.

Debug mode for mobile apps mean that:

Assertions are enabled.
Service extensions are enabled.
Compilation is optimized for fast development and run cycles (but not for execution speed, binary size, or deployment).
Debugging is enabled, and tools supporting source level debugging (such as DevTools) can connect to the process.

Debug mode for a web app means that:

The build is not minified and tree shaking has not been performed.
The app is compiled with the dartdevc compiler for easier debugging.

By default, flutter run compiles to debug mode. Your IDE supports this
mode. Android Studio, for example, provides a Run > Debug… menu
option, as well as a green bug icon overlayed with a small triangle on
the project page.

Release:

Use release mode for deploying the app, when you want maximum
optimization and minimal footprint size. For mobile, release mode
(which is not supported on the simulator or emulator), means that:

Assertions are disabled.
Debugging information is stripped out.
Debugging is disabled.
Compilation is optimized for fast startup, fast execution, and small package sizes.
Service extensions are disabled.

Release mode for a web app means that:

The build is minified and tree shaking has been performed.
The app is compiled with the dart2js compiler for best performance.

Profile:

In profile mode, some debugging ability is maintained—enough to
profile your app’s performance. Profile mode is disabled on the
emulator and simulator, because their behavior is not representative
of real performance. On mobile, profile mode is similar to release
mode, with the following differences:

Some service extensions, such as the one that enables the performance overlay, are enabled.
Tracing is enabled, and tools supporting source-level debugging (such as DevTools) can connect to the process.

Profile mode for a web app means that:

The build is not minified but tree shaking has been performed.
The app is compiled with the dart2js compiler.

You can find the docs on flutter official website here: Flutter's build modes


问:
no valid credential sources for Terraform AWS Provider found
I am using shared_cred_file for aws provider. With aws provider version 3.63 for example, terraform plan works good.

When I use aws provider 4.0 it prompts me to use apply changed setting for shared_credentials_files. After the changes, there is no error, but the second error remains

what could be the problem?

```<code>Warning: Argument is deprecated
│
│   with provider[“registry.terraform.io/hashicorp/aws”],
│   on main.tf line 15, in provider “aws”:
│   15:   shared_credentials_file = “~/.aws/credentials”
│
│ Use shared_credentials_files instead.
│
│ (and one more similar warning elsewhere)
╵
╷
│ Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│
│ Error: no EC2 IMDS role found, operation error ec2imds: GetMetadata, canceled, context deadline exceeded
│
│
│   with provider[“registry.terraform.io/hashicorp/aws”],
│   on main.tf line 13, in provider “aws”:
│   13: provider “aws” {
│
</code>```
```<code>///////////////////////////////
// Infrastructure init
terraform {
  backend "s3" {
    bucket                  = "monitoring-********-infrastructure"
    key                     = "tfstates/********-non-prod-rds-info.tfstate"
    profile                 = "test-prof"
    region                  = "eu-west-2"
    shared_credentials_file = "~/.aws/credentials"
  }
}

    provider "aws" {
      profile                 = "test-prof"
      shared_credentials_files = ["~/.aws/credentials"]
      region                  = "eu-west-2"
    }
</code>```
```<code>    Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
        │
        │ Please see https://registry.terraform.io/providers/hashicorp/aws
        │ for more information about providing credentials.
        │
        │ Error: no EC2 IMDS role found, operation error ec2imds: GetMetadata, canceled, context deadline exceeded
        │
        │
        │   with provider["registry.terraform.io/hashicorp/aws"],
        │   on main.tf line 13, in provider "aws":
        │   13: provider "aws" {

</code>```

cat config

```<code>[test-prof]
output = json
region = eu-west-2
</code>```

cat credentials

```<code>[test-prof]
aws_access_key_id = ****************
aws_secret_access_key = ******************
</code>```

答:
Changing

```<code>provider "aws" {
  shared_credentials_file = "$HOME/.aws/credentials"
  profile                 = "default"
  region                  = "us-east-1"
}
</code>```

to

```<code>provider "aws" {
  shared_credentials_file = "/Users/me/.aws/credentials"
  profile                 = "default"
  region                  = "us-east-1"
}
</code>```

worked for me.

Body:
I am using shared_cred_file for aws provider. With aws provider version 3.63 for example, terraform plan works good.

When I use aws provider 4.0 it prompts me to use apply changed setting for shared_credentials_files. After the changes, there is no error, but the second error remains

what could be the problem?

Warning: Argument is deprecated
│
│   with provider[“registry.terraform.io/hashicorp/aws”],
│   on main.tf line 15, in provider “aws”:
│   15:   shared_credentials_file = “~/.aws/credentials”
│
│ Use shared_credentials_files instead.
│
│ (and one more similar warning elsewhere)
╵
╷
│ Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│
│ Error: no EC2 IMDS role found, operation error ec2imds: GetMetadata, canceled, context deadline exceeded
│
│
│   with provider[“registry.terraform.io/hashicorp/aws”],
│   on main.tf line 13, in provider “aws”:
│   13: provider “aws” {
│

///////////////////////////////
// Infrastructure init
terraform {
  backend "s3" {
    bucket                  = "monitoring-********-infrastructure"
    key                     = "tfstates/********-non-prod-rds-info.tfstate"
    profile                 = "test-prof"
    region                  = "eu-west-2"
    shared_credentials_file = "~/.aws/credentials"
  }
}

    provider "aws" {
      profile                 = "test-prof"
      shared_credentials_files = ["~/.aws/credentials"]
      region                  = "eu-west-2"
    }

    Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
        │
        │ Please see https://registry.terraform.io/providers/hashicorp/aws
        │ for more information about providing credentials.
        │
        │ Error: no EC2 IMDS role found, operation error ec2imds: GetMetadata, canceled, context deadline exceeded
        │
        │
        │   with provider["registry.terraform.io/hashicorp/aws"],
        │   on main.tf line 13, in provider "aws":
        │   13: provider "aws" {

cat config

[test-prof]
output = json
region = eu-west-2

cat credentials

[test-prof]
aws_access_key_id = ****************
aws_secret_access_key = ******************

Body:
Changing

provider "aws" {
  shared_credentials_file = "$HOME/.aws/credentials"
  profile                 = "default"
  region                  = "us-east-1"
}

to

provider "aws" {
  shared_credentials_file = "/Users/me/.aws/credentials"
  profile                 = "default"
  region                  = "us-east-1"
}

worked for me.


问:
Get ID of preceding image on click event
I have this HTML code

```<code><div> <img src="download1.jpeg" image-id="9a8ae555af5f"></div>
<div><h1><a href ="#">test</a></h1></div>

</code>```

When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link

I have tried this but imageID returns undefined

```<code>function trackClick(event)
{
  let imageId = this.$('a').prev('img').attr('image-id');

console.log("imageId", imageId);
}

document.addEventListener('click', trackClick, true);

</code>```

Any ideas on how i can make this work using js or css selectors?

thanks

答:
Using Vanilla JS, step by step:</p>
```<code>function trackClick(event)
{
  let targetElement = event.target || event.srcElement;

  let closestDiv = targetElement.closest('div');

  let previousDiv = closestDiv.previousElementSibling;

  let insideImage = previousDiv.getElementsByTagName('img');
  // or
  // let insideImage = previousDiv.children;

  console.log(insideImage[0].getAttribute('src'));
}

document.addEventListener('click', trackClick, true);
</code>```

Body:
I have this HTML code

test

When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link

I have tried this but imageID returns undefined

function trackClick(event)
{
  let imageId = this.$('a').prev('img').attr('image-id');

console.log("imageId", imageId);
}

document.addEventListener('click', trackClick, true);

Any ideas on how i can make this work using js or css selectors?

thanks

Body:
Using Vanilla JS, step by step:

function trackClick(event)
{
  let targetElement = event.target || event.srcElement;

  let closestDiv = targetElement.closest('div');

  let previousDiv = closestDiv.previousElementSibling;

  let insideImage = previousDiv.getElementsByTagName('img');
  // or
  // let insideImage = previousDiv.children;

  console.log(insideImage[0].getAttribute('src'));
}

document.addEventListener('click', trackClick, true);


问:
how to create a table with different type values with Parse method?
```<code>public class Libro
    {
        public string Titolo { get; set; }
        public string Autore { get; set; }
        public string Editore { get; set; }
        public int ISBN { get; set; }
        public int Pagine { get; set; }
        public decimal Prezzo { get; set; }
        public int Quantità { get; set; }
</code>```

not being all of type string, I would not know how to convert the int and decimal values to have as a result a table in which to display a list of books (titles, authors, publishers and price) that I have on a file.txt

```<code>        public Libro BuildLibro(string input)
        {
            Libro result = null;

            if (!String.IsNullOrEmpty(input))
            {
                var inputArray = input.Split('*');

                if (inputArray.Length >= 6)
                {
                    result = new Libro();

                    result.Titolo = inputArray[0];
                    result.Autore = inputArray[1];
                    result.Editore = inputArray[2];

                    if (!string.IsNullOrEmpty(inputArray[3]))
                    {
                        int.TryParse(inputArray[3], out int num);
                        result.ISBN= num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[4]))
                    {
                        int.TryParse(inputArray[4], out int num);
                        result.Pagine = num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[5]))
                    {
                        decimal.TryParse(inputArray[5], out decimal num);
                        result.Prezzo = num/100;

                    }

                    if (!string.IsNullOrEmpty(inputArray[6]))
                    {
                        int.TryParse(inputArray[6], out int num);
                        result.Quantità = num;

                    }

                }
            }
            return result;
        }
    }
}
</code>```

答:
There are many ways to parse information out of a string.

I would sugest using regex. For example with the following regex you could parse three strings separated by a *:

```<code>(?'Title'[^*]+)[*](?'Author'[^*]+)[*](?'ISBN'[^*]+)
</code>```

The Advantage of using regex is, that you check if the string is valid while the string is parsed.
To test a regex I would sugest to use something like https://regex101.com

In your code you can use the C# library:

```<code>using System.Text.RegularExpressions;

Regex rx = new Regex(@"(?'Title'[^*]+)[*](?'Author'[^*]+)[*](?'ISBN'[^*]+)",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

// Define a test string.
string text = "Harry Potter*Rowling*12345";

// Find matches.
MatchCollection matches = rx.Matches(text);
</code>```

Body:
public class Libro
    {
        public string Titolo { get; set; }
        public string Autore { get; set; }
        public string Editore { get; set; }
        public int ISBN { get; set; }
        public int Pagine { get; set; }
        public decimal Prezzo { get; set; }
        public int Quantità { get; set; }

not being all of type string, I would not know how to convert the int and decimal values to have as a result a table in which to display a list of books (titles, authors, publishers and price) that I have on a file.txt

        public Libro BuildLibro(string input)
        {
            Libro result = null;

            if (!String.IsNullOrEmpty(input))
            {
                var inputArray = input.Split('*');

                if (inputArray.Length >= 6)
                {
                    result = new Libro();

                    result.Titolo = inputArray[0];
                    result.Autore = inputArray[1];
                    result.Editore = inputArray[2];

                    if (!string.IsNullOrEmpty(inputArray[3]))
                    {
                        int.TryParse(inputArray[3], out int num);
                        result.ISBN= num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[4]))
                    {
                        int.TryParse(inputArray[4], out int num);
                        result.Pagine = num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[5]))
                    {
                        decimal.TryParse(inputArray[5], out decimal num);
                        result.Prezzo = num/100;

                    }

                    if (!string.IsNullOrEmpty(inputArray[6]))
                    {
                        int.TryParse(inputArray[6], out int num);
                        result.Quantità = num;

                    }

                }
            }
            return result;
        }
    }
}

Body:
There are many ways to parse information out of a string.

I would sugest using regex. For example with the following regex you could parse three strings separated by a *:

(?'Title'[^*]+)[*](?'Author'[^*]+)[*](?'ISBN'[^*]+)

The Advantage of using regex is, that you check if the string is valid while the string is parsed.
To test a regex I would sugest to use something like https://regex101.com

In your code you can use the C# library:

using System.Text.RegularExpressions;

Regex rx = new Regex(@"(?'Title'[^*]+)[*](?'Author'[^*]+)[*](?'ISBN'[^*]+)",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

// Define a test string.
string text = "Harry Potter*Rowling*12345";

// Find matches.
MatchCollection matches = rx.Matches(text);