问:
Execute binary file inside C code (No system())
I am trying to execute a binary executable file inside C code without using system since it has security and resource management issues.

The system used here is Debian Buster with kernel 5.4.0-2-amd64 and gcc 9.2.1.

I used the method in this question:
execute binary machine code from C

which is to convert executable into hexadecimal code with xxd -i, but constantly get Segmentation fault.

The procedures I used are:

First attempt

executable.c:

```<code>#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
    return 0;
}
</code>```

after compiling it with gcc -o executable executable.c

xxd -i executable will display binary file into hex

Then copy and paste the output to embedded.c

embedded.c:

```<code>#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

const unsigned char[] executable = {
    0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01,
    ...
};

int main(void)
{
    void *buf = mmap(
        NULL, sizeof(executable), PROT_READ | PROT_WRITE | PROT_EXEC,
        MAP_PRIVATE | MAP_ANON, -1, 0);
    memcpy(buf, sizeof(executable);
    __builtin___clear_cache(buf, buf + sizeof(executable) - 1);

    int i = ((int (*) (void)buf)();
    return 0;
}
</code>```

when compiled and run, the terminal displays Segmentation fault.

Second attempt

Another method I tried is by using ld which also displayed Segmentation fault:

embedded.c:

```<code>extern const char _binary_executable_start[];
extern const char _binary_executable_end[];

// And same as the previous code.
</code>```

The code was compiled using:

gcc -c -o embedded.o embedded.c

ld -r -b binary -o executable.o executable

gcc -o embedded embedded.o executable.o

And failed.

Is there anything I missed or is it impossible to embed binary file into C code and run it?

答:
If you want to execute directly an executable from your running program (system(3) library function spawns a shell to run it) you can use the same system calls that were used to run your binary (the one you are executing and whishes to execute a binary)

In unix, you need first to create a second process, which is normally a twin (in the exact same state of execution) with the fork(2) system call.  The fork(2) makes the difference between parent and child processes, by returning a different value to each (it returns the pid of the child to the parent, and 0 to the child)  So, from that point on, you can follow different paths in your execution, based on the return value.

Normally, the parent and child then arrange for input/output redirection, which means to substitute the 0, 1 and 2 open file descriptors to do the redirection, and then the memory of the child process is overlaid with a new executable, that is loaded in place by the kernel, with the execve(2) family of system calls.  There's no more secure method than this.  I don't fully understand what do you mean with secure, but if you are not able to execute a program with this method, then nothing else can be done.

Your method of loading yourself a binary in memory and try to run it yourself, is not only error prone, but also is not portable.  Compiling a source file, as already commented in other answers, is not the solution, as that requires you to first understand the whole process of loading an executable in general  unix systems.  An executable has some text segment (normally it is read-only to make the executable code shareable between different processes running the same program), a read-write data segment (that grows on request by issuing a system call for it) and a stack segment (per thread) that usually grows automatically, when references to it are being made by the cpu.

So you have to deal with all of this, it is not as easy as on a simple processor, where all the memory is available for use.  You have to ask the operating system for the memory you'll be using to run your program.  Think for example, that executable code in Intel processors don't need even to be readable memory (only when loaded to the cpu as an instruction, the read memory operation succeeds, but if you try to read the data as data, you'll generate a trap)

Conclussion

Read about the fork(2) and exec(2) system calls in your linux manual, and a basic unix programming manual, to get a good introduction on how to execute programs in unix.

Body:
I am trying to execute a binary executable file inside C code without using system since it has security and resource management issues.

The system used here is Debian Buster with kernel 5.4.0-2-amd64 and gcc 9.2.1.

I used the method in this question:
execute binary machine code from C

which is to convert executable into hexadecimal code with xxd -i, but constantly get Segmentation fault.

The procedures I used are:

First attempt

executable.c:

#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
    return 0;
}

after compiling it with gcc -o executable executable.c

xxd -i executable will display binary file into hex

Then copy and paste the output to embedded.c

embedded.c:

#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

const unsigned char[] executable = {
    0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01,
    ...
};

int main(void)
{
    void *buf = mmap(
        NULL, sizeof(executable), PROT_READ | PROT_WRITE | PROT_EXEC,
        MAP_PRIVATE | MAP_ANON, -1, 0);
    memcpy(buf, sizeof(executable);
    __builtin___clear_cache(buf, buf + sizeof(executable) - 1);

    int i = ((int (*) (void)buf)();
    return 0;
}

when compiled and run, the terminal displays Segmentation fault.

Second attempt

Another method I tried is by using ld which also displayed Segmentation fault:

embedded.c:

extern const char _binary_executable_start[];
extern const char _binary_executable_end[];

// And same as the previous code.

The code was compiled using:

gcc -c -o embedded.o embedded.c

ld -r -b binary -o executable.o executable

gcc -o embedded embedded.o executable.o

And failed.

Is there anything I missed or is it impossible to embed binary file into C code and run it?


来源: stackexchange

问:
How to exclude "others" in my pie chart in Data Studio
I have a pie chart in Data Studio as below:

As you can see from the donut, there is "others" slice which I don't want to see it there, and I want to customize the label to show "python (88%)".

Can anyone share your expertise and enlighten me on how to do it?

Thank you very much.

UPDATE

Following @Jaishree's suggestion, I have selected only the top 10, so there is no "others" now.

however, I still don't get it on how to show the label as "python (88%)"

As you can see, I have two fields in my data source (the table on the left): Category and TagsTotal. There is NO percentage_field.

To show "percentage", all I need to do is switch to "percentage" in the STYLE option:

What I ended up of creating this customized labeling is detailed below for future readers:

Back to the data source, create another field pctg:

round((TagsTotal * 100 / (Select Sum(TagsTotal) From cte)),2) as pctg

for the donut chart, create a new field named my_label

CONCAT(category," (",pctg ,"% )")

add the new field my_label as the Dimension field

change in STYLE to show "label"

Voila!

Very cumbersome but finally kind of working with the rest to be sorted out:

1. The newly created field is not showing up in the right-side panel as an available field and how to modify it?

2. The legend needs to be customized to display two lines instead of showing a pagina

答:
In Pie chart and donuts chart you can only show 20 slices. The chart shows the results in a sorted way. If you do not want to see others, then you have select only 20 data points.

"python (88%)" If you want to show the labels as "python (88%)" you can add a new field and customize the labels as you want.
You can do that by click on "create new field " then "add new field" and then give a name to the new field in formula type the below code:

```<code>CONCAT(category," (",percentage_field,"% )")
</code>```

To use the above formula you have to create a percentage_field also before, in the same way with percentage formula.

ContentLicense: CC BY-SA 4.0

Body:
In Pie chart and donuts chart you can only show 20 slices. The chart shows the results in a sorted way. If you do not want to see others, then you have select only 20 data points.

"python (88%)" If you want to show the labels as "python (88%)" you can add a new field and customize the labels as you want.
You can do that by click on "create new field " then "add new field" and then give a name to the new field in formula type the below code:

CONCAT(category," (",percentage_field,"% )")

To use the above formula you have to create a percentage_field also before, in the same way with percentage formula.


问:
select sub dataset with specific conditions without using apply & subset functions
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

```<code> #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA
</code>```

I would like to do this work without apply and subset functions.

The final dataset that I would like to have is

```<code>#    name  age income
# 1 alicia 40  100
# 2 jessie 28  60
</code>```

By the way, someone can explain me why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

答:
We can use subset from base R

```<code>subset(df,  age >=0 & income <= 100)
</code>```

Body:
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

 #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA

I would like to do this work without apply and subset functions.

The final dataset that I would like to have is

#    name  age income
# 1 alicia 40  100
# 2 jessie 28  60

By the way, someone can explain me why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

Body:
We can use subset from base R

subset(df,  age >=0 & income <= 100)


问:
Converting rows into columns and columns into rows using R
I have a dataframe with unique row names and unique column names. I want to convert the rows into columns and column into rows.

For example, this code:

```<code>starting_df <- data.frame(row.names= c(LETTERS[1:4]),
                          a = c(1:4),
                          b = seq(0.02,0.08,by=0.02),
                          c = c("Aaaa","Bbbb","Cccc","Dddd")
                )
</code>```

results in the following:

```<code>> starting_df
  a    b    c
A 1 0.02 Aaaa
B 2 0.04 Bbbb
C 3 0.06 Cccc
D 4 0.08 Dddd
</code>```

I want to convert it into another data frame containing exactly the same data, except that what were formerly rows were now columns and vice versa:

```<code>> final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
</code>```

答:
Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

```<code>library(tidyverse)

starting_df %>%
  rownames_to_column() %>%
  gather(variable, value, -rowname) %>%
  spread(rowname, value)
</code>```

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

```<code>smiths %>%
    gather(variable, value, -subject) %>%
    spread(subject, value)
</code>```

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE is added,
whereas the tidyverse option converts everything to a character by default if
there are mixed column types.

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe with unique row names and unique column names. I want to convert the rows into columns and column into rows.

For example, this code:

starting_df <- data.frame(row.names= c(LETTERS[1:4]),
                          a = c(1:4),
                          b = seq(0.02,0.08,by=0.02),
                          c = c("Aaaa","Bbbb","Cccc","Dddd")
                )

results in the following:

> starting_df
  a    b    c
A 1 0.02 Aaaa
B 2 0.04 Bbbb
C 3 0.06 Cccc
D 4 0.08 Dddd

I want to convert it into another data frame containing exactly the same data, except that what were formerly rows were now columns and vice versa:

> final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Body:
Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>%
  rownames_to_column() %>%
  gather(variable, value, -rowname) %>%
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>%
    gather(variable, value, -subject) %>%
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE is added,
whereas the tidyverse option converts everything to a character by default if
there are mixed column types.


问:
Large set of data in QTableView
I am trying to add large sets of data in QTableView. As there is huge set of data, in order to avoid freezing the application, I am trying to use a QAbstractTableModel to not showthe whole dataset immediately, but only what is necessary. Based on the QT example for this (HERE), I have the following class:
FileListModel.cpp

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

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), fileCount(0) //edit
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : fileCount;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList.size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList.at(index.row());
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (fileCount < fileList.size());
}
int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colCount;
}
void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList.size() - fileCount;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), fileCount, fileCount + itemsToFetch - 1);
    qDebug()<< "Qmodelindex "<< QModelIndex()<< "filecount "<< fileCount <<"filecount + itemtofetch "<<fileCount + itemsToFetch - 1;
    fileCount += itemsToFetch;

    endInsertRows();
}
void FileListModel::setColumnNumber(const int x) //edit
{
    colCount = x;
}
void FileListModel::setDataToList(const QList<float> &data)
{
    beginResetModel();
    fileList = data;
    fileCount = 0;
    endResetModel();
}
</code>```

FileListModel.h

```<code>#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractTableModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel //edit
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override; //edit
    void setColumnNumber(const int );

public slots:
    void setDataToList(const QList<float>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<float> fileList;
    int fileCount;
int colCount;//edit
};

#endif // FILELISTMODEL_H
</code>```

In my window, I have a QTableView and 5 QList<float>, each representing a column.
I proceed this way to add the data in my QTableView:

```<code>FileListModel *model=new FileListModel(this);
model->setColumnNumber(5); //edit

model->setDataToList(list1);
model->setDataToList(list2);
model->setDataToList(list3);
model->setDataToList(list4);
model->setDataToList(list5);

tableview->setModel(model)
</code>```

However, the last list added (list5) replace the previous one and I have only the same text in all the columns. I am aware that I need to write the needed code to add columns. But to be honest, I am not knowing very well the QAbstract classes, and have no idea how to proceed. I would be grateful if you could provide me some hints or an example on how to modify my code in order to add columns in my model.

答:
I found how to proceed by storing my data in a QList>.
Please find below a working code that can probably be improved:

CPP FILE

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

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), rowNumber(0)
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : rowNumber;
}

int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colNumber;
}

void FileListModel::setColumnNumber(const int x)
{
    colNumber = x;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList[0].size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList[index.column()][index.row()];
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (rowNumber < fileList[0].size());
}

void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList[0].size() - rowNumber;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), rowNumber, rowNumber + itemsToFetch - 1);

    rowNumber += itemsToFetch;

    endInsertRows();
}

void FileListModel::setDataToTable(const QList<QList<float>> &data)
{
    beginResetModel();
    fileList = data;
    rowNumber = 0;
    endResetModel();
}
</code>```

H FILE

```<code>#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractListModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    void setColumnNumber(const int );
    void setDataToTable(const QList<QList<float>>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<QList<float>> fileList;
    int rowNumber;
    int colNumber;
};

#endif // FILELISTMODEL_H
</code>```

BUILDING MODEL

```<code>FileListModel *pModel =new FileListModel(this);
QList<QList<float>> a;
pModel->setColumnNumber(5);
a.append(qlist1);
a.append(qlist2);
a.append(qlist3);
a.append(qlist4);
a.append(qlist5);
pModel->setDataToTable(a);
</code>```

Title: Large set of data in QTableView

Body:
I am trying to add large sets of data in QTableView. As there is huge set of data, in order to avoid freezing the application, I am trying to use a QAbstractTableModel to not showthe whole dataset immediately, but only what is necessary. Based on the QT example for this (HERE), I have the following class:
FileListModel.cpp

#include "filelistmodel.h"

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), fileCount(0) //edit
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : fileCount;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList.size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList.at(index.row());
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (fileCount < fileList.size());
}
int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colCount;
}
void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList.size() - fileCount;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), fileCount, fileCount + itemsToFetch - 1);
    qDebug()<< "Qmodelindex "<< QModelIndex()<< "filecount "<< fileCount <<"filecount + itemtofetch "<<fileCount + itemsToFetch - 1;
    fileCount += itemsToFetch;

    endInsertRows();
}
void FileListModel::setColumnNumber(const int x) //edit
{
    colCount = x;
}
void FileListModel::setDataToList(const QList<float> &data)
{
    beginResetModel();
    fileList = data;
    fileCount = 0;
    endResetModel();
}

FileListModel.h

#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractTableModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel //edit
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override; //edit
    void setColumnNumber(const int );

public slots:
    void setDataToList(const QList<float>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<float> fileList;
    int fileCount;
int colCount;//edit
};

#endif // FILELISTMODEL_H

In my window, I have a QTableView and 5 QList<float>, each representing a column.
I proceed this way to add the data in my QTableView:

FileListModel *model=new FileListModel(this);
model->setColumnNumber(5); //edit

model->setDataToList(list1);
model->setDataToList(list2);
model->setDataToList(list3);
model->setDataToList(list4);
model->setDataToList(list5);

tableview->setModel(model)

However, the last list added (list5) replace the previous one and I have only the same text in all the columns. I am aware that I need to write the needed code to add columns. But to be honest, I am not knowing very well the QAbstract classes, and have no idea how to proceed. I would be grateful if you could provide me some hints or an example on how to modify my code in order to add columns in my model.

Body:
I found how to proceed by storing my data in a QList>.
Please find below a working code that can probably be improved:

CPP FILE

#include "filelistmodel.h"

#include <QGuiApplication>
#include <QDir>
#include <QPalette>
#include "qdebug.h"

FileListModel::FileListModel(QObject *parent)
    : QAbstractTableModel(parent), rowNumber(0)
{}

int FileListModel::rowCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : rowNumber;
}

int FileListModel::columnCount(const QModelIndex &parent) const
{
    return parent.isValid() ? 0 : colNumber;
}

void FileListModel::setColumnNumber(const int x)
{
    colNumber = x;
}

QVariant FileListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }
    if (index.row() >= fileList[0].size() || index.row() < 0)
    {
        return QVariant();
    }
    if (role == Qt::DisplayRole)
    {
        return fileList[index.column()][index.row()];
    }
    return QVariant();
}

bool FileListModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return false;
    }
    return (rowNumber < fileList[0].size());
}

void FileListModel::fetchMore(const QModelIndex &parent)
{
    if (parent.isValid())
    {
        return;
    }
    int remainder = fileList[0].size() - rowNumber;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
    {
        return;
    }
    beginInsertRows(QModelIndex(), rowNumber, rowNumber + itemsToFetch - 1);

    rowNumber += itemsToFetch;

    endInsertRows();
}

void FileListModel::setDataToTable(const QList<QList<float>> &data)
{
    beginResetModel();
    fileList = data;
    rowNumber = 0;
    endResetModel();
}

H FILE

#ifndef FILELISTMODEL_H
#define FILELISTMODEL_H

#include <QAbstractListModel>
#include <QStringList>

class FileListModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    FileListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    void setColumnNumber(const int );
    void setDataToTable(const QList<QList<float>>&);

protected:
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;

private:
    QList<QList<float>> fileList;
    int rowNumber;
    int colNumber;
};

#endif // FILELISTMODEL_H

BUILDING MODEL

FileListModel *pModel =new FileListModel(this);
QList<QList<float>> a;
pModel->setColumnNumber(5);
a.append(qlist1);
a.append(qlist2);
a.append(qlist3);
a.append(qlist4);
a.append(qlist5);
pModel->setDataToTable(a);


问:
The control does not flow beyond 45th line
The question is as follows.

Q) Develop a function f1 to accept an integer argument, reverse the digits and return the reversed value. Also, develop another function f2 to accept two integer arguments x and n and to return the value of x raised to the power n. The return value of f2 should be passed on to f1 and the return value of f1 must be checked whether it is prime or not by another function f3. The result must be printed in the program.

The control does not flow beyond the 45th line in this code. I do not really know what it the issue here because when i run the code in code blocks, the output screen displays the output of f2 and then it remains idle. for example, if i give the input as 8 and 2, then the output returns a value of 81 and then it does not do anything beyond that.

```<code>    #include <stdio.h>
    #include <math.h>
    int f1(int npow)
    {
        int ret=0;
        while (npow>0)
        {
            ret=(ret*10)+(npow%10);
        }
        return ret;
    }
    int f2(int x,int n)
    {
        int res;
        res=pow(x,n);
        return res;
    }
    int f3(int resrev)
    {
        int i,check;
        for (i=2;i<resrev;i++)
        {
            if (resrev%i==0)
            {
                check =1;
                break;
            }
            else
            {
                check=0;
                break;
            }
        }
        return check;
    }
    void main()
    {
        int resrev,x,n,npow,prime;
        printf("Enter two numbers x and n\n");
        scanf("%d %d",&x,&n);
        npow=f2(x,n);
        printf("x to the power n is %d\n",npow);
        resrev=f1(npow);
        printf("Reversed value of x to the power n is %d \n",resrev);
        prime=f3(resrev);
        if (prime==1)
            printf("It is not a prime number \n");
        else
            printf("It is a prime number\n");
    }
</code>```

答:
Problem is in function f1. It is an infinite loop.

Loop condition is until npow>0 but you are not updating value of npow in the loop.
Following is corrected code:

```<code>int f1(int npow)
{
    int ret=0;
    while (npow>0)
    {
        ret=(ret*10)+(npow%10);
        npow = npow/10;
    }
    return ret;
}
</code>```

Body:
The question is as follows.

Q) Develop a function f1 to accept an integer argument, reverse the digits and return the reversed value. Also, develop another function f2 to accept two integer arguments x and n and to return the value of x raised to the power n. The return value of f2 should be passed on to f1 and the return value of f1 must be checked whether it is prime or not by another function f3. The result must be printed in the program.

The control does not flow beyond the 45th line in this code. I do not really know what it the issue here because when i run the code in code blocks, the output screen displays the output of f2 and then it remains idle. for example, if i give the input as 8 and 2, then the output returns a value of 81 and then it does not do anything beyond that.

    #include <stdio.h>
    #include <math.h>
    int f1(int npow)
    {
        int ret=0;
        while (npow>0)
        {
            ret=(ret*10)+(npow%10);
        }
        return ret;
    }
    int f2(int x,int n)
    {
        int res;
        res=pow(x,n);
        return res;
    }
    int f3(int resrev)
    {
        int i,check;
        for (i=2;i<resrev;i++)
        {
            if (resrev%i==0)
            {
                check =1;
                break;
            }
            else
            {
                check=0;
                break;
            }
        }
        return check;
    }
    void main()
    {
        int resrev,x,n,npow,prime;
        printf("Enter two numbers x and n\n");
        scanf("%d %d",&x,&n);
        npow=f2(x,n);
        printf("x to the power n is %d\n",npow);
        resrev=f1(npow);
        printf("Reversed value of x to the power n is %d \n",resrev);
        prime=f3(resrev);
        if (prime==1)
            printf("It is not a prime number \n");
        else
            printf("It is a prime number\n");
    }

Body:
Problem is in function f1. It is an infinite loop.

Loop condition is until npow>0 but you are not updating value of npow in the loop.
Following is corrected code:

int f1(int npow)
{
    int ret=0;
    while (npow>0)
    {
        ret=(ret*10)+(npow%10);
        npow = npow/10;
    }
    return ret;
}


问:
Jumping scrolling when switching fragments
Inside a ScrollView I am dynamically switching between two fragments with different heights.
Unfortunately that leads to jumping. One can see it in the following animation:

I am scrolling down until I reach the button "show yellow".

Pressing "show yellow" replaces a huge blue fragment with a tiny yellow fragment. When this happens, both buttons jump down to the end of the screen.

I want both buttons to stay at the same position when switching to the yellow fragment. How can that be done?

Source code available at https://github.com/wondering639/stack-dynamiccontent respectively https://github.com/wondering639/stack-dynamiccontent.git

Relevant code snippets:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="800dp"
        android:background="@color/colorAccent"
        android:text="@string/long_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_fragment1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:text="show blue"
        app:layout_constraintEnd_toStartOf="@+id/button_fragment2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_fragment2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="show yellow"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button_fragment1"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/button_fragment2">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

MainActivity.kt

```<code>package com.example.dynamiccontent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // onClick handlers
        findViewById<Button>(R.id.button_fragment1).setOnClickListener {
            insertBlueFragment()
        }

        findViewById<Button>(R.id.button_fragment2).setOnClickListener {
            insertYellowFragment()
        }

        // by default show the blue fragment
        insertBlueFragment()
    }

    private fun insertYellowFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, YellowFragment())
        transaction.commit()
    }

    private fun insertBlueFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, BlueFragment())
        transaction.commit()
    }

}
</code>```

fragment_blue.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#0000ff"
tools:context=".BlueFragment" />
</code>```

fragment_yellow.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ffff00"
tools:context=".YellowFragment" />
</code>```

HINT

Please note that this is of course a minimum working example to show off my issue. In my real project, I also have views below the @+id/fragment_container. So giving a fixed size to @+id/fragment_container is not an option for me - it would cause a large blank area when switching to the low, yellow fragment.

UPDATE: Overview of proposed solutions

I implemented the proposed solutions for testing purposes and added my personal experiences with them.

answer by Cheticamp, https://stackoverflow.com/a/60323255

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60323255

-> FrameLayout wraps content, short code

answer by Pavneet_Singh, https://stackoverflow.com/a/60310807

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60310807

-> FrameLayout gets the size of the blue fragment. So no content wrapping. When switching to the yellow fragment, there's a gap between it and the content following it (if any content follows it). No additional rendering though!
** update ** a second version was provided showing how to do it without gaps. Check the comments to the answer.

answer by Ben P., https://stackoverflow.com/a/60251036

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60251036

-> FrameLayout wraps content. More code than the solution by Cheticamp. Touching the "show yellow" button twice leads to a "bug" (buttons jump down to the bottom, actually my original issue). One could argue about just disabling the "show yellow" button after switching to it, so I wouldn't consider this a real issue.

答:
I solved this by creating a layout listener that keeps track of the "previous" height and adds padding to the ScrollView if the new height is less than before.

HeightLayoutListener.kt

```<code>class HeightLayoutListener(
        private val activity: MainActivity,
        private val root: View,
        private val previousHeight: Int,
        private val targetScroll: Int
) : ViewTreeObserver.OnGlobalLayoutListener {

    override fun onGlobalLayout() {
        root.viewTreeObserver.removeOnGlobalLayoutListener(this)

        val padding = max((previousHeight - root.height), 0)
        activity.setPaddingBottom(padding)
        activity.setScrollPosition(targetScroll)
    }

    companion object {

        fun create(fragment: Fragment): HeightLayoutListener {
            val activity = fragment.activity as MainActivity
            val root = fragment.view!!
            val previousHeight = fragment.requireArguments().getInt("height")
            val targetScroll = fragment.requireArguments().getInt("scroll")

            return HeightLayoutListener(activity, root, previousHeight, targetScroll)
        }
    }
}
</code>```

To enable this listener, add this method to both of your fragments:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val listener = HeightLayoutListener.create(this)
    view.viewTreeObserver.addOnGlobalLayoutListener(listener)
}
</code>```

These are the methods that the listener calls in order to actually update the ScrollView. Add them to your activity:

```<code>fun setPaddingBottom(padding: Int) {
    val wrapper = findViewById<View>(R.id.wrapper) // add this ID to your ConstraintLayout
    wrapper.setPadding(0, 0, 0, padding)

    val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(wrapper.width, View.MeasureSpec.EXACTLY)
    val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    wrapper.measure(widthMeasureSpec, heightMeasureSpec)
    wrapper.layout(0, 0, wrapper.measuredWidth, wrapper.measuredHeight)
}

fun setScrollPosition(scrollY: Int) {
    val scroll = findViewById<NestedScrollView>(R.id.myScrollView)
    scroll.scrollY = scrollY
}
</code>```

And you need to set arguments to your fragments in order for the listener to know what the previous height and the previous scroll position were. So make sure to add them to your fragment transactions:

```<code>private fun insertYellowFragment() {
    val fragment = YellowFragment().apply {
        this.arguments = createArgs()
    }

    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, fragment)
    transaction.commit()
}

private fun insertBlueFragment() {
    val fragment = BlueFragment().apply {
        this.arguments = createArgs()
    }

    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, fragment)
    transaction.commit()
}

private fun createArgs(): Bundle {
    val scroll = findViewById<NestedScrollView>(R.id.myScrollView)
    val container = findViewById<View>(R.id.fragment_container)

    return Bundle().apply {
        putInt("scroll", scroll.scrollY)
        putInt("height", container.height)
    }
}
</code>```

And that should do it!

Body:
Inside a ScrollView I am dynamically switching between two fragments with different heights.
Unfortunately that leads to jumping. One can see it in the following animation:

I am scrolling down until I reach the button "show yellow".

Pressing "show yellow" replaces a huge blue fragment with a tiny yellow fragment. When this happens, both buttons jump down to the end of the screen.

I want both buttons to stay at the same position when switching to the yellow fragment. How can that be done?

Source code available at https://github.com/wondering639/stack-dynamiccontent respectively https://github.com/wondering639/stack-dynamiccontent.git

Relevant code snippets:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="800dp"
        android:background="@color/colorAccent"
        android:text="@string/long_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_fragment1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:text="show blue"
        app:layout_constraintEnd_toStartOf="@+id/button_fragment2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_fragment2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="show yellow"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button_fragment1"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/button_fragment2">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.example.dynamiccontent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // onClick handlers
        findViewById<Button>(R.id.button_fragment1).setOnClickListener {
            insertBlueFragment()
        }

        findViewById<Button>(R.id.button_fragment2).setOnClickListener {
            insertYellowFragment()
        }

        // by default show the blue fragment
        insertBlueFragment()
    }

    private fun insertYellowFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, YellowFragment())
        transaction.commit()
    }

    private fun insertBlueFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, BlueFragment())
        transaction.commit()
    }

}

fragment_blue.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#0000ff"
tools:context=".BlueFragment" />

fragment_yellow.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ffff00"
tools:context=".YellowFragment" />

HINT

Please note that this is of course a minimum working example to show off my issue. In my real project, I also have views below the @+id/fragment_container. So giving a fixed size to @+id/fragment_container is not an option for me - it would cause a large blank area when switching to the low, yellow fragment.

UPDATE: Overview of proposed solutions

I implemented the proposed solutions for testing purposes and added my personal experiences with them.

answer by Cheticamp, https://stackoverflow.com/a/60323255

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60323255

-> FrameLayout wraps content, short code

answer by Pavneet_Singh, https://stackoverflow.com/a/60310807

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60310807

-> FrameLayout gets the size of the blue fragment. So no content wrapping. When switching to the yellow fragment, there's a gap between it and the content following it (if any content follows it). No additional rendering though!
** update ** a second version was provided showing how to do it without gaps. Check the comments to the answer.

answer by Ben P., https://stackoverflow.com/a/60251036

-> available in https://github.com/wondering639/stack-dynamiccontent/tree/60251036

-> FrameLayout wraps content. More code than the solution by Cheticamp. Touching the "show yellow" button twice leads to a "bug" (buttons jump down to the bottom, actually my original issue). One could argue about just disabling the "show yellow" button after switching to it, so I wouldn't consider this a real issue.

Body:
I solved this by creating a layout listener that keeps track of the "previous" height and adds padding to the ScrollView if the new height is less than before.

HeightLayoutListener.kt

class HeightLayoutListener(
        private val activity: MainActivity,
        private val root: View,
        private val previousHeight: Int,
        private val targetScroll: Int
) : ViewTreeObserver.OnGlobalLayoutListener {

    override fun onGlobalLayout() {
        root.viewTreeObserver.removeOnGlobalLayoutListener(this)

        val padding = max((previousHeight - root.height), 0)
        activity.setPaddingBottom(padding)
        activity.setScrollPosition(targetScroll)
    }

    companion object {

        fun create(fragment: Fragment): HeightLayoutListener {
            val activity = fragment.activity as MainActivity
            val root = fragment.view!!
            val previousHeight = fragment.requireArguments().getInt("height")
            val targetScroll = fragment.requireArguments().getInt("scroll")

            return HeightLayoutListener(activity, root, previousHeight, targetScroll)
        }
    }
}

To enable this listener, add this method to both of your fragments:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val listener = HeightLayoutListener.create(this)
    view.viewTreeObserver.addOnGlobalLayoutListener(listener)
}

These are the methods that the listener calls in order to actually update the ScrollView. Add them to your activity:

fun setPaddingBottom(padding: Int) {
    val wrapper = findViewById<View>(R.id.wrapper) // add this ID to your ConstraintLayout
    wrapper.setPadding(0, 0, 0, padding)

    val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(wrapper.width, View.MeasureSpec.EXACTLY)
    val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    wrapper.measure(widthMeasureSpec, heightMeasureSpec)
    wrapper.layout(0, 0, wrapper.measuredWidth, wrapper.measuredHeight)
}

fun setScrollPosition(scrollY: Int) {
    val scroll = findViewById<NestedScrollView>(R.id.myScrollView)
    scroll.scrollY = scrollY
}

And you need to set arguments to your fragments in order for the listener to know what the previous height and the previous scroll position were. So make sure to add them to your fragment transactions:

private fun insertYellowFragment() {
    val fragment = YellowFragment().apply {
        this.arguments = createArgs()
    }

    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, fragment)
    transaction.commit()
}

private fun insertBlueFragment() {
    val fragment = BlueFragment().apply {
        this.arguments = createArgs()
    }

    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, fragment)
    transaction.commit()
}

private fun createArgs(): Bundle {
    val scroll = findViewById<NestedScrollView>(R.id.myScrollView)
    val container = findViewById<View>(R.id.fragment_container)

    return Bundle().apply {
        putInt("scroll", scroll.scrollY)
        putInt("height", container.height)
    }
}

And that should do it!


问:
Create Group from Sequences
How can I create a "group" vector that identifies sequences of same values in another vector.

From this

```<code>x <- c(0,1,0,0,1,0,1)
</code>```

I want to create this

```<code>outcome <- c(1,2,3,3,4,5,6)

[1] 0 1 0 0 1 0 1
[1] 1 2 3 3 4 5 6
</code>```

So, whenever there is a new sequence of the same values there is a new group number (or can be something other than a number as well).

I would actually know ways to get there, but they are all hideous. The best I can come up with is

```<code>comparison <- x != lag(x)
cumsum(replace_na(comparison, TRUE))
</code>```

but like I said - hideous. There must be a better way and I hope someone knows it.

答:
We can use rleid from data.table

```<code>library(data.table)
rleid(x)
#[1] 1 2 3 3 4 5 6
</code>```

Or in base R with rle

```<code>with(rle(x), rep(seq_along(values), lengths))
#[1] 1 2 3 3 4 5 6
</code>```

Or if we use the similar approach from OP

```<code>1 + cumsum(x != dplyr::lag(x, default = first(x)))
</code>```

Title: Create Group from Sequences

Body:
How can I create a "group" vector that identifies sequences of same values in another vector.

From this

x <- c(0,1,0,0,1,0,1)

I want to create this

outcome <- c(1,2,3,3,4,5,6)

[1] 0 1 0 0 1 0 1
[1] 1 2 3 3 4 5 6

So, whenever there is a new sequence of the same values there is a new group number (or can be something other than a number as well).

I would actually know ways to get there, but they are all hideous. The best I can come up with is

comparison <- x != lag(x)
cumsum(replace_na(comparison, TRUE))

but like I said - hideous. There must be a better way and I hope someone knows it.

Body:
We can use rleid from data.table

library(data.table)
rleid(x)
#[1] 1 2 3 3 4 5 6

Or in base R with rle

with(rle(x), rep(seq_along(values), lengths))
#[1] 1 2 3 3 4 5 6

Or if we use the similar approach from OP

1 + cumsum(x != dplyr::lag(x, default = first(x)))


问:
How to mock variable responses based on the url when fetch(url) is called using the Jest testing framework?
I have a module that looks like follows:

calculate-average.js

```<code>const fetch = require('node-fetch')
const stats = require('stats-lite')
const BASE_URL = 'https://www.example.com/api'

const calculateAverage = async(numApiCalls) => {
  const importantData = []

  for (let i = 0; i < numApiCalls; i++) {
      const url = `${BASE_URL}/${i}` // will make requests to https://www.example.com/api/0, https://www.example.com/api/1 and so on....
      const res = await fetch(url)
      const jsonRes = await res.json()

      importantData.push(jsonRes.importantData)
  }

  return stats.mean(importantData)
}

module.exports = calculateAverage
</code>```

I tried testing it along the following lines but I am clearly way off from the solution:

calculate-average.test.js

```<code>const calculateAverage = require('../calculate-average')

jest.mock(
    'node-fetch',
    () => {
        return jest.fn(() => {})
    }
)

test('Should calculate stats for liquidation open interest delatas', async() => {
    const stats = await calculateAverage(100) // Should make 100 API calls.

    console.log(stats)
})
</code>```

What I need to do is the following:

Be able to specify custom varied responses for each API call. For example, I should be able to specify that a call to https://www.example.com/api/0 returns { importantData: 0 }, a call to https://www.example.com/api/1 returns { importantData: 1 } and so on...

If a request is made to a url that I have not specified a response for, a default response is provided. For example if a response is made to https://www.example.com/api/101, then a default response of { importantData: 1000 } is sent.

I would preferably like to do this only using Jest without depending on modules like mock-fetch and jest-mock-fetch. However, if the solution without using is way too complex, then I would be happy to use them. Just don't want to create unnecessary dependencies if not required.

答:
Sure you can! You can use mock function mockResolvedValueOnce method to return a result for a specific call and mockResolvedValue to return the default result.

```<code>jest.mock('node-fetch', () => {
    const generateResponse = (value) => {
        return { json: () => ({ importantData: value }) };
    };

    return jest
        .fn()
        .mockResolvedValue(generateResponse(1000)) // default response
        .mockResolvedValueOnce(generateResponse(0)) // response for first call
        .mockResolvedValueOnce(generateResponse(1)) // response for second call
        .mockResolvedValueOnce(generateResponse(2)); // response for third call
});
</code>```

Note that we are returning an object with the json property so that it returns the json data when you call res.json() in calculate-average.js.

If you want to return a specific response based on the url parameter, you will have to mock the desired behaviour in the returned mock function for node-fetch. The following example will mock the returned value so that for URLs where the counter is greater than 100 it will return 1000. Otherwise, it will return the same value present in the url:

```<code>jest.mock('node-fetch', () => {
    return jest.fn((url) => {
        // Get and parse the URL parameter.
        const value = parseInt(url.split('/').slice(-1)[0], 10);

        return Promise.resolve({
            json: () => ({ importantData: value > 100 ? 1000 : value })
        });
    });
});
</code>```

Body:
I have a module that looks like follows:

calculate-average.js

const fetch = require('node-fetch')
const stats = require('stats-lite')
const BASE_URL = 'https://www.example.com/api'

const calculateAverage = async(numApiCalls) => {
  const importantData = []

  for (let i = 0; i < numApiCalls; i++) {
      const url = `${BASE_URL}/${i}` // will make requests to https://www.example.com/api/0, https://www.example.com/api/1 and so on....
      const res = await fetch(url)
      const jsonRes = await res.json()

      importantData.push(jsonRes.importantData)
  }

  return stats.mean(importantData)
}

module.exports = calculateAverage

I tried testing it along the following lines but I am clearly way off from the solution:

calculate-average.test.js

const calculateAverage = require('../calculate-average')

jest.mock(
    'node-fetch',
    () => {
        return jest.fn(() => {})
    }
)

test('Should calculate stats for liquidation open interest delatas', async() => {
    const stats = await calculateAverage(100) // Should make 100 API calls.

    console.log(stats)
})

What I need to do is the following:

Be able to specify custom varied responses for each API call. For example, I should be able to specify that a call to https://www.example.com/api/0 returns { importantData: 0 }, a call to https://www.example.com/api/1 returns { importantData: 1 } and so on...

If a request is made to a url that I have not specified a response for, a default response is provided. For example if a response is made to https://www.example.com/api/101, then a default response of { importantData: 1000 } is sent.

I would preferably like to do this only using Jest without depending on modules like mock-fetch and jest-mock-fetch. However, if the solution without using is way too complex, then I would be happy to use them. Just don't want to create unnecessary dependencies if not required.

Body:
Sure you can! You can use mock function mockResolvedValueOnce method to return a result for a specific call and mockResolvedValue to return the default result.

jest.mock('node-fetch', () => {
    const generateResponse = (value) => {
        return { json: () => ({ importantData: value }) };
    };

    return jest
        .fn()
        .mockResolvedValue(generateResponse(1000)) // default response
        .mockResolvedValueOnce(generateResponse(0)) // response for first call
        .mockResolvedValueOnce(generateResponse(1)) // response for second call
        .mockResolvedValueOnce(generateResponse(2)); // response for third call
});

Note that we are returning an object with the json property so that it returns the json data when you call res.json() in calculate-average.js.

If you want to return a specific response based on the url parameter, you will have to mock the desired behaviour in the returned mock function for node-fetch. The following example will mock the returned value so that for URLs where the counter is greater than 100 it will return 1000. Otherwise, it will return the same value present in the url:

jest.mock('node-fetch', () => {
    return jest.fn((url) => {
        // Get and parse the URL parameter.
        const value = parseInt(url.split('/').slice(-1)[0], 10);

        return Promise.resolve({
            json: () => ({ importantData: value > 100 ? 1000 : value })
        });
    });
});


问:
Unexpected for loop result
I'm sure this is a stupid question

but i'm trying to make a select box which show years but this for loop gives me a strange result

```<code><select name="years">
    <?php
        for ( $year=2000; $year <= 2015; $year++ ) {
            echo "<option>{$year}</option>";
        }
    ?>
</select>
</code>```

it gives me 2.0002001200220032e+63

but if i change it like this it works

```<code><select name="years">
    <?php
        for ( $year=0; $year <= 10; $year++ ) {
            echo "<option>$year</option>";
        }
    ?>
</select>
</code>```

can someone explain it to me ?

I have discovered now that the code works on firefox  .. bun not on the chrome

答: I'm soooo sorry ... it is "JSON Viewer" plugin in chrome once i remove it .. every thing works fine ... thank you</p>

Title: Unexpected for loop result

Body:
I'm sure this is a stupid question

but i'm trying to make a select box which show years but this for loop gives me a strange result

<select name="years">
    <?php
        for ( $year=2000; $year <= 2015; $year++ ) {
            echo "<option>{$year}</option>";
        }
    ?>
</select>

it gives me 2.0002001200220032e+63

but if i change it like this it works

<select name="years">
    <?php
        for ( $year=0; $year <= 10; $year++ ) {
            echo "<option>$year</option>";
        }
    ?>
</select>

can someone explain it to me ?

I have discovered now that the code works on firefox  .. bun not on the chrome


问:
JavaFX: How do I add an Image to rectangles that have been initialized in another method?
I made a crude copy of SpaceInvaders to get a feeling for JavaFX and was wondering how I could replace the rectangles I've used as Sprites with graphics.

It works fine with the player sprite and the stage background, but I cant figure out how to replace the red enemy squares with graphics.

I have tried putting the Image Object in the nextLevel() method and filling it into the sprites there, but this gives me only a FileNotFoundException error.

nextLevel() method:

```<code>private void nextLevel() {
// Image img2 = Image(newFileInputStream("C:\\Users\\user\\Pictures\\y.jpg"));

            for (int i = 0; i < 5; i++) {
                Sprite enemy = new Sprite (90 + i*100, 150, 30, 30, "enemy", Color.RED);
//      enemy.setFill(new ImagePattern(img2));

                root.getChildren().add(enemy);
            }
        }
</code>```

I can only initialize the Image in the start method, but then I don't know how to assign it to the enemy square since they have not been initialized yet.
The enemy cannot be resolved yet, even when I put it after the createContent() method, which calls the nextLevel() method and also the Stage.

start method:

```<code>@Override
        public void start(Stage stage) throws Exception {

            Image img2 = new Image(new FileInputStream("C:\\Users\\user\\Pictures\\x.jpg"));
            Image img = new Image(new FileInputStream("C:\\Users\\user\\Pictures\\y.png"));

            player.setFill(new ImagePattern(img));
    // enemy.setFill(new ImagePattern(img2));

            stage.setTitle("Box");
            stage.setResizable(false);

            Scene scene = new Scene(createContent());
            scene.setFill(new ImagePattern(img2));
            scene.setOnKeyPressed(e ->{
                switch (e.getCode()) {
                case A:
                    player.moveLeft();
                    break;
                case D:
                    player.moveRight();
                    break;
                case SPACE:
                    shoot(player);
                    break;
                }
            });

            stage.setScene(scene);
            stage.show();
        }
</code>```

createContent() method:

```<code>    private Parent createContent() {

        root.setPrefSize(600,800);
        root.getChildren().add(player);

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
            }
        };

        timer.start();

        nextLevel();

        return root;
    }
</code>```

If anyone needs it, here is the full code:

```<code>import java.io.FileInputStream;
import java.util.List;
import java.util.stream.Collectors;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class SpaceInvaders extends Application {

    private double t = 0;
    private final Pane root = new Pane();
    private final Sprite player = new Sprite (300,700,80,80, "player",Color.BLUE);

    private Parent createContent() {

        root.setPrefSize(600,800);
        root.getChildren().add(player);

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
            }
        };

        timer.start();
        nextLevel();
        return root;
    }

    private void nextLevel() {

        for (int i = 0; i < 5; i++) {
            Sprite enemy = new Sprite (90 + i*100, 150, 30, 30, "enemy", Color.RED);
            root.getChildren().add(enemy);
        }
    }

    private List<Sprite> sprites(){
        return root.getChildren().stream().map(n -> (Sprite)n).collect(Collectors.toList());
    }
    private void update() {
        t += 0.016;
        sprites().forEach(s -> {
            switch (s.type) {

            case "enemybullet":
                s.moveDown();

                if (s.getBoundsInParent().intersects(player.getBoundsInParent())) {
                    player.dead = true;
                    s.dead = true;
                }
                break;

            case "playerbullet":
                s.moveUp();

                sprites().stream().filter(e -> e.type.equals("enemy")).forEach(enemy ->{
                    if (s.getBoundsInParent().intersects(enemy.getBoundsInParent())) {
                        enemy.dead = true;
                        s.dead = true;
                    }
                });
                break;

            case "enemy":

                if (t > 2) {
                    if (Math.random() < 0.3) {
                        shoot2(s);
                    }
                }

                break;
            }
        });

        root.getChildren().removeIf(n -> {
            Sprite s = (Sprite) n;
            return s.dead;
        });

        if (t > 2) {
            t = 0;
        }
    }

    private void shoot(Sprite who) {
        Sprite s = new Sprite((int) who.getTranslateX() + 40, (int) who.getTranslateY(), 5, 20, who.type + "bullet", Color.BLACK);
        root.getChildren().add(s);
    }

    private void shoot2(Sprite who) {
        Sprite s = new Sprite((int) who.getTranslateX() + 20, (int) who.getTranslateY() + 5, 5, 20, who.type + "bullet", Color.BLACK);
        root.getChildren().add(s);
    }

    @Override
    public void start(Stage stage) throws Exception {

        Image img2 = new Image(new FileInputStream("C:\\Users\\Alexxx\\Pictures\\ibama.jpg"));
        Image img = new Image(new FileInputStream("C:\\Users\\Alexxx\\Pictures\\pinguin.png"));

        player.setFill(new ImagePattern(img));

        stage.setTitle("Nordpol-Defender 2");
        stage.setResizable(false);

        Scene scene = new Scene(createContent());
        scene.setFill(new ImagePattern(img2));
        scene.setOnKeyPressed(e ->{
            switch (e.getCode()) {
            case A:
                player.moveLeft();
                break;
            case D:
                player.moveRight();
                break;
            case SPACE:
                shoot(player);
                break;
            }
        });

        stage.setScene(scene);
        stage.show();
    }

    private static class Sprite extends Rectangle {

        boolean dead = false;
        final String type;

        Sprite(int x, int y, int w, int h, String type, Color colour){
            super(w, h, colour);
            this.type = type;

            setTranslateX(x);
            setTranslateY(y);
        }

        Sprite(int x, int y, int w, int h, String type, Color colour, Image img){
            super(w, h, colour);
            this.type = type;

            setFill(new ImagePattern(img));
            setTranslateX(x);
            setTranslateY(y);
        }

        void moveLeft() {
            setTranslateX(getTranslateX() - 5);
        }

        void moveRight() {
            setTranslateX(getTranslateX() + 5);
        }
        void moveUp() {
            setTranslateY(getTranslateY() - 5);
        }

        void moveDown() {
            setTranslateY(getTranslateY() + 5);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

答:
The following Minimal, Reproducible Example (1) demonstrates changing an image in a Rectangle in run time:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ChangeImageInShape extends Application {

    private int imageSelected = 0;
    private Sprite player;

    private static final String[] fishImages = {
            "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/lg/57/tropical-fish_1f420.png",
            "https://www.shareicon.net/data/128x128/2015/03/28/14104_animal_256x256.png",
            "https://cdn1.iconfinder.com/data/icons/DarkGlass_Reworked/128x128/apps/gnome-fish.png",
            "http://www.iconsalot.com/asset/icons/freepik/pet-shop-13/128/010-fish-2-icon.png"
    };
    private final Image[] images = new Image[fishImages.length];

    @Override
    public void start(Stage stage) throws Exception {

        for(int i = 0 ; i < images.length ; i++){
            images[i] = new Image(fishImages[i]); //loading images takes some time
        }

        player = new Sprite (0,0,80,80, "player",Color.BLUE);
        changeImageInSprite();

        Button btn = new Button("Change Image In Sprite");
        btn.setOnAction(e->changeImageInSprite());

        Pane root = new BorderPane(player, null, null, btn, null);
        root.setPrefSize(300,200);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    private void changeImageInSprite() {
        player.setFill(new ImagePattern(images[imageSelected++]));
        imageSelected = imageSelected >= images.length ?  0 : imageSelected;
    }

    private static class Sprite extends Rectangle {

        Sprite(int x, int y, int w, int h, String type, Color colour){
            super(w, h, colour);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

(1)  It uses publicly available resources, it is a short as possible, and does not represent your application but the problem.

Consider adding mre to question and asnswers.

Body:
I made a crude copy of SpaceInvaders to get a feeling for JavaFX and was wondering how I could replace the rectangles I've used as Sprites with graphics.

It works fine with the player sprite and the stage background, but I cant figure out how to replace the red enemy squares with graphics.

I have tried putting the Image Object in the nextLevel() method and filling it into the sprites there, but this gives me only a FileNotFoundException error.

nextLevel() method:

private void nextLevel() {
// Image img2 = Image(newFileInputStream("C:\\Users\\user\\Pictures\\y.jpg"));

            for (int i = 0; i < 5; i++) {
                Sprite enemy = new Sprite (90 + i*100, 150, 30, 30, "enemy", Color.RED);
//      enemy.setFill(new ImagePattern(img2));

                root.getChildren().add(enemy);
            }
        }

I can only initialize the Image in the start method, but then I don't know how to assign it to the enemy square since they have not been initialized yet.
The enemy cannot be resolved yet, even when I put it after the createContent() method, which calls the nextLevel() method and also the Stage.

start method:

@Override
        public void start(Stage stage) throws Exception {

            Image img2 = new Image(new FileInputStream("C:\\Users\\user\\Pictures\\x.jpg"));
            Image img = new Image(new FileInputStream("C:\\Users\\user\\Pictures\\y.png"));

            player.setFill(new ImagePattern(img));
    // enemy.setFill(new ImagePattern(img2));

            stage.setTitle("Box");
            stage.setResizable(false);

            Scene scene = new Scene(createContent());
            scene.setFill(new ImagePattern(img2));
            scene.setOnKeyPressed(e ->{
                switch (e.getCode()) {
                case A:
                    player.moveLeft();
                    break;
                case D:
                    player.moveRight();
                    break;
                case SPACE:
                    shoot(player);
                    break;
                }
            });

            stage.setScene(scene);
            stage.show();
        }

createContent() method:

    private Parent createContent() {

        root.setPrefSize(600,800);
        root.getChildren().add(player);

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
            }
        };

        timer.start();

        nextLevel();

        return root;
    }

If anyone needs it, here is the full code:

import java.io.FileInputStream;
import java.util.List;
import java.util.stream.Collectors;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class SpaceInvaders extends Application {

    private double t = 0;
    private final Pane root = new Pane();
    private final Sprite player = new Sprite (300,700,80,80, "player",Color.BLUE);

    private Parent createContent() {

        root.setPrefSize(600,800);
        root.getChildren().add(player);

        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
            }
        };

        timer.start();
        nextLevel();
        return root;
    }

    private void nextLevel() {

        for (int i = 0; i < 5; i++) {
            Sprite enemy = new Sprite (90 + i*100, 150, 30, 30, "enemy", Color.RED);
            root.getChildren().add(enemy);
        }
    }

    private List<Sprite> sprites(){
        return root.getChildren().stream().map(n -> (Sprite)n).collect(Collectors.toList());
    }
    private void update() {
        t += 0.016;
        sprites().forEach(s -> {
            switch (s.type) {

            case "enemybullet":
                s.moveDown();

                if (s.getBoundsInParent().intersects(player.getBoundsInParent())) {
                    player.dead = true;
                    s.dead = true;
                }
                break;

            case "playerbullet":
                s.moveUp();

                sprites().stream().filter(e -> e.type.equals("enemy")).forEach(enemy ->{
                    if (s.getBoundsInParent().intersects(enemy.getBoundsInParent())) {
                        enemy.dead = true;
                        s.dead = true;
                    }
                });
                break;

            case "enemy":

                if (t > 2) {
                    if (Math.random() < 0.3) {
                        shoot2(s);
                    }
                }

                break;
            }
        });

        root.getChildren().removeIf(n -> {
            Sprite s = (Sprite) n;
            return s.dead;
        });

        if (t > 2) {
            t = 0;
        }
    }

    private void shoot(Sprite who) {
        Sprite s = new Sprite((int) who.getTranslateX() + 40, (int) who.getTranslateY(), 5, 20, who.type + "bullet", Color.BLACK);
        root.getChildren().add(s);
    }

    private void shoot2(Sprite who) {
        Sprite s = new Sprite((int) who.getTranslateX() + 20, (int) who.getTranslateY() + 5, 5, 20, who.type + "bullet", Color.BLACK);
        root.getChildren().add(s);
    }

    @Override
    public void start(Stage stage) throws Exception {

        Image img2 = new Image(new FileInputStream("C:\\Users\\Alexxx\\Pictures\\ibama.jpg"));
        Image img = new Image(new FileInputStream("C:\\Users\\Alexxx\\Pictures\\pinguin.png"));

        player.setFill(new ImagePattern(img));

        stage.setTitle("Nordpol-Defender 2");
        stage.setResizable(false);

        Scene scene = new Scene(createContent());
        scene.setFill(new ImagePattern(img2));
        scene.setOnKeyPressed(e ->{
            switch (e.getCode()) {
            case A:
                player.moveLeft();
                break;
            case D:
                player.moveRight();
                break;
            case SPACE:
                shoot(player);
                break;
            }
        });

        stage.setScene(scene);
        stage.show();
    }

    private static class Sprite extends Rectangle {

        boolean dead = false;
        final String type;

        Sprite(int x, int y, int w, int h, String type, Color colour){
            super(w, h, colour);
            this.type = type;

            setTranslateX(x);
            setTranslateY(y);
        }

        Sprite(int x, int y, int w, int h, String type, Color colour, Image img){
            super(w, h, colour);
            this.type = type;

            setFill(new ImagePattern(img));
            setTranslateX(x);
            setTranslateY(y);
        }

        void moveLeft() {
            setTranslateX(getTranslateX() - 5);
        }

        void moveRight() {
            setTranslateX(getTranslateX() + 5);
        }
        void moveUp() {
            setTranslateY(getTranslateY() - 5);
        }

        void moveDown() {
            setTranslateY(getTranslateY() + 5);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Body:
The following Minimal, Reproducible Example (1) demonstrates changing an image in a Rectangle in run time:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ChangeImageInShape extends Application {

    private int imageSelected = 0;
    private Sprite player;

    private static final String[] fishImages = {
            "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/lg/57/tropical-fish_1f420.png",
            "https://www.shareicon.net/data/128x128/2015/03/28/14104_animal_256x256.png",
            "https://cdn1.iconfinder.com/data/icons/DarkGlass_Reworked/128x128/apps/gnome-fish.png",
            "http://www.iconsalot.com/asset/icons/freepik/pet-shop-13/128/010-fish-2-icon.png"
    };
    private final Image[] images = new Image[fishImages.length];

    @Override
    public void start(Stage stage) throws Exception {

        for(int i = 0 ; i < images.length ; i++){
            images[i] = new Image(fishImages[i]); //loading images takes some time
        }

        player = new Sprite (0,0,80,80, "player",Color.BLUE);
        changeImageInSprite();

        Button btn = new Button("Change Image In Sprite");
        btn.setOnAction(e->changeImageInSprite());

        Pane root = new BorderPane(player, null, null, btn, null);
        root.setPrefSize(300,200);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    private void changeImageInSprite() {
        player.setFill(new ImagePattern(images[imageSelected++]));
        imageSelected = imageSelected >= images.length ?  0 : imageSelected;
    }

    private static class Sprite extends Rectangle {

        Sprite(int x, int y, int w, int h, String type, Color colour){
            super(w, h, colour);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

(1)  It uses publicly available resources, it is a short as possible, and does not represent your application but the problem.

Consider adding mre to question and asnswers.


答:
Loop inside f1 is infinite as condition to exit while loop is unaltered.

snippet has to be updated as follows,

```<code>int f1(int npow)
{
   int ret=0;
   while (npow>0)
   {
        ret=(ret*10)+(npow%10);
        npow /= 10; // divide to remove lsb digit
   }
   return ret;
}
</code>```

Title: The control does not flow beyond 45th line

Body:
Loop inside f1 is infinite as condition to exit while loop is unaltered.

snippet has to be updated as follows,

int f1(int npow)
{
   int ret=0;
   while (npow>0)
   {
        ret=(ret*10)+(npow%10);
        npow /= 10; // divide to remove lsb digit
   }
   return ret;
}


问:
Squaring all the elements in a list by Scheme
I wanted to square all elements in a list by the Scheme programming language.
my code is:

(define (square n) (* n *n))

(define (fun items factor)
  (if (null? items)
      0
      (cons (* (fun (car items)
                    factor))
            (fun (cdr items)
                 factor) ) ) ) )
(display (fun '( 1 2 3 4) square))
```

<p>I'm showing these errors: </p>

```ERROR: In procedure car:
  ERROR: In procedure car:
    Wrong type (expecting pair): 1
```

答:
You have a couple of errors:

The square procedure has an extra * that shouldn't be there

If we're building a list as output, then the base case should return the empty list '(), not 0.

The part where you operate on the current element of the list is incorrect, you should simply call the factor procedure on the car of the list, and there's no need to multiply again, square will take care of that.

This should fix them:

```<code>(define (square n) (* n n))

(define (fun items factor)
  (if (null? items)
      '()
      (cons (factor (car items))
            (fun (cdr items) factor))))
</code>```

In real life, you don't need to implement this procedure yourself, map is already built-in and it's as simple to use as this:

```<code>(map square '(1 2 3 4))
=> '(1 4 9 16)
</code>```

Body:
I wanted to square all elements in a list by the Scheme programming language.
my code is:

(define (square n) (* n *n))

(define (fun items factor)
  (if (null? items)
      0
      (cons (* (fun (car items)
                    factor))
            (fun (cdr items)
                 factor) ) ) ) )
(display (fun '( 1 2 3 4) square))

I'm showing these errors:

ERROR: In procedure car:
  ERROR: In procedure car:
    Wrong type (expecting pair): 1

Body:
You have a couple of errors:

The square procedure has an extra * that shouldn't be there

If we're building a list as output, then the base case should return the empty list '(), not 0.

The part where you operate on the current element of the list is incorrect, you should simply call the factor procedure on the car of the list, and there's no need to multiply again, square will take care of that.

This should fix them:

(define (square n) (* n n))

(define (fun items factor)
  (if (null? items)
      '()
      (cons (factor (car items))
            (fun (cdr items) factor))))

In real life, you don't need to implement this procedure yourself, map is already built-in and it's as simple to use as this:

(map square '(1 2 3 4))
=> '(1 4 9 16)


问:
React. How to call method of specific subchild in component tree
I'm starting to learn React and wonder how the following theoretical problem can be solved.

Suppose I have such components.

```<code>class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        galaxyData:{}
    };
  }

  handleGalaxyCommand(cmd) {
    ...
  }

  render() {
    return (
      <Galaxy galaxyData={this.state.galaxyData} />
    );
  }
}

class Galaxy extends React.Component {
  render() {
    return (this.props.galaxyData.sectors.map((sector) =>
        <Sector sectorData={sector.sectorData} />
    )
    );
  }
}

class Sector extends React.Component {
  render() {
    return (this.props.sectorData.ships.map((ship) =>
        <Ship shipData={ship.shipData} />
    )
    );
  }
}

class Ship extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        x: this.props.shipData.inialX,
        y: this.props.shipData.inialY,
    };
  }

  moveTo(x,y){
  ...
  }

  render() {
    return <div x={this.state.x} y={this.state.y} id={this.props.shipData.id}/>
  }
}
</code>```

I wrote the code quickly for an example only, so I apologize for any syntax errors.
So the component tree looks something like this.

```<code><Galaxy>
    <Sector>
        <Ship/>
        ...
        <Ship/>
    </Sector>
    <Sector>
        <Ship/>
        ...
        <Ship/>
    </Sector>
</Galaxy>
</code>```

There may even be thousands of ships.
The ship has a "moveTo" method, which starts the Timer to change the x and y variables in the state, which causes the re-render, the move effect.
Let's assume that the Game component receives the command via the "handleGalaxyCommand" method to make the ship start moving.

How to call the "moveTo" method on a ship that interests me?

答:
This is actually possible in react :) in a very simple way.

But this works only in class-based components (not functional or hooks).

Basically, you can call any child's methods from the parent if you access it's refs

Something like:

```<code>class Parent extends Component {

    childRef = null;

   componentDidMount() {
       //via ref you can call it
       this.childRef.myCustomMethod();
   }

    render() {
        return <Child ref={ref => this.childRef = ref} />
    }
}

class Child extends Component {

    myCustomMethod() {
        console.log("call me ");
    }

    render() {
        return <div />;
    }
</code>```

}

Check this part of the docs for more details: https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component

Body:
I'm starting to learn React and wonder how the following theoretical problem can be solved.

Suppose I have such components.

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        galaxyData:{}
    };
  }

  handleGalaxyCommand(cmd) {
    ...
  }

  render() {
    return (
      <Galaxy galaxyData={this.state.galaxyData} />
    );
  }
}

class Galaxy extends React.Component {
  render() {
    return (this.props.galaxyData.sectors.map((sector) =>
        <Sector sectorData={sector.sectorData} />
    )
    );
  }
}

class Sector extends React.Component {
  render() {
    return (this.props.sectorData.ships.map((ship) =>
        <Ship shipData={ship.shipData} />
    )
    );
  }
}

class Ship extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        x: this.props.shipData.inialX,
        y: this.props.shipData.inialY,
    };
  }

  moveTo(x,y){
  ...
  }

  render() {
    return

  }
}

I wrote the code quickly for an example only, so I apologize for any syntax errors.
So the component tree looks something like this.

<Galaxy>
    <Sector>
        <Ship/>
        ...
        <Ship/>
    </Sector>
    <Sector>
        <Ship/>
        ...
        <Ship/>
    </Sector>
</Galaxy>

There may even be thousands of ships.
The ship has a "moveTo" method, which starts the Timer to change the x and y variables in the state, which causes the re-render, the move effect.
Let's assume that the Game component receives the command via the "handleGalaxyCommand" method to make the ship start moving.

How to call the "moveTo" method on a ship that interests me?

Body:
This is actually possible in react :) in a very simple way.

But this works only in class-based components (not functional or hooks).

Basically, you can call any child's methods from the parent if you access it's refs

Something like:

class Parent extends Component {

    childRef = null;

   componentDidMount() {
       //via ref you can call it
       this.childRef.myCustomMethod();
   }

    render() {
        return <Child ref={ref => this.childRef = ref} />
    }
}

class Child extends Component {

    myCustomMethod() {
        console.log("call me ");
    }

    render() {
        return <div />;
    }

}

Check this part of the docs for more details: https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component


问:
Why don't I get an integer overflow when adding two chars?

Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

```<code>unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;
</code>```

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

答:
No, this is not an error.

The compiler always calculates at minimum of integer precision, the result will be converted back to unsigned char on assignment only.

This is in the standard.

Body:
Possible Duplicate:

  Addition of two chars produces int

Given the following C++ code:

unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.


问:
Ctrl+C does not stop node server in Command Line from VS Code
From a normal Windows command prompt, ctrl+c will stop a node server running.

However, if I start the command prompt via the VS Code menu item Open in Command Prompt, then pressing ctrl+c (even multiple times) does not stop the server as usual.

Any idea what is different in the VS Code command prompt compared to the standard windows command prompt?

(Running on Windows 10 x64)
(VS Code 1.11.2)

答: If you use Code Runner Visual Code Extension use Ctrl + Alt + M.


问:
Particle system design using Three.js and Shader
I'm very new to this community. As i'm asking question if there is something i claim not right, please correct me.

Now to the point, i'm design a particle system using Three.js library, particularly i'm using THREE.Geometry() and control the vertex using shader. I want my particle movement restricted inside a box, which means when a particle crosses over a face of the box, it new position will be at the opposite side of that face.

Here's how i approach, in the vertex shader:

uniform float elapsedTime;

        void main() {
            gl_PointSize = 3.2;
            vec3 pos = position;

            pos.y -= elapsedTime*2.1;

            if( pos.y < -100.0) {
                pos.y = 100.0;
            }

            gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0 );
        }
```

The ellapsedTime is sent from javascript animation loop via uniform. And the y position of each vertex will be update corresponding to the time. As a test, i want if a particle is lower than the bottom plane ( y = -100) it will move to the top plane. That was my plan. And this is the result after they all reach the bottom:

Start to fall

After reach the bottom

So, what am i missing here?

答:
You can achieve it, using mod function:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 0, 300);
var renderer = new THREE.WebGLRenderer({
  antialis: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var gridTop = new THREE.GridHelper(200, 10);
gridTop.position.y = 100;
var gridBottom = new THREE.GridHelper(200, 10);
gridBottom.position.y = -100;
scene.add(gridTop, gridBottom);

var pts = [];
for (let i = 0; i < 1000; i++) {
  pts.push(new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiplyScalar(100));
}
var geom = new THREE.BufferGeometry().setFromPoints(pts);
var mat = new THREE.PointsMaterial({
  size: 2,
  color: "aqua"
});
var uniforms = {
  time: {
    value: 0
  },
  highY: {
    value: 100
  },
  lowY: {
    value: -100
  }
}
mat.onBeforeCompile = shader => {
  shader.uniforms.time = uniforms.time;
  shader.uniforms.highY = uniforms.highY;
  shader.uniforms.lowY = uniforms.lowY;
  console.log(shader.vertexShader);
  shader.vertexShader = `
    uniform float time;
    uniform float highY;
    uniform float lowY;
  ` + shader.vertexShader;
  shader.vertexShader = shader.vertexShader.replace(
    `#include <begin_vertex>`,
    `#include <begin_vertex>

      float totalY = highY - lowY;
      transformed.y = highY - mod(highY - (transformed.y - time * 20.), totalY);
    `
  );
}
var points = new THREE.Points(geom, mat);
scene.add(points);

var clock = new THREE.Clock();

renderer.setAnimationLoop(() => {
  uniforms.time.value = clock.getElapsedTime();
  renderer.render(scene, camera);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

```

Body:
I'm very new to this community. As i'm asking question if there is something i claim not right, please correct me.

Now to the point, i'm design a particle system using Three.js library, particularly i'm using THREE.Geometry() and control the vertex using shader. I want my particle movement restricted inside a box, which means when a particle crosses over a face of the box, it new position will be at the opposite side of that face.

Here's how i approach, in the vertex shader:

uniform float elapsedTime;

        void main() {
            gl_PointSize = 3.2;
            vec3 pos = position;

            pos.y -= elapsedTime*2.1;

            if( pos.y < -100.0) {
                pos.y = 100.0;
            }

            gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0 );
        }

The ellapsedTime is sent from javascript animation loop via uniform. And the y position of each vertex will be update corresponding to the time. As a test, i want if a particle is lower than the bottom plane ( y = -100) it will move to the top plane. That was my plan. And this is the result after they all reach the bottom:

Start to fall

After reach the bottom

So, what am i missing here?

Body:
You can achieve it, using mod function:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 0, 300);
var renderer = new THREE.WebGLRenderer({
  antialis: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var gridTop = new THREE.GridHelper(200, 10);
gridTop.position.y = 100;
var gridBottom = new THREE.GridHelper(200, 10);
gridBottom.position.y = -100;
scene.add(gridTop, gridBottom);

var pts = [];
for (let i = 0; i < 1000; i++) {
  pts.push(new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiplyScalar(100));
}
var geom = new THREE.BufferGeometry().setFromPoints(pts);
var mat = new THREE.PointsMaterial({
  size: 2,
  color: "aqua"
});
var uniforms = {
  time: {
    value: 0
  },
  highY: {
    value: 100
  },
  lowY: {
    value: -100
  }
}
mat.onBeforeCompile = shader => {
  shader.uniforms.time = uniforms.time;
  shader.uniforms.highY = uniforms.highY;
  shader.uniforms.lowY = uniforms.lowY;
  console.log(shader.vertexShader);
  shader.vertexShader = `
    uniform float time;
    uniform float highY;
    uniform float lowY;
  ` + shader.vertexShader;
  shader.vertexShader = shader.vertexShader.replace(
    `#include <begin_vertex>`,
    `#include <begin_vertex>

      float totalY = highY - lowY;
      transformed.y = highY - mod(highY - (transformed.y - time * 20.), totalY);
    `
  );
}
var points = new THREE.Points(geom, mat);
scene.add(points);

var clock = new THREE.Clock();

renderer.setAnimationLoop(() => {
  uniforms.time.value = clock.getElapsedTime();
  renderer.render(scene, camera);
});

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>


问:
What does this Typescript syntax mean
```<code>export declare type SomeType = {
   [key: string] : string
};
</code>```

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

答:
Basically, Typescript is a static typed version of javascript. In this case, we have a type called SomeType which is an Object. And we are also mentioning the object's key and value type in this manner - [key: string]: string.

In your case, SomeType will only accept a key of string and value of string. Else, It will throw a type error.

Eg: { "name": "user"} is valid and {"name" : 10 } is invalid.

Title: What does this Typescript syntax mean

Body:
export declare type SomeType = {
   [key: string] : string
};

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?