Firebase (....ContinueWith(task => ...) in a For-Loop - firebase

First, this is the code:
for (int j = 1; j <= count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
Debug.Log("j: " + j); // Here the Debug will show me that j = count
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}
Ok, so my problem is that after the "....ContinueWith(task => ..." ' j ' will become directly equal to the count variable. Why this happens and how to solve it? Or is there another method to do that?

Ok, so my problem is that after the "....ContinueWith(task => ..." ' j
' will become directly equal to the count variable. Why this happens
and how to solve it?
That's because you used <= instead of <. With <=, j must be equals to count for the loop condition to be met and finish. If you want j to be less than count then use count-1 or simply use <.
So, that should be
for (int j = 1; i <= count-1; j++)
Or
for (int j = 1; i < count; j++)
Note that array starts from 0 not 1 so int j = 1; should be int j = 0; but I have a feeling that's what you wanted to do and you are starting the loop from 1 on purpose.
Finally, another problem is your variable being captured in a loop because you are using lambda in the ContinueWith function. See this post for more information. To use the j variable inside the ContinueWith lambda function, make a copy of it then use that copy instead of the j variable.
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy); // Here the Debug will show me that j = count
}
Complete fixed code:
for (int j = 1; i < count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy);
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}

Related

Last line of a datatable asp.net

I have a problem when I'm trying to a loop in a DataTable that a dataset contains.
I'm doing a loop like this:
for(int i = 0; i<ds.Tables[0].Rows.Count - 1 ; i++)
The problem is that I can't get the value of the last line with this one, but if I try to get rid of the "-1" and do a loop on the whole table, I'll have an out of range exception.
This out of range exception is because I have to check if the value of a line "i" is equal to the value of a line "i+1", like this:
if (ds.Tables[0].Rows[i]["Release_No"] != ds.Tables[0].Rows[i + 1]["Release_No"])
So if I do it in a loop, when the index is on the last line it will check if the last line is equal to i+1, and it's out of the table.
So I was trying to check if the index is on the last line, then just get the value of the last line, but it seems like it doesn't work.
if(ds.Tables[0].Rows.IndexOf(ds.Tables[0].Rows[i]) == ds.Tables[0].Rows.Count)
If anyone has an idea, let me know, and of course if it is not clear enough let me know, I'll give more information and more code.
Thanks for your help and your time!
Check if it's the last record, first.
I like to refactor code to read as close to sentence form as possible, explaining what you want it to do using named variables and methods, and that often gets me unlocked.
Try to make each line of code do one thing, and one thing only, like check if it is the last row:
var data = ds.Tables[0].Rows;
var lastRow = data.Count - 1;
for(int i = 0; i < lastRow ; i++)
{
if (i == lastRow){
// This is the last row. Handle the last row here.
}
else
{
// Handle all other rows here
var currentRecord = data[i];
var nextRecord = data[i + 1];
if (currentRecord["Release_No"] != nextRecord["Release_No"])
{
// Handle unique Releases...
}
}
}
Use less than or equal to like this
for(int i = 0; i<=ds.Tables[0].Rows.Count - 1 ; i++)
I hope this may get what you want.
Something like this is better ?
var lastRow = data.Count - 1;
var data = ds.Tables[0].Rows;
for(int i = 0; i< lastRow; i++)
{
testFirstCum = Convert.ToInt32(ds.Tables[0].Rows[i]["EDI_Accum_Quantity"]);
if ( i == lastRow)
{
if (DBNull.Value.Equals(data[i]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
else
{
var col = ds.Tables[0].Columns;
var currentRecord = data[i];
var nextRecord = data[i + 1];
if(currentRecord["Release_No"] != nextRecord["Release_No"])
{
for (int j = col[2].Ordinal; j < col.Count; j++)
{
if (DBNull.Value.Equals(data[i][j]))
{
quantity = 0;
}
else
{
quantity = Convert.ToInt32(data[i][j]);
testFirstCum = testFirstCum + quantity;
System.Diagnostics.Debug.WriteLine(quantity);
System.Diagnostics.Debug.WriteLine(testFirstCum);
}
}
}
}
}

Calculating assignemnt operators

Can someone explain to me why the answer to this problem isn't 25,102?
For the following code, suppose the if statement is true 50% of the time. If so, how many assignment operations occur? (Don't forget to count the initializations of i and j. Also remember that i++ and j++ are assignments.)
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
I can see how you got 25102, but I think you've not counted the j loop properly - it doesn't just add one j=0 to the total because the whole loop happens multiple times.

Big O notation of recursion function called inside for loop

I'm trying to determine the big O complexity of several algorithms and I'm having trouble understanding how to reason about the following piece of code:
void recursiveFunc (n)
{
for(int i = 0; i < 8; i++)
{
if (n < maxN)
{
recursiveFunc (n + 1);
}
else
{
for(int j = 0; j < 8; j++)
{
// do some stuff
}
}
}
}
I have the idea this is an exponential since the recursive function is called inside the loop. O(8^n)?
But I'm a bit lost on how to reason about it.
Your tip is correct.
Given the code:
var maxN = 16;
var initN = 0;
var count = 0;
function recursiveFunc (n) {
for(var i = 0; i < 8; i++) {
if (n < maxN) {
recursiveFunc (n + 1);
} else {
for(int j = 0; j < 8; j++) {
count++;
}
}
}
}
recursiveFunc(initN);
First call happens with n = 0:
8^1 calls of recursiveFunc (where n = 1)
calls with n = 1 then cause: 8^2 calls of recursiveFunc
...
calls with n = (maxN - 1) then cause: 8^maxN calls of recursiveFunc => visiting else branch, each call enters "some stuff" 64 times
First call happens with n = 2, maxN = 4:
8^1 calls of recursiveFunc (where n = 3)
calls with n = 3 then cause: 8^2 calls of recursiveFunc (where n = 4)
calls with n = 4 then visit else branch, each 64 times.
Therefore total count of entering the "some stuff" stage: 64 * (8^(maxN - initN))
O(8^n)
EDIT: You can see this in work here, just click "Run the snippet" and then hit the "Test" button. (Trying bigger maxN values may crash your browser)
function test () {
var maxN = parseInt(document.querySelector("#nmax").value);
var initN = parseInt(document.querySelector("#n").value);
var count = 0;
function recursiveFunc (n) {
for(var i = 0; i < 8; i++) {
if (n < maxN) {
recursiveFunc (n + 1);
} else {
for(var j = 0; j < 8; j++) {
count++;
}
}
}
}
recursiveFunc(initN);
document.querySelector("#expectedValue").innerHTML = 64 * (Math.pow(8, maxN - initN));// 64 * (8^(maxN - initN));
document.querySelector("#realValue").innerHTML = count;
}
N: <input type=number id=n value=0><br>
NMAX: <input type=number id=nmax value=5><br>
<hr>
Expected value: <span id=expectedValue></span><br>
Real value: <span id=realValue></span><br>
<button onclick="test()">Test</button>
(I also assume that initN <= maxN)

is String or is Number function

I'm actually working on a personal "Excel" for school.
When the value of my cell is a number (int), I want to add it in my listNumber (QList int). When the value of my cell is a String, I want to add it my listString.
These two lists then allow me to sort.
The problem is here :
QString test = text(i, j);
test.toInt(&ok);
if (ok == true) {
listNumber.append(test.toInt());
qSort(listNumber.begin(), listNumber.end());
}
ERROR ASSERT failure in QList<T>::at: "index out of range" .
I think it's because it wants to "insert" a string in a list of integer.
Here my function "sort"
QList<QString> listString;
QList<int> listNumber;
bool ok;
QTableWidgetSelectionRange range = selectedRange();
for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
for (int i = range.topRow(); i <= range.bottomRow(); ++i) {
QString test = text(i, j);
test.toInt(&ok);
if (ok == true) {
listNumber.append(test.toInt());
qSort(listNumber.begin(), listNumber.end());
}
}
}
if (listNumber.count() == 0) {
QMessageBox test;
test.setText("liste vide");
test.exec();
}
else {
int x = 0;
for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
for (int i = range.topRow(); i <= range.bottomRow(); ++i) {
Spreadsheet::setFormula(i, j, QString::number(listNumber.at(x)));
x++;
}
}
}
Thank you a lot for your help.
First of all, qSort in Qt is deprecated and it is recommended not to use it:
QT_DEPRECATED_X("Use std::sort") inline void qSort(...
You can use std::sort instead:
#include <algorithm>
//...
std::sort(listNumber.begin(), listNumber.end(), std::less<int>());
//or simply:
std::sort(listNumber.begin(), listNumber.end()); // using default comparison (operator <)
(But also you can simply call deprecated qSort:)
qSort(listNumber);

Infinite loop (do - while)

for(int m=0;m<=3;m++){
for(int n=0;n<=3;n++){
if(n>0){
int c =n,t=1;
do{
t = up_key_no0(&puzz[c][m]);
c--;
}while(t==1||c>=0);
}
}
}
int up_key_no0(int *puzy){
int *puzx = puzy -4;
int down = *puzy;
int up = *puzx;
if(((down==up)||(up==0))&&down!=0){
*puzx += *puzy;
*puzy=0;
return 1;
}
else{
return 0;
}
}
Is The Following piece of code wrong? if Yes Then Reply. The Whole Code Cant Be Fit But puzz is a 2 dimensional array of 4X4
Your do-while loop can go out of the range of the table to the negative indices when the t is 1 and the c is 0. So maybe you should change the condition to (t == 1 && c >= 0) (and instead of or).
I don't know that language is this, but case it's like Java, a "for" should be like so:
for (var i=0;i<=3;i++) {
}
Your while maybe wrong. This "==" on the while should be "=".
while(t=1||c>=0) {
}

Resources