问:
Sending 2D array from Server to Client via TCP/IP and print it as a chessboard
how can I send a 2D array from a Server to Client(s) as if they played chess?

This is my server.c file:

```<code>// MAPPA
#define RIGHE 5
#define COLONNE 5

// STRUTTURA DATI
typedef struct ClientNode {
    int data;
    struct ClientNode* prev;
    struct ClientNode* next;
    char ip[16];
    char name[31];
} ClientList;

// Global variable
int serverSocket = 0, clientSocket = 0;
ClientList *top, *lastAdded;
int clientDisconnessi = 0;
char mappa[RIGHE][COLONNE];

void setupMap(char[][COLONNE]);
void setDestinationOnMap(char[][COLONNE]);
void setObstaclesOnMap(char[][COLONNE]);
void setPackagesOnMap(char[][COLONNE]);
void printMap(char[][COLONNE]);
void hideObstacles(char);
int getNumberOfPackages(char[][COLONNE]);
int getNumberOfObstacles(char[][COLONNE]);
void catch_ctrl_c_and_exit(int);
void sent_to_all_clients(ClientList*, char*);
void client_handler(void*);
int countNumberOfClientsConnected(ClientList*);
void whoIsOn(ClientList*);
int isNotACommand(char*);
ClientList *creaNuovoNodo(int, char*);

int main()
{

    setupMap(mappa);

    // Associa come handler del comando CTRL-C la funzione catch_ctrl_c_and_exit
    signal(SIGINT, catch_ctrl_c_and_exit);

    // Creazione socket
    serverSocket = socket(AF_INET , SOCK_STREAM , 0);
    if (serverSocket == -1) {
        printf("Fail to create a socket.");
        exit(1);
    }

    // Socket information
    struct sockaddr_in server_info, client_info;
    int s_addrlen = sizeof(server_info);
    int c_addrlen = sizeof(client_info);
    memset(&server_info, 0, s_addrlen);
    memset(&client_info, 0, c_addrlen);
    server_info.sin_family = PF_INET;
    server_info.sin_addr.s_addr = INADDR_ANY;
    server_info.sin_port = htons(8888);

    // Binding
    if (bind(serverSocket, (struct sockaddr *) &server_info, s_addrlen) == -1) {
        perror("Errore binding");
        exit(1);
    }

    // Imposta all'ascolto
    if (listen(serverSocket, 5) == -1) {
        perror("Errore listening");
        exit(1);
    }

    // Visualizzare indirizzo IP del server
    getsockname(serverSocket, (struct sockaddr*) &server_info, (socklen_t*) &s_addrlen);
    printf("Start server on: %s:%d\n", inet_ntoa(server_info.sin_addr), ntohs(server_info.sin_port));

    // Lista doppiamente concatenata per i client che contiene come primo nodo le informazioni sul server
    top = creaNuovoNodo(serverSocket, inet_ntoa(server_info.sin_addr));
    lastAdded = top;

    while (1) {

        clientSocket = accept(serverSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
        if (clientSocket == -1) {
            perror("Errore accept");
            exit(1);
        }

        // Visualizzare l'indirizzo IP del client
        getpeername(clientSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
        printf("Client %s:%d come in.\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));

        // Inserimento (append) nella linked list dei client
        ClientList *client = creaNuovoNodo(clientSocket, inet_ntoa(client_info.sin_addr));
        client->prev = lastAdded;
        lastAdded->next = client;
        lastAdded = client;

        pthread_t tid;
        if (pthread_create(&tid, NULL, (void *) client_handler, (void *) client) != 0) {
            perror("Create pthread error!\n");
            exit(1);
        }
    }

    return 0;
}

void catch_ctrl_c_and_exit(int sig)
{
    ClientList *tmp;

    while (top != NULL) {
        printf("\nClose socketfd: %d\n", top->data);
        close(top->data); // close all socket include server_sockfd
        tmp = top;
        top = top->next;
        free(tmp);
    }

    printf("Hai spento il server\n");

    exit(0);
}

void send_to_all_clients(ClientList *client, char messageToBeSent[LENGTH_SEND])
{
    ClientList *tmp = top->next;

    while (tmp != NULL) {
        if (client->data != tmp->data) { // notifica tutti i client ad eccezione di se stesso
            printf("Send to sockfd %d: \"%s\" \n", tmp->data, messageToBeSent);
            if (send(tmp->data, messageToBeSent, LENGTH_SEND, 0) == -1 ){ // invia LENGTH_SEND byte di messageToBeSent a tmp->data il quale contiene il filedescriptor per un client
                perror("Errore nell'invio del messaggio");
                exit(1);
            }
        }

        tmp = tmp->next;
    }

}

void client_handler(void *p_client)
{
    int hasLeftTheChatroom = 0;
    char nickname[LENGTH_NAME] = ""; // ricevuto tramite il send da parte del client
    char receivedMessage[LENGTH_MSG] = "";
    char messageToBeSent[LENGTH_SEND] = "";
    char mapToBeSent[RIGHE][COLONNE];
    ClientList *client = (ClientList *) p_client;

    // Conversazione
    while (1) {

        if (hasLeftTheChatroom) {
            break;
        }

        int receive = recv(client->data, receivedMessage, LENGTH_MSG, 0);
        if (receive > 0) {

            if (strlen(receivedMessage) == 0) {
                continue;
            }

            // Impacchetta quelle informazioni nella stringa messageToBeSent
            sprintf(messageToBeSent, "-%s (%s): %s", client->name, client->ip, receivedMessage);

            // TODO:
            if (strcmp(receivedMessage, ":map") == 0) {
                char escape = '\n';
                for (int i = 0; i < RIGHE; i++) {
                    for (int j = 0; j < COLONNE; j++) {
                        if (send(client->data, &mappa[i][j], LENGTH_SEND, 0) == -1) {
                            perror("Errore nell'invio");
                            exit(1);
                        }
                    }
                }
            }

        }

        else {
            printf("Fatal Error: -1\n");
            hasLeftTheChatroom = 1;
        }

        if (isNotACommand(receivedMessage)) // Se il messaggio ricevuto non è un comando (tranne :exit)
            send_to_all_clients(client, messageToBeSent);

    }

    // Rimozione di un nood dalla lista
    close(client->data);
    if (client == lastAdded) { // remove an edge node
        lastAdded = client->prev;
        lastAdded->next = NULL;
    } else { // remove a middle node
        client->prev->next = client->next;
        client->next->prev = client->prev;
    }

    free(client);
}

/* Conta il numero di client attualmente connessi */
int countNumberOfClientsConnected(ClientList *client)
{
    ClientList *tmp = client;
    int count = 0;

    while (tmp != NULL) {
        count++;
        tmp = tmp->next;
    }

    return count;
}

/* Restituisce vero se il messaggio ricevuto non è un comando (eccezion fatta per :exit) */
int isNotACommand(char *receivedMessage)
{
    return (strcmp(receivedMessage, ":howManyOn") != 0 && strcmp(receivedMessage, ":howManyOff") != 0
                    && strcmp(receivedMessage, ":who") != 0);
}

/* Predispone la mappa */
void setupMap(char mappa[][COLONNE])
{

    //memset(mappa, ' ', sizeof mappa); oppure . . .
    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            mappa[i][j] = ' ';
        }
    }

    setDestinationOnMap(mappa);

    setObstaclesOnMap(mappa);

    setPackagesOnMap(mappa);

    printMap(mappa);

}

/* Posiziona la destinazione del gioco in un punto qualsiasi della mappa */
void setDestinationOnMap(char mappa[][COLONNE])
{
    int rigaDestinazione, colonnaDestinazione;

    srand(time(NULL)); // Randomizza numeri

    rigaDestinazione = rand() % RIGHE;
    colonnaDestinazione = rand() % COLONNE;

    mappa[rigaDestinazione][colonnaDestinazione] = 'D';
}

/* Posiziona gli ostacoli sulla mappa in posizioni casuali */
void setObstaclesOnMap(char mappa[][COLONNE])
{
    int rigaOstacolo, colonnaOstacolo;
    int numeroMassimoDiOstacoli = RIGHE * COLONNE * 1/5;

    srand(time(NULL));

    for (int times = 0; times < numeroMassimoDiOstacoli; times++) {

        rigaOstacolo = rand() % RIGHE;
        colonnaOstacolo = rand() % COLONNE;

        if (mappa[rigaOstacolo][colonnaOstacolo] != 'D')
            mappa[rigaOstacolo][colonnaOstacolo] = '*';
        /*else
            printf("Ho trovato una coincidenza, infatti %c = 'D' cioè mappa[%d][%d]\n", mappa[rigaOstacolo][colonnaOstacolo], rigaOstacolo, colonnaOstacolo);*/

    }
}

/* Posiziona i pacchi sulla mappa */
void setPackagesOnMap(char mappa[][COLONNE])
{
    int rigaPacco, colonnaPacco;
    int numeroMassimoDiPacchi = RIGHE * COLONNE * 1/2;

    srand(time(NULL));

    for (int times = 0; times < numeroMassimoDiPacchi; times++) {

        rigaPacco = rand() % RIGHE;
        colonnaPacco = rand() % COLONNE;

        if (mappa[rigaPacco][colonnaPacco] != 'D' && mappa[rigaPacco][colonnaPacco] != '*')
            mappa[rigaPacco][colonnaPacco] = 'P';
        /*else
            printf("Ho trovato una coincidenza, infatti %c = '*' oppure 'D' cioè mappa[%d][%d]\n", mappa[rigaPacco][colonnaPacco], rigaPacco, colonnaPacco);*/

    }
}

/* Visualizza la mappa sullo schermo */
void printMap(char mappa[][COLONNE])
{
    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < RIGHE; j++) {
            printf("[ %c ]", mappa[i][j]);
            //hideObstacles(mappa[i][j]);
        }
        printf("\n");
    }
}

/* Nasconde gli ostacoli e colora l'obiettivo in verde */
void hideObstacles(char cella)
{
    if (cella == 'D')
        printf(ANSI_COLOR_GREEN "[ %c ]" ANSI_COLOR_RESET, cella); // Colora in verde l'obiettivo
    else if (cella != '*')
        printf("[ %c ]", cella);
    else
        printf("[   ]");
}

/* Restituisce il numero di pacchi presenti sulla mappa */
int getNumberOfPackages(char mappa[][COLONNE])
{
    int number = 0;

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            if (mappa[i][j] == 'P')
            number++;
        }
    }

    return number;
}

/* Restituisce il numero di ostacoli presenti sulla mappa */
int getNumberOfObstacles(char mappa[][COLONNE])
{
    int number = 0;

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            if (mappa[i][j] == '*')
            number++;
        }
    }

    return number;
}

ClientList *creaNuovoNodo(int sockfd, char* ip)
{
    ClientList *p = (ClientList *) malloc(sizeof(ClientList));

    p->data = sockfd;

    p->prev = NULL;
    p->next = NULL;

    strncpy(p->ip, ip, 16);
    strncpy(p->name, "NULL", 5);

    return p;
}
</code>```

and this is my client.c file:

```<code>// Global variables
volatile sig_atomic_t hasLeftTheChat = 0;
int clientSocket = 0;
char nickname[LENGTH_NAME];

void catch_ctrl_c_and_exit(int);
void recv_msg_handler();
void send_msg_handler();
void str_trim_lf (char*, int);
void str_overwrite_stdout();

int main()
{
    // Associa come handler del segnale CTRL-C la funzione catch...
    signal(SIGINT, catch_ctrl_c_and_exit);

    // Creazione della socket
    clientSocket = socket(AF_INET , SOCK_STREAM , 0);
    if (clientSocket == -1) {
        printf("Fail to create a socket.");
        exit(1);
    }

    // Socket information
    struct sockaddr_in server_info, client_info;
    int s_addrlen = sizeof(server_info);
    int c_addrlen = sizeof(client_info);
    memset(&server_info, 0, s_addrlen);
    memset(&client_info, 0, c_addrlen);
    server_info.sin_family = PF_INET;
    server_info.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_info.sin_port = htons(8888);

    // Connect to Server
    if (connect(clientSocket, (struct sockaddr *)&server_info, s_addrlen) == -1) {
        printf("Connection to Server error!\n");
        exit(1);
    }

    // Richiesta nome
    printf("Please enter your name: ");
    if (fgets(nickname, LENGTH_NAME, stdin) != NULL) {
        str_trim_lf(nickname, LENGTH_NAME);
    }
    if (strlen(nickname) < 2 || strlen(nickname) >= LENGTH_NAME-1) {
        printf("\nName must be more than one and less than thirty characters.\n");
        exit(1);
    }

    // Names
    getsockname(clientSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
    getpeername(clientSocket, (struct sockaddr*) &server_info, (socklen_t*) &s_addrlen);
    printf("Connect to Server: %s:%d\n", inet_ntoa(server_info.sin_addr), ntohs(server_info.sin_port));
    printf("You are: %s:%d\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));

    // Invio dei dati al server
    if (send(clientSocket, nickname, strlen(nickname), 0) == -1) {
        perror("Errore con l'invio del nickname al server");
        exit(1);
    }

    // Creazione del thread relativo alla funzione send_msg_handler per l'invio dei messaggi
    pthread_t send_msg_thread;
    if (pthread_create(&send_msg_thread, NULL, (void *) send_msg_handler, NULL) != 0) {
        printf ("Create pthread error!\n");
        exit(1);
    }

    // Creazione del thread relativo alla funzione recv_msg_handler per la ricezione dei messaggi
    pthread_t recv_msg_thread;
    if (pthread_create(&recv_msg_thread, NULL, (void *) recv_msg_handler, NULL) != 0) {
        printf ("Create pthread error!\n");
        exit(1);
    }

    while (1) {
        if(hasLeftTheChat) {
            printf("\nHai abbandonato la chat.\n");
            break;
        }
    }

    close(clientSocket);

    return 0;
}

void catch_ctrl_c_and_exit(int sig)
{
    hasLeftTheChat = 1;
}

void recv_msg_handler()
{

    char receivedMessage;

    while (1) {
        // Riceve i dati dal server
        if ( recv(clientSocket, &receivedMessage, LENGTH_SEND, 0) <= 0) {
            perror("[-]Error in receiving data from server\n");
            break;
        }
        else {
            printf("\r[ %c ]\n", receivedMessage);
            str_overwrite_stdout();
        }
    }

}

void send_msg_handler()
{
    char messageToBeSent[LENGTH_MSG] = {};

    while (1) {
        str_overwrite_stdout();

        while (fgets(messageToBeSent, LENGTH_MSG, stdin) != NULL) {

            str_trim_lf(messageToBeSent, LENGTH_MSG);

            if (strlen(messageToBeSent) == 0)
                str_overwrite_stdout();

            else
                break;

        }

        // Invio dei dati al server
        if (send(clientSocket, messageToBeSent, LENGTH_MSG, 0) == -1) {
            perror("Errore con l'invio del messaggio");
            exit(1);
        }

        if (strcmp(messageToBeSent, ":exit") == 0) {
            break;
        }

    }

    catch_ctrl_c_and_exit(2);

}

void str_trim_lf (char* arr, int length) {
    int i;
    for (i = 0; i < length; i++) { // trim \n
        if (arr[i] == '\n') {
            arr[i] = '\0';
            break;
        }
    }
}

void str_overwrite_stdout() {
    printf("\r%s", "> ");
    fflush(stdout);
}
</code>```

This is client.c output:

but what I want is to see it as the server does:

How do I fix?

答:
I don't know is this will be an actual answer for you. But SO is not a site to do a homework. So the post is an answer to the question in general form. As you had already used sockets, you probably know, that TCP protocol sends and recieves data in octets of bits. On most modern systems, the byte is an octet of bits. So, in general, TCP sends/recieves data as bytes. In C programming language, strings represent a series of bytes with zero at the end of a series.

So you may send data as a C string. Take a two-dimensional array in C. It, off course, can be represented as a one-dimensional. Given:

```<code>0 1
2 3
</code>```

Can be represented as a 0 1 2 3. The usual formula for converting one dimensional index to two-dimensional is:

```<code>index = row_position + row_length * column_position
</code>```

Continue. Take one-dimensional series of 0 1 2 3. The 2 value have index of 2 for 2x2 chess board.

```<code>2 = 0 + 2 * 1 == 2
^   ^   ^   ^
|   |   |   |
I  RP  RL  CP
</code>```

Where I is index, RP is row position, RL is row length, CP is column position. Now that you can encode your chessboard in the above way, you can send the chessboard data. For exampl you can send it as such: 0 1 2 3 ... 20 21 22.
After this is done, you may recieve your data and decode it. Wish you all lucks.

Body:
how can I send a 2D array from a Server to Client(s) as if they played chess?

This is my server.c file:

// MAPPA
#define RIGHE 5
#define COLONNE 5

// STRUTTURA DATI
typedef struct ClientNode {
    int data;
    struct ClientNode* prev;
    struct ClientNode* next;
    char ip[16];
    char name[31];
} ClientList;

// Global variable
int serverSocket = 0, clientSocket = 0;
ClientList *top, *lastAdded;
int clientDisconnessi = 0;
char mappa[RIGHE][COLONNE];

void setupMap(char[][COLONNE]);
void setDestinationOnMap(char[][COLONNE]);
void setObstaclesOnMap(char[][COLONNE]);
void setPackagesOnMap(char[][COLONNE]);
void printMap(char[][COLONNE]);
void hideObstacles(char);
int getNumberOfPackages(char[][COLONNE]);
int getNumberOfObstacles(char[][COLONNE]);
void catch_ctrl_c_and_exit(int);
void sent_to_all_clients(ClientList*, char*);
void client_handler(void*);
int countNumberOfClientsConnected(ClientList*);
void whoIsOn(ClientList*);
int isNotACommand(char*);
ClientList *creaNuovoNodo(int, char*);

int main()
{

    setupMap(mappa);

    // Associa come handler del comando CTRL-C la funzione catch_ctrl_c_and_exit
    signal(SIGINT, catch_ctrl_c_and_exit);

    // Creazione socket
    serverSocket = socket(AF_INET , SOCK_STREAM , 0);
    if (serverSocket == -1) {
        printf("Fail to create a socket.");
        exit(1);
    }

    // Socket information
    struct sockaddr_in server_info, client_info;
    int s_addrlen = sizeof(server_info);
    int c_addrlen = sizeof(client_info);
    memset(&server_info, 0, s_addrlen);
    memset(&client_info, 0, c_addrlen);
    server_info.sin_family = PF_INET;
    server_info.sin_addr.s_addr = INADDR_ANY;
    server_info.sin_port = htons(8888);

    // Binding
    if (bind(serverSocket, (struct sockaddr *) &server_info, s_addrlen) == -1) {
        perror("Errore binding");
        exit(1);
    }

    // Imposta all'ascolto
    if (listen(serverSocket, 5) == -1) {
        perror("Errore listening");
        exit(1);
    }

    // Visualizzare indirizzo IP del server
    getsockname(serverSocket, (struct sockaddr*) &server_info, (socklen_t*) &s_addrlen);
    printf("Start server on: %s:%d\n", inet_ntoa(server_info.sin_addr), ntohs(server_info.sin_port));

    // Lista doppiamente concatenata per i client che contiene come primo nodo le informazioni sul server
    top = creaNuovoNodo(serverSocket, inet_ntoa(server_info.sin_addr));
    lastAdded = top;

    while (1) {

        clientSocket = accept(serverSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
        if (clientSocket == -1) {
            perror("Errore accept");
            exit(1);
        }

        // Visualizzare l'indirizzo IP del client
        getpeername(clientSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
        printf("Client %s:%d come in.\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));

        // Inserimento (append) nella linked list dei client
        ClientList *client = creaNuovoNodo(clientSocket, inet_ntoa(client_info.sin_addr));
        client->prev = lastAdded;
        lastAdded->next = client;
        lastAdded = client;

        pthread_t tid;
        if (pthread_create(&tid, NULL, (void *) client_handler, (void *) client) != 0) {
            perror("Create pthread error!\n");
            exit(1);
        }
    }

    return 0;
}

void catch_ctrl_c_and_exit(int sig)
{
    ClientList *tmp;

    while (top != NULL) {
        printf("\nClose socketfd: %d\n", top->data);
        close(top->data); // close all socket include server_sockfd
        tmp = top;
        top = top->next;
        free(tmp);
    }

    printf("Hai spento il server\n");

    exit(0);
}

void send_to_all_clients(ClientList *client, char messageToBeSent[LENGTH_SEND])
{
    ClientList *tmp = top->next;

    while (tmp != NULL) {
        if (client->data != tmp->data) { // notifica tutti i client ad eccezione di se stesso
            printf("Send to sockfd %d: \"%s\" \n", tmp->data, messageToBeSent);
            if (send(tmp->data, messageToBeSent, LENGTH_SEND, 0) == -1 ){ // invia LENGTH_SEND byte di messageToBeSent a tmp->data il quale contiene il filedescriptor per un client
                perror("Errore nell'invio del messaggio");
                exit(1);
            }
        }

        tmp = tmp->next;
    }

}

void client_handler(void *p_client)
{
    int hasLeftTheChatroom = 0;
    char nickname[LENGTH_NAME] = ""; // ricevuto tramite il send da parte del client
    char receivedMessage[LENGTH_MSG] = "";
    char messageToBeSent[LENGTH_SEND] = "";
    char mapToBeSent[RIGHE][COLONNE];
    ClientList *client = (ClientList *) p_client;

    // Conversazione
    while (1) {

        if (hasLeftTheChatroom) {
            break;
        }

        int receive = recv(client->data, receivedMessage, LENGTH_MSG, 0);
        if (receive > 0) {

            if (strlen(receivedMessage) == 0) {
                continue;
            }

            // Impacchetta quelle informazioni nella stringa messageToBeSent
            sprintf(messageToBeSent, "-%s (%s): %s", client->name, client->ip, receivedMessage);

            // TODO:
            if (strcmp(receivedMessage, ":map") == 0) {
                char escape = '\n';
                for (int i = 0; i < RIGHE; i++) {
                    for (int j = 0; j < COLONNE; j++) {
                        if (send(client->data, &mappa[i][j], LENGTH_SEND, 0) == -1) {
                            perror("Errore nell'invio");
                            exit(1);
                        }
                    }
                }
            }

        }

        else {
            printf("Fatal Error: -1\n");
            hasLeftTheChatroom = 1;
        }

        if (isNotACommand(receivedMessage)) // Se il messaggio ricevuto non è un comando (tranne :exit)
            send_to_all_clients(client, messageToBeSent);

    }

    // Rimozione di un nood dalla lista
    close(client->data);
    if (client == lastAdded) { // remove an edge node
        lastAdded = client->prev;
        lastAdded->next = NULL;
    } else { // remove a middle node
        client->prev->next = client->next;
        client->next->prev = client->prev;
    }

    free(client);
}

/* Conta il numero di client attualmente connessi */
int countNumberOfClientsConnected(ClientList *client)
{
    ClientList *tmp = client;
    int count = 0;

    while (tmp != NULL) {
        count++;
        tmp = tmp->next;
    }

    return count;
}

/* Restituisce vero se il messaggio ricevuto non è un comando (eccezion fatta per :exit) */
int isNotACommand(char *receivedMessage)
{
    return (strcmp(receivedMessage, ":howManyOn") != 0 && strcmp(receivedMessage, ":howManyOff") != 0
                    && strcmp(receivedMessage, ":who") != 0);
}

/* Predispone la mappa */
void setupMap(char mappa[][COLONNE])
{

    //memset(mappa, ' ', sizeof mappa); oppure . . .
    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            mappa[i][j] = ' ';
        }
    }

    setDestinationOnMap(mappa);

    setObstaclesOnMap(mappa);

    setPackagesOnMap(mappa);

    printMap(mappa);

}

/* Posiziona la destinazione del gioco in un punto qualsiasi della mappa */
void setDestinationOnMap(char mappa[][COLONNE])
{
    int rigaDestinazione, colonnaDestinazione;

    srand(time(NULL)); // Randomizza numeri

    rigaDestinazione = rand() % RIGHE;
    colonnaDestinazione = rand() % COLONNE;

    mappa[rigaDestinazione][colonnaDestinazione] = 'D';
}

/* Posiziona gli ostacoli sulla mappa in posizioni casuali */
void setObstaclesOnMap(char mappa[][COLONNE])
{
    int rigaOstacolo, colonnaOstacolo;
    int numeroMassimoDiOstacoli = RIGHE * COLONNE * 1/5;

    srand(time(NULL));

    for (int times = 0; times < numeroMassimoDiOstacoli; times++) {

        rigaOstacolo = rand() % RIGHE;
        colonnaOstacolo = rand() % COLONNE;

        if (mappa[rigaOstacolo][colonnaOstacolo] != 'D')
            mappa[rigaOstacolo][colonnaOstacolo] = '*';
        /*else
            printf("Ho trovato una coincidenza, infatti %c = 'D' cioè mappa[%d][%d]\n", mappa[rigaOstacolo][colonnaOstacolo], rigaOstacolo, colonnaOstacolo);*/

    }
}

/* Posiziona i pacchi sulla mappa */
void setPackagesOnMap(char mappa[][COLONNE])
{
    int rigaPacco, colonnaPacco;
    int numeroMassimoDiPacchi = RIGHE * COLONNE * 1/2;

    srand(time(NULL));

    for (int times = 0; times < numeroMassimoDiPacchi; times++) {

        rigaPacco = rand() % RIGHE;
        colonnaPacco = rand() % COLONNE;

        if (mappa[rigaPacco][colonnaPacco] != 'D' && mappa[rigaPacco][colonnaPacco] != '*')
            mappa[rigaPacco][colonnaPacco] = 'P';
        /*else
            printf("Ho trovato una coincidenza, infatti %c = '*' oppure 'D' cioè mappa[%d][%d]\n", mappa[rigaPacco][colonnaPacco], rigaPacco, colonnaPacco);*/

    }
}

/* Visualizza la mappa sullo schermo */
void printMap(char mappa[][COLONNE])
{
    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < RIGHE; j++) {
            printf("[ %c ]", mappa[i][j]);
            //hideObstacles(mappa[i][j]);
        }
        printf("\n");
    }
}

/* Nasconde gli ostacoli e colora l'obiettivo in verde */
void hideObstacles(char cella)
{
    if (cella == 'D')
        printf(ANSI_COLOR_GREEN "[ %c ]" ANSI_COLOR_RESET, cella); // Colora in verde l'obiettivo
    else if (cella != '*')
        printf("[ %c ]", cella);
    else
        printf("[   ]");
}

/* Restituisce il numero di pacchi presenti sulla mappa */
int getNumberOfPackages(char mappa[][COLONNE])
{
    int number = 0;

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            if (mappa[i][j] == 'P')
            number++;
        }
    }

    return number;
}

/* Restituisce il numero di ostacoli presenti sulla mappa */
int getNumberOfObstacles(char mappa[][COLONNE])
{
    int number = 0;

    for (int i = 0; i < RIGHE; i++) {
        for (int j = 0; j < COLONNE; j++) {
            if (mappa[i][j] == '*')
            number++;
        }
    }

    return number;
}

ClientList *creaNuovoNodo(int sockfd, char* ip)
{
    ClientList *p = (ClientList *) malloc(sizeof(ClientList));

    p->data = sockfd;

    p->prev = NULL;
    p->next = NULL;

    strncpy(p->ip, ip, 16);
    strncpy(p->name, "NULL", 5);

    return p;
}

and this is my client.c file:

// Global variables
volatile sig_atomic_t hasLeftTheChat = 0;
int clientSocket = 0;
char nickname[LENGTH_NAME];

void catch_ctrl_c_and_exit(int);
void recv_msg_handler();
void send_msg_handler();
void str_trim_lf (char*, int);
void str_overwrite_stdout();

int main()
{
    // Associa come handler del segnale CTRL-C la funzione catch...
    signal(SIGINT, catch_ctrl_c_and_exit);

    // Creazione della socket
    clientSocket = socket(AF_INET , SOCK_STREAM , 0);
    if (clientSocket == -1) {
        printf("Fail to create a socket.");
        exit(1);
    }

    // Socket information
    struct sockaddr_in server_info, client_info;
    int s_addrlen = sizeof(server_info);
    int c_addrlen = sizeof(client_info);
    memset(&server_info, 0, s_addrlen);
    memset(&client_info, 0, c_addrlen);
    server_info.sin_family = PF_INET;
    server_info.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_info.sin_port = htons(8888);

    // Connect to Server
    if (connect(clientSocket, (struct sockaddr *)&server_info, s_addrlen) == -1) {
        printf("Connection to Server error!\n");
        exit(1);
    }

    // Richiesta nome
    printf("Please enter your name: ");
    if (fgets(nickname, LENGTH_NAME, stdin) != NULL) {
        str_trim_lf(nickname, LENGTH_NAME);
    }
    if (strlen(nickname) < 2 || strlen(nickname) >= LENGTH_NAME-1) {
        printf("\nName must be more than one and less than thirty characters.\n");
        exit(1);
    }

    // Names
    getsockname(clientSocket, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
    getpeername(clientSocket, (struct sockaddr*) &server_info, (socklen_t*) &s_addrlen);
    printf("Connect to Server: %s:%d\n", inet_ntoa(server_info.sin_addr), ntohs(server_info.sin_port));
    printf("You are: %s:%d\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));

    // Invio dei dati al server
    if (send(clientSocket, nickname, strlen(nickname), 0) == -1) {
        perror("Errore con l'invio del nickname al server");
        exit(1);
    }

    // Creazione del thread relativo alla funzione send_msg_handler per l'invio dei messaggi
    pthread_t send_msg_thread;
    if (pthread_create(&send_msg_thread, NULL, (void *) send_msg_handler, NULL) != 0) {
        printf ("Create pthread error!\n");
        exit(1);
    }

    // Creazione del thread relativo alla funzione recv_msg_handler per la ricezione dei messaggi
    pthread_t recv_msg_thread;
    if (pthread_create(&recv_msg_thread, NULL, (void *) recv_msg_handler, NULL) != 0) {
        printf ("Create pthread error!\n");
        exit(1);
    }

    while (1) {
        if(hasLeftTheChat) {
            printf("\nHai abbandonato la chat.\n");
            break;
        }
    }

    close(clientSocket);

    return 0;
}

void catch_ctrl_c_and_exit(int sig)
{
    hasLeftTheChat = 1;
}

void recv_msg_handler()
{

    char receivedMessage;

    while (1) {
        // Riceve i dati dal server
        if ( recv(clientSocket, &receivedMessage, LENGTH_SEND, 0) <= 0) {
            perror("[-]Error in receiving data from server\n");
            break;
        }
        else {
            printf("\r[ %c ]\n", receivedMessage);
            str_overwrite_stdout();
        }
    }

}

void send_msg_handler()
{
    char messageToBeSent[LENGTH_MSG] = {};

    while (1) {
        str_overwrite_stdout();

        while (fgets(messageToBeSent, LENGTH_MSG, stdin) != NULL) {

            str_trim_lf(messageToBeSent, LENGTH_MSG);

            if (strlen(messageToBeSent) == 0)
                str_overwrite_stdout();

            else
                break;

        }

        // Invio dei dati al server
        if (send(clientSocket, messageToBeSent, LENGTH_MSG, 0) == -1) {
            perror("Errore con l'invio del messaggio");
            exit(1);
        }

        if (strcmp(messageToBeSent, ":exit") == 0) {
            break;
        }

    }

    catch_ctrl_c_and_exit(2);

}

void str_trim_lf (char* arr, int length) {
    int i;
    for (i = 0; i < length; i++) { // trim \n
        if (arr[i] == '\n') {
            arr[i] = '\0';
            break;
        }
    }
}

void str_overwrite_stdout() {
    printf("\r%s", "> ");
    fflush(stdout);
}

This is client.c output:

but what I want is to see it as the server does:

How do I fix?

Body:
I don't know is this will be an actual answer for you. But SO is not a site to do a homework. So the post is an answer to the question in general form. As you had already used sockets, you probably know, that TCP protocol sends and recieves data in octets of bits. On most modern systems, the byte is an octet of bits. So, in general, TCP sends/recieves data as bytes. In C programming language, strings represent a series of bytes with zero at the end of a series.

So you may send data as a C string. Take a two-dimensional array in C. It, off course, can be represented as a one-dimensional. Given:

0 1
2 3

Can be represented as a 0 1 2 3. The usual formula for converting one dimensional index to two-dimensional is:

index = row_position + row_length * column_position

Continue. Take one-dimensional series of 0 1 2 3. The 2 value have index of 2 for 2x2 chess board.

2 = 0 + 2 * 1 == 2
^   ^   ^   ^
|   |   |   |
I  RP  RL  CP

Where I is index, RP is row position, RL is row length, CP is column position. Now that you can encode your chessboard in the above way, you can send the chessboard data. For exampl you can send it as such: 0 1 2 3 ... 20 21 22.
After this is done, you may recieve your data and decode it. Wish you all lucks.


来源: stackexchange

问:
default value for file input form when update image in laravel 5.8
I'm Using Laravel 5.8, I'm trying to make update data in laravel, the data is contained images, when the form update did not get a new image, laravel displays an error, that the image is null,
can I make the old image as the default value for the file input?

this is my controller

```<code>public function UploadEdit(Request $request, Books $book,$id_book){
    $book = Books::find($id_book);
    global $old_image;
    $old_image = public_path("img/books/". $book->image);
    if($request->hasFile('image')){
        if (File::exists($old_image)) {
            unlink($old image);
        }

        $image = $request->file('image');
        $image_name = time()."_".$image->getClientOriginalName();
        $image->move('img/books',$image_name);
        $book->image=$image_name;
    }else{
        $book->image = $old_image;
    }

    DB::table('books')->where('id_book',$request->id_book,$image_name)->update([
        'title' => $request->title,
        'image' => $request->image = $image_name,
        'category' => $request->category,
        'description' => $request->description
    ]);

    return redirect('/books');
}
</code>```

this is input file from my form :

```<code><div class="form-group">
    <label for="image">Image</label>
    <input type="file" class="form-control-file" id="image" name="image" id="image" enctype="multipart/form-data" value="{{ asset("img/books/$book->image") }}">
    <img src="{{ asset("img/books/$book->image") }}" width="150">
</div>
</code>```

I'm trying to make the default value  for file form, but still doesn't work

答:
You can't set default value for <input type="file"/> the best thing you can do is when you're updating books table check if request has image if it doesn't then you can skip updating image or reassign previous one

here is what it looks like

DB::table('books')->where('id_book',$request->id_book,$image_name)->update([
    'title' => $request->title,
    'image' => $request->hasFile('image') ? $image_name : $book->image,
    'category' => $request->category,
    'description' => $request->description
]);
```

ContentLicense: CC BY-SA 4.0

Body:
I'm Using Laravel 5.8, I'm trying to make update data in laravel, the data is contained images, when the form update did not get a new image, laravel displays an error, that the image is null,
can I make the old image as the default value for the file input?

this is my controller

public function UploadEdit(Request $request, Books $book,$id_book){
    $book = Books::find($id_book);
    global $old_image;
    $old_image = public_path("img/books/". $book->image);
    if($request->hasFile('image')){
        if (File::exists($old_image)) {
            unlink($old image);
        }

        $image = $request->file('image');
        $image_name = time()."_".$image->getClientOriginalName();
        $image->move('img/books',$image_name);
        $book->image=$image_name;
    }else{
        $book->image = $old_image;
    }

    DB::table('books')->where('id_book',$request->id_book,$image_name)->update([
        'title' => $request->title,
        'image' => $request->image = $image_name,
        'category' => $request->category,
        'description' => $request->description
    ]);

    return redirect('/books');
}

this is input file from my form :

    Image
    <input type="file" class="form-control-file" id="image" name="image" id="image" enctype="multipart/form-data" value="{{ asset("img/books/$book->image") }}">
    image") }}" width="150">

I'm trying to make the default value  for file form, but still doesn't work


问:
How to create a matrix like this in scala?
I have a table like

```<code>ID    Name
1      11
2      12
3      13
4      14
5      15
6      16
</code>```

I want to create a matrix using this table. Matrix should be like this

```<code>0   11   12   13   14   15   16

1   1/6  0    0     0   0    0

2   0   1/6   0     0   0    0

3   0    0    1/6   0   0    0

4   0    0    0   1/6   0    0

5   0    0    0    0   1/6   0

6   0    0    0     0   0    1/6
</code>```

Where the index of i is quals to j,  i.e  i=j => 1/6  else 0.

答:
This may not be the neatest way, but it will do what you want:

//Assuming the table consists of pairs
val table: List[(Double, Double)] =
  List(
    1.0 -> 11.0,
    2.0 -> 12.0,
    3.0 -> 13.0,
    4.0 -> 14.0,
    5.0 -> 15.0,
    6.0 -> 16.0
  )

println(table)

// The following assumes we want the matrix as a List of rows, where each row is a List[Double]

// Get the columns of table
val t1 = table.map(_._1)
val t2 = table.map(_._2)

// Make the first row separately, since it is different from the others
val firstRow = 0.0 :: t2

// Make the other rows - start with value from first column, then the diagonal matrix entries
val otherRows = t1.zipWithIndex.map { case (a, row) =>
  a :: t1.indices.toList.map(i => if (i == row) 1.0/6.0 else 0.0)
}

// Assemble the whole matrix
val matrix = firstRow :: otherRows

// Matrix as List[List[Double]
println(matrix)

// Printed
println(matrix.map(row => row.map(a => f"$a%.3f").mkString("\t")).mkString("\n"))
```

<p>I've put this code in a scalafiddle here</p>

<p>The final result is:</p>

```0.000   11.000  12.000  13.000  14.000  15.000  16.000
1.000   0.167   0.000   0.000   0.000   0.000   0.000
2.000   0.000   0.167   0.000   0.000   0.000   0.000
3.000   0.000   0.000   0.167   0.000   0.000   0.000
4.000   0.000   0.000   0.000   0.167   0.000   0.000
5.000   0.000   0.000   0.000   0.000   0.167   0.000
6.000   0.000   0.000   0.000   0.000   0.000   0.167
```

Body:
I have a table like

ID    Name
1      11
2      12
3      13
4      14
5      15
6      16

I want to create a matrix using this table. Matrix should be like this

0   11   12   13   14   15   16

1   1/6  0    0     0   0    0

2   0   1/6   0     0   0    0

3   0    0    1/6   0   0    0

4   0    0    0   1/6   0    0

5   0    0    0    0   1/6   0

6   0    0    0     0   0    1/6

Where the index of i is quals to j,  i.e  i=j => 1/6  else 0.

Body:
This may not be the neatest way, but it will do what you want:

//Assuming the table consists of pairs
val table: List[(Double, Double)] =
  List(
    1.0 -> 11.0,
    2.0 -> 12.0,
    3.0 -> 13.0,
    4.0 -> 14.0,
    5.0 -> 15.0,
    6.0 -> 16.0
  )

println(table)

// The following assumes we want the matrix as a List of rows, where each row is a List[Double]

// Get the columns of table
val t1 = table.map(_._1)
val t2 = table.map(_._2)

// Make the first row separately, since it is different from the others
val firstRow = 0.0 :: t2

// Make the other rows - start with value from first column, then the diagonal matrix entries
val otherRows = t1.zipWithIndex.map { case (a, row) =>
  a :: t1.indices.toList.map(i => if (i == row) 1.0/6.0 else 0.0)
}

// Assemble the whole matrix
val matrix = firstRow :: otherRows

// Matrix as List[List[Double]
println(matrix)

// Printed
println(matrix.map(row => row.map(a => f"$a%.3f").mkString("\t")).mkString("\n"))

I've put this code in a scalafiddle here

The final result is:

0.000   11.000  12.000  13.000  14.000  15.000  16.000
1.000   0.167   0.000   0.000   0.000   0.000   0.000
2.000   0.000   0.167   0.000   0.000   0.000   0.000
3.000   0.000   0.000   0.167   0.000   0.000   0.000
4.000   0.000   0.000   0.000   0.167   0.000   0.000
5.000   0.000   0.000   0.000   0.000   0.167   0.000
6.000   0.000   0.000   0.000   0.000   0.000   0.167


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答: Reference vs value types.</p>

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

Body: Reference vs value types.

OwnerDisplayName: siz


问:
Regex to validate a twitter url
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

```<code>http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regex to validate a twitter url

Body:
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama

Body: url.match(/http:\/\/twitter.com\/(#!\/)?(\w*)/i);


问:
Ionic devapp just searching
I'm having a problem with the Ionic DevApp application .. I use the "ionic serve -c" command it opens in the browser, but on my device it is just looking for .. "Listening for apps on your network". It is not appearing on my device, however I have already tested on 2 other devices, and in them appears the project in the list. I even formatted my Android device, but still can not find the project. Anyone have any idea what it can be? Why is this happening? Thanks!</p>

答:
How to run the ionic app using devapp:

Navigate to the Ionic Project folder via cmd line.

Disable your Firewall - Enabled Firewall  is what causes the buffering problem.

Run cmd ionic serve --devapp

Search for the app in the devapp on your android phone which is connected to the same wifi network like Hotspot or via Home Wifi Router.

Title: Ionic devapp just searching


问:
Small String Optimisation (Debug vs Release mode)
I've been examining the small string optimisation (in MSVC 2019) using this sample script:

#include <string>

void* operator new(size_t size)
{
    std::printf("global op new called, size = %zu\n", size);
    void* ptr = std::malloc(size);

    if (ptr)
        return ptr;
    else
        throw std::bad_alloc{};
}

int main()
{
    std::string test = "small value";
    return 0;
}
```

<p>Note, I took <code>void* operator new(size_t size)</code> from https://en.cppreference.com/w/cpp/memory/new/operator_new.</p>

<p>In <em>Release</em> mode the optimisation works as expected (i.e. <code>new</code> does not get called), but in <em>Debug</em> mode the script actually prints <code>global op new called, size = 16</code>. After drilling down this seems to be due to this code segment in header <code>xmemory</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>#if _ITERATOR_DEBUG_LEVEL == 0
  #define _GET_PROXY_ALLOCATOR(_Alty, _Al) _Fake_allocator()
  template <class _Alloc>
  using _Container_proxy_ptr = _Fake_proxy_ptr_impl;
#else // _ITERATOR_DEBUG_LEVEL == 0
  #define _GET_PROXY_ALLOCATOR(_Alty, _Al) static_cast<_Rebind_alloc_t<_Alty, _Container_proxy>>(_Al)
  template <class _Alloc>
  using _Container_proxy_ptr = _Container_proxy_ptr12<_Rebind_alloc_t<_Alloc, _Container_proxy>>;
#endif // _ITERATOR_DEBUG_LEVEL == 0
</code>```

We can see that in Release mode (i.e. _ITERATOR_DEBUG_LEVEL == 0) we use _Fake_proxy_ptr_impl, whereas in Debug mode we use _Container_proxy_ptr12 which uses new.

My question is simple: why is there this difference between Debug and Release mode?

答:
Small string optimization is still there also in Debug mode.
If we create a larger string

```<code>std::string test = "large value.large value.large value.large value.";
</code>```

then we get the actual string allocation

```<code>global op new called, size = 64
</code>```

in both Debug and Release builds.

What you're observing is the allocation of the container proxy for iterator debugging (as can be seen from #if _ITERATOR_DEBUG_LEVEL)

```<code>struct _Container_proxy { // store head of iterator chain and back pointer
</code>```

You can disable iterator debugging by building with /D _ITERATOR_DEBUG_LEVEL=0 (but then it will be disabled for all containers, so also for vector, map etc.).

Body:
I've been examining the small string optimisation (in MSVC 2019) using this sample script:

#include <string>

void* operator new(size_t size)
{
    std::printf("global op new called, size = %zu\n", size);
    void* ptr = std::malloc(size);

    if (ptr)
        return ptr;
    else
        throw std::bad_alloc{};
}

int main()
{
    std::string test = "small value";
    return 0;
}

Note, I took void* operator new(size_t size) from https://en.cppreference.com/w/cpp/memory/new/operator_new.

In Release mode the optimisation works as expected (i.e. new does not get called), but in Debug mode the script actually prints global op new called, size = 16. After drilling down this seems to be due to this code segment in header xmemory:

#if _ITERATOR_DEBUG_LEVEL == 0
  #define _GET_PROXY_ALLOCATOR(_Alty, _Al) _Fake_allocator()
  template <class _Alloc>
  using _Container_proxy_ptr = _Fake_proxy_ptr_impl;
#else // _ITERATOR_DEBUG_LEVEL == 0
  #define _GET_PROXY_ALLOCATOR(_Alty, _Al) static_cast<_Rebind_alloc_t<_Alty, _Container_proxy>>(_Al)
  template <class _Alloc>
  using _Container_proxy_ptr = _Container_proxy_ptr12<_Rebind_alloc_t<_Alloc, _Container_proxy>>;
#endif // _ITERATOR_DEBUG_LEVEL == 0

We can see that in Release mode (i.e. _ITERATOR_DEBUG_LEVEL == 0) we use _Fake_proxy_ptr_impl, whereas in Debug mode we use _Container_proxy_ptr12 which uses new.

My question is simple: why is there this difference between Debug and Release mode?

Body:
Small string optimization is still there also in Debug mode.
If we create a larger string

std::string test = "large value.large value.large value.large value.";

then we get the actual string allocation

global op new called, size = 64

in both Debug and Release builds.

What you're observing is the allocation of the container proxy for iterator debugging (as can be seen from #if _ITERATOR_DEBUG_LEVEL)

struct _Container_proxy { // store head of iterator chain and back pointer

You can disable iterator debugging by building with /D _ITERATOR_DEBUG_LEVEL=0 (but then it will be disabled for all containers, so also for vector, map etc.).


问:
Passing by reference in C++ function
I am writing a simple program to calculate 6^5 using a function. Here's my code

```<code>#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}
</code>```

The result is

```<code> 6^5 is -683606016
</code>```

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

答:
Let's consider this loop

```<code> for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
</code>```

After the first iteration when i is equal to 1 you have

```<code>   base= base * base;
</code>```

that is the result is base ^ 2.

When i = 2 you have

```<code>   base= base^2 * base^2;
</code>```

that is the result is base^4.

When i is equal to 3 you have

```<code>   base= base^4 * base^4;
</code>```

that is the result is base^8.

When i is equal to 4 you have

```<code>   base= base^8 * base^8;
</code>```

that is the result is base^16.

It seems the resulted value is too big to be accomodated in an object of the type int.

Also it is not a good idea when an argument is passed by reference. And the second parameter should have the type unsigned int.

Here is a demonstrative program that shows how the function can be implemented.

```<code>#include <iostream>

long long int raiseToPower( int base, unsigned int exponent )
{
    long long int result = 1;

    while ( exponent-- )
    {
        result *= base;
    }

    return result;
}

int main()
{
    int base = 6;

    std::cout << "6^5 is " << raiseToPower(base, 5) << std::endl;

    return 0;
}
</code>```

Its output is

```<code>6^5 is 7776
</code>```

Title: Passing by reference in C++ function

Body:
I am writing a simple program to calculate 6^5 using a function. Here's my code

#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}

The result is

 6^5 is -683606016

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

Body:
Let's consider this loop

 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }

After the first iteration when i is equal to 1 you have

   base= base * base;

that is the result is base ^ 2.

When i = 2 you have

   base= base^2 * base^2;

that is the result is base^4.

When i is equal to 3 you have

   base= base^4 * base^4;

that is the result is base^8.

When i is equal to 4 you have

   base= base^8 * base^8;

that is the result is base^16.

It seems the resulted value is too big to be accomodated in an object of the type int.

Also it is not a good idea when an argument is passed by reference. And the second parameter should have the type unsigned int.

Here is a demonstrative program that shows how the function can be implemented.

#include <iostream>

long long int raiseToPower( int base, unsigned int exponent )
{
    long long int result = 1;

    while ( exponent-- )
    {
        result *= base;
    }

    return result;
}

int main()
{
    int base = 6;

    std::cout << "6^5 is " << raiseToPower(base, 5) << std::endl;

    return 0;
}

Its output is

6^5 is 7776


问:
Overflow error when trying to read drive properties with ioctl in python
When trying to extract a vendor-specific feature for one of my drives (cmd = 0x89), I get an overflow error: OverflowError: signed integer is greater than maximum. The error is thrown immediately after ioctl is called. The traceback is not very informative either:

```<code>Traceback (most recent call last):
  File "lockbx/atacmd.py", line 148, in <module>
    GetDriveIdSgIo("/dev/sda")
  File "lockbx/atacmd.py", line 134, in GetDriveIdSgIo
    ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))
OverflowError: signed integer is greater than maximum
</code>```

ATA Command Pass-Through Reference: http://www.t10.org/ftp/t10/document.04/04-262r8.pdf

```<code>class AtaCmd(ctypes.Structure):

    _fields_ = [
        ('opcode', ctypes.c_ubyte),
        ('protocol', ctypes.c_ubyte),
        ('flags', ctypes.c_ubyte),
        ('features', ctypes.c_ubyte),
        ('sector_count', ctypes.c_ubyte),
        ('lba_low', ctypes.c_ubyte),
        ('lba_mid', ctypes.c_ubyte),
        ('lba_high', ctypes.c_ubyte),
        ('device', ctypes.c_ubyte),
        ('command', ctypes.c_ubyte),
        ('reserved', ctypes.c_ubyte),
        ('control', ctypes.c_ubyte)]

class SgioHdr(ctypes.Structure):
    """<scsi/sg.h> sg_io_hdr_t."""

    _fields_ = [
        ('interface_id', ctypes.c_int),
        ('dxfer_direction', ctypes.c_int),
        ('cmd_len', ctypes.c_ubyte),
        ('mx_sb_len', ctypes.c_ubyte),
        ('iovec_count', ctypes.c_ushort),
        ('dxfer_len', ctypes.c_uint),
        ('dxferp', ctypes.c_void_p),
        ('cmdp', ctypes.c_void_p),
        ('sbp', ctypes.c_void_p),
        ('timeout', ctypes.c_uint),
        ('flags', ctypes.c_uint),
        ('pack_id', ctypes.c_int),
        ('usr_ptr', ctypes.c_void_p),
        ('status', ctypes.c_ubyte),
        ('masked_status', ctypes.c_ubyte),
        ('msg_status', ctypes.c_ubyte),
        ('sb_len_wr', ctypes.c_ubyte),
        ('host_status', ctypes.c_ushort),
        ('driver_status', ctypes.c_ushort),
        ('resid', ctypes.c_int),
        ('duration', ctypes.c_uint),
        ('info', ctypes.c_uint)]

def GetDriveIdSgIo(dev):
    ata_cmd = AtaCmd(opcode=0xA1,  # ATA PASS-THROUGH (12)
                     protocol=3 << 1,  # PIO Data-In
                     flags=0x06,
                     features=0xF5,
                     sector_count=1,
                     lba_low=0, lba_mid=0, lba_high=0,
                     device=0,
                     command=0x89,  # IDENTIFY
                     reserved=0,
                     control=0)

    SG_DXFER_FROM_DEV = -3
    sense = ctypes.c_buffer(64)
    identify = ctypes.c_buffer(512)

    sgio = SgioHdr(
        interface_id=ord('S'),
        dxfer_direction=SG_DXFER_FROM_DEV,
        cmd_len=ctypes.sizeof(ata_cmd),
        mx_sb_len=ctypes.sizeof(sense),
        iovec_count=0,
        dxfer_len=ctypes.sizeof(identify),
        dxferp=0,
        cmdp=ctypes.addressof(ata_cmd),
        sbp=ctypes.addressof(sense),
        timeout=3000,
        flags=0,
        pack_id=0,
        usr_ptr=None,
        # Set values
        status=0, masked_status=0, msg_status=0, sb_len_wr=0, host_status=0,
        driver_status=0, resid=0, duration=0, info=0
    )

    SG_IO = 0x2285  # <scsi/sg.h>
    with open(dev, 'r') as fd:
        ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))  # fails here

    # some other stuff returns endian swapped buffer info but not relevant

GetDriveIdSgIo("/dev/sda")
</code>```

Where have I gone wrong?

答:
try this:

```<code>ret = fcntl.ioctl(fd.fileno(), 0x2285, ctypes.addressof(sgio))
</code>```

maybe python stores SG_IO as int64 but ioctl only takes 32bit integers as arg. Or explicitly cast it to 32bit as: c_uint(0x2285)

If this doesn't work, it could be the arg parameter. Try this:

```<code>ret = fcntl.ioctl(fd.fileno(), 0x2285, sgio)
</code>```

If that doesn't work try to use struct.pack instead of ctypes as sgio parameter and struct.unpack to read the ret.

Reference: https://docs.python.org/2/library/struct.html

Body:
When trying to extract a vendor-specific feature for one of my drives (cmd = 0x89), I get an overflow error: OverflowError: signed integer is greater than maximum. The error is thrown immediately after ioctl is called. The traceback is not very informative either:

Traceback (most recent call last):
  File "lockbx/atacmd.py", line 148, in <module>
    GetDriveIdSgIo("/dev/sda")
  File "lockbx/atacmd.py", line 134, in GetDriveIdSgIo
    ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))
OverflowError: signed integer is greater than maximum

ATA Command Pass-Through Reference: http://www.t10.org/ftp/t10/document.04/04-262r8.pdf

class AtaCmd(ctypes.Structure):

    _fields_ = [
        ('opcode', ctypes.c_ubyte),
        ('protocol', ctypes.c_ubyte),
        ('flags', ctypes.c_ubyte),
        ('features', ctypes.c_ubyte),
        ('sector_count', ctypes.c_ubyte),
        ('lba_low', ctypes.c_ubyte),
        ('lba_mid', ctypes.c_ubyte),
        ('lba_high', ctypes.c_ubyte),
        ('device', ctypes.c_ubyte),
        ('command', ctypes.c_ubyte),
        ('reserved', ctypes.c_ubyte),
        ('control', ctypes.c_ubyte)]

class SgioHdr(ctypes.Structure):
    """<scsi/sg.h> sg_io_hdr_t."""

    _fields_ = [
        ('interface_id', ctypes.c_int),
        ('dxfer_direction', ctypes.c_int),
        ('cmd_len', ctypes.c_ubyte),
        ('mx_sb_len', ctypes.c_ubyte),
        ('iovec_count', ctypes.c_ushort),
        ('dxfer_len', ctypes.c_uint),
        ('dxferp', ctypes.c_void_p),
        ('cmdp', ctypes.c_void_p),
        ('sbp', ctypes.c_void_p),
        ('timeout', ctypes.c_uint),
        ('flags', ctypes.c_uint),
        ('pack_id', ctypes.c_int),
        ('usr_ptr', ctypes.c_void_p),
        ('status', ctypes.c_ubyte),
        ('masked_status', ctypes.c_ubyte),
        ('msg_status', ctypes.c_ubyte),
        ('sb_len_wr', ctypes.c_ubyte),
        ('host_status', ctypes.c_ushort),
        ('driver_status', ctypes.c_ushort),
        ('resid', ctypes.c_int),
        ('duration', ctypes.c_uint),
        ('info', ctypes.c_uint)]

def GetDriveIdSgIo(dev):
    ata_cmd = AtaCmd(opcode=0xA1,  # ATA PASS-THROUGH (12)
                     protocol=3 << 1,  # PIO Data-In
                     flags=0x06,
                     features=0xF5,
                     sector_count=1,
                     lba_low=0, lba_mid=0, lba_high=0,
                     device=0,
                     command=0x89,  # IDENTIFY
                     reserved=0,
                     control=0)

    SG_DXFER_FROM_DEV = -3
    sense = ctypes.c_buffer(64)
    identify = ctypes.c_buffer(512)

    sgio = SgioHdr(
        interface_id=ord('S'),
        dxfer_direction=SG_DXFER_FROM_DEV,
        cmd_len=ctypes.sizeof(ata_cmd),
        mx_sb_len=ctypes.sizeof(sense),
        iovec_count=0,
        dxfer_len=ctypes.sizeof(identify),
        dxferp=0,
        cmdp=ctypes.addressof(ata_cmd),
        sbp=ctypes.addressof(sense),
        timeout=3000,
        flags=0,
        pack_id=0,
        usr_ptr=None,
        # Set values
        status=0, masked_status=0, msg_status=0, sb_len_wr=0, host_status=0,
        driver_status=0, resid=0, duration=0, info=0
    )

    SG_IO = 0x2285  # <scsi/sg.h>
    with open(dev, 'r') as fd:
        ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))  # fails here

    # some other stuff returns endian swapped buffer info but not relevant

GetDriveIdSgIo("/dev/sda")

Where have I gone wrong?

Body:
try this:

ret = fcntl.ioctl(fd.fileno(), 0x2285, ctypes.addressof(sgio))

maybe python stores SG_IO as int64 but ioctl only takes 32bit integers as arg. Or explicitly cast it to 32bit as: c_uint(0x2285)

If this doesn't work, it could be the arg parameter. Try this:

ret = fcntl.ioctl(fd.fileno(), 0x2285, sgio)

If that doesn't work try to use struct.pack instead of ctypes as sgio parameter and struct.unpack to read the ret.

Reference: https://docs.python.org/2/library/struct.html


问:
Generate unique url slug with PHP
I'm developing a small CMS system. Currently brain dead while trying to generate a unique url. I generate the url from the title of the page. Got a nice script to make this happen but I can't resolve the issue of duplicates.

Similar question here but getting the exact output.

I manage to make the following;

```<code>this-is-the-slug
this-is-the-slug-2
</code>```

But if I create the same post the third time, it would just duplicate: this-is-the-slug-2

```<code>$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}
</code>```

I can't get around it, would be thankful for assistance.

```<code>if(isset($_POST['save'])) {
    $title = mysqli_real_escape_string($db, $_POST['title']);
    $url = toAscii($title);
    // check url
    $content = $_POST['content'];
    $author = $_SESSION['thelab_username'];
    $type = $_POST['type'];
    $showtitle = $_POST['showtitle'];
    $saveas = $_POST['status'];

    $insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
    VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");

    if($insert === TRUE) {
        echo '<div id="success">Page added. <button id="close">Close</button></div>';
    }

    else {
        echo '<div id="error">Failed. Try again. <button id="failed">Close</button></div>';
        printf("Errormessage: %s\n", $db->error);
    }
}

function toAscii($str, $replace=array(), $delimiter='-') {
 if( !empty($replace) ) {
  $str = str_replace((array)$replace, ' ', $str);
 }

 $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
 $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
 $clean = strtolower(trim($clean, '-'));
 $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

 return $clean;
}
</code>```

答:
Try this code, this worked for me.

// check if slug is already exist

```<code>$post_slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($_POST['post_title'])));

$query = "SELECT * FROM `posts` WHERE post_slug = '$post_slug'";
$result = mysqli_query($conn, $query) or die(mysql_error());
$ifExist = mysqli_num_rows($result);
if ($ifExist >= 1) {

    $post_slug = $post_slug . '-' . $ifExist++;
} else {
    $post_slug = $post_slug;
}
</code>```

Title: Generate unique url slug with PHP

Body:
I'm developing a small CMS system. Currently brain dead while trying to generate a unique url. I generate the url from the title of the page. Got a nice script to make this happen but I can't resolve the issue of duplicates.

Similar question here but getting the exact output.

I manage to make the following;

this-is-the-slug
this-is-the-slug-2

But if I create the same post the third time, it would just duplicate: this-is-the-slug-2

$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}

I can't get around it, would be thankful for assistance.

if(isset($_POST['save'])) {
    $title = mysqli_real_escape_string($db, $_POST['title']);
    $url = toAscii($title);
    // check url
    $content = $_POST['content'];
    $author = $_SESSION['thelab_username'];
    $type = $_POST['type'];
    $showtitle = $_POST['showtitle'];
    $saveas = $_POST['status'];

    $insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
    VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");

    if($insert === TRUE) {
        echo '
Page added. <button id="close">Close</button>
';
    }

    else {
        echo '
Failed. Try again. <button id="failed">Close</button>
';
        printf("Errormessage: %s\n", $db->error);
    }
}

function toAscii($str, $replace=array(), $delimiter='-') {
 if( !empty($replace) ) {
  $str = str_replace((array)$replace, ' ', $str);
 }

 $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
 $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
 $clean = strtolower(trim($clean, '-'));
 $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

 return $clean;
}

Body:
Try this code, this worked for me.

// check if slug is already exist

$post_slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($_POST['post_title'])));

$query = "SELECT * FROM `posts` WHERE post_slug = '$post_slug'";
$result = mysqli_query($conn, $query) or die(mysql_error());
$ifExist = mysqli_num_rows($result);
if ($ifExist >= 1) {

    $post_slug = $post_slug . '-' . $ifExist++;
} else {
    $post_slug = $post_slug;
}


问:
SmartClient or SmartGWT?
Besides the obvious differences between JavaScript and Java, what are the relevant differences in using either SmartClient or SmartGWT?</p>

答:
We chose to use Javascript (no SmartGWT) ... I prefer it that way, although some of our team members (newer to Javascript) would have preferred the SmartGWT way. Both have their pros and cons :

One of the advantages of using SmartGWT, is that you get to have compile time errors since everything gets compiled first by the Java compiler, before it gets rendered to Javascript.

One of the drawbacks of SmartGWT, is that it doesn't expose the full underlying Javascript Smartclient API. This means, if you want to do more advanced stuff, you might end up needing to do it in Javascript anyways.

Another drawback of SmartGWT, productivity wise, is that every single change you do and want to test, needs to go thru the painful Java EE compile/deploy process, whereas if you do it in Javascript, you can alter client side code faster by changing .js files directly without the need for the whole compile/deploy process.

Title: SmartClient or SmartGWT?


问:
ProgressBar wont be visible in Android Studio from code
So I have made an app, and I'm trying to show the progress bar at the time when a button is clicked.

It shows only if I put the View.VISIBLE outside the handler.

Kotlin code:

```<code>button.setOnClickListener {

progressBar.visibility = View.VISIBLE
    runBlocking {

        try {
            //HTTP request removed because of confidentiality, assume I'm setting delay

        } catch (e: Exception) {
            Log.e(tag, "Error: " + e.message)
            Toast.makeText(this@MainActivity, "Could not find page", Toast.LENGTH_LONG)
                .show()
        }

    }
    progressBar.visibility = View.GONE
}
</code>```

Button XML:

```<code><ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:alpha="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility= "invisible"/>
</code>```

I've been searching for hours now and couldn't find something relevant to my case.

Output wanted:
Get the progress bar at the time the button is clicked.

答:
Executing a command like progressBar.visibility = View.VISIBLE may take a few nanoseconds(144100 approx).

The main thread might ask some other threads to perform some tasks and instead of waiting for the response of those threads, it resumes its normal execution(next lines of code). Your next line of code(runBlocking: Runs a new coroutine and blocks the current thread interruptibly until its completion.) blocks the current until the coroutine started from the runBlocking method is finished. This simply means that the Main thread can't execute other commands or process responses received from the other threads until the coroutine is finished.

Once the coroutine is finished. Main thread resumes its execution, showing and hiding progress bar simultaneously, which is why you don't see the progress bar spinning.

Main Thread should only be used for UI operations. Instead of blocking your main thread, you should perform the network operations in coroutine by switching to IO context.

Check here on types of Dispatchers.
https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb

```<code>bt.setOnClickListener {
    progressBar.visibility = View.VISIBLE
    GlobalScope.launch {
        networkCall()
    }

}

private suspend fun networkCall() {
    withContext(Dispatchers.Default) {
        for (i in 1..50000) {
            Log.v("Network call", "$i")
        }
        runOnUiThread {
            progressBar.visibility = View.INVISIBLE
        }
    }
}
</code>```

Body:
So I have made an app, and I'm trying to show the progress bar at the time when a button is clicked.

It shows only if I put the View.VISIBLE outside the handler.

Kotlin code:

button.setOnClickListener {

progressBar.visibility = View.VISIBLE
    runBlocking {

        try {
            //HTTP request removed because of confidentiality, assume I'm setting delay

        } catch (e: Exception) {
            Log.e(tag, "Error: " + e.message)
            Toast.makeText(this@MainActivity, "Could not find page", Toast.LENGTH_LONG)
                .show()
        }

    }
    progressBar.visibility = View.GONE
}

Button XML:

<ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:alpha="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility= "invisible"/>

I've been searching for hours now and couldn't find something relevant to my case.

Output wanted:
Get the progress bar at the time the button is clicked.

Body:
Executing a command like progressBar.visibility = View.VISIBLE may take a few nanoseconds(144100 approx).

The main thread might ask some other threads to perform some tasks and instead of waiting for the response of those threads, it resumes its normal execution(next lines of code). Your next line of code(runBlocking: Runs a new coroutine and blocks the current thread interruptibly until its completion.) blocks the current until the coroutine started from the runBlocking method is finished. This simply means that the Main thread can't execute other commands or process responses received from the other threads until the coroutine is finished.

Once the coroutine is finished. Main thread resumes its execution, showing and hiding progress bar simultaneously, which is why you don't see the progress bar spinning.

Main Thread should only be used for UI operations. Instead of blocking your main thread, you should perform the network operations in coroutine by switching to IO context.

Check here on types of Dispatchers.
https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb

bt.setOnClickListener {
    progressBar.visibility = View.VISIBLE
    GlobalScope.launch {
        networkCall()
    }

}

private suspend fun networkCall() {
    withContext(Dispatchers.Default) {
        for (i in 1..50000) {
            Log.v("Network call", "$i")
        }
        runOnUiThread {
            progressBar.visibility = View.INVISIBLE
        }
    }
}


问:
Getting this error while running a systemd service
[ERROR] 05:24:00+0100 [main] internal.NodeStartupLogging.invoke - Could not create the DataSource: liquibase.exception.DatabaseException: Error executing SQL UPDATE PUBLIC.DATABASECHHANGELOGLOCK SET LOCKED = TRUE, LOCKEDBY = '172.18.0.1 (172.18.0.1)', LOCKGRANTED = '2019-04-03 05:23:18.603' WHERE ID = 1 AND LOCKED = FALSE: The database is read only; SQL statement:

where should i run the update query to set locked = false in the server?

答:
However it's very late,
Maybe you have copied cordapp files from another location or previously have run the node by other user. Therefore, delete these files and directories:
persistence.mv.db ,
persistence.trace.db ,
additional-node-infos ,
artemis ,
brokers ,
capsule ,
drivers</p>


问:
Unable to install dapper 2.0.30 with .net framework 4.5
I am learning dapper ORM. While installing it through nuget package manager I am getting following error:

Could not install package 'Dapper 2.0.30'. You are trying to install
  this package into a project that targets '.NETFramework,Version=v4.5',
  but the package does not contain any assembly references or content
  files that are compatible with that framework. For more information,
  contact the package author.

In target framework option in project properties I've changed .net framework from 2.0 to 4.5.1

答:
No 2.* (or above) version of Dapper supports .NET 4.5.*, and there are no plans to do so. You will have to update your target framework, or stick with older versions of the tool. Preferably the first.

Ultimately you should expect this to be more and more of a problem if you choose to use old frameworks.


问:
API work but return Instance of class name
I have this Api,
printing the item oneJalsah is correct, but I have a problem when I return List, I get in the console
 ALL = [Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime']

here is my cod

```<code>class Day1API{
  Future<List<JalsahTime>> getDay1()async{

    String url = "http://www.something.......";
    JalsahTime oneJalsah;
    List<JalsahTime> allJalsay =  List<JalsahTime>();
        print(url);
    var response = await http.get(url);
    if (response.statusCode == 200){
      var data = jsonDecode(response.body);
      print(data);
      for (var item in data){
        print("item = $item");
        oneJalsah = JalsahTime(item['id'], item['day'], item['start'], item['end'], item['date'], item['stateDay'], item['stateTime']);
        allJalsay.add(oneJalsah);
      }
      print("ALL = $allJalsay");
      print('jalsah done');
      return allJalsay;
    }
    else print(" day failed");
  }
}
</code>```

here is my class

```<code>class JalsahTime{
  String id,day,start,end,date,stateDay,stateTime;
  JalsahTime(this.id, this.day, this.start, this.end, this.date, this.stateDay,
      this.stateTime);
}
</code>```

答:
Add toString method to your class

```<code>class JalsahTime{
  String id,day,start,end,date,stateDay,stateTime;
  JalsahTime(this.id, this.day, this.start, this.end, this.date, this.stateDay,
      this.stateTime);

  @override
  String toString(){
      return "Some representation of that instance: ${this.id}"
  }
}
</code>```

Body:
I have this Api,
printing the item oneJalsah is correct, but I have a problem when I return List, I get in the console
 ALL = [Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime', Instance of 'JalsahTime']

here is my cod

class Day1API{
  Future<List<JalsahTime>> getDay1()async{

    String url = "http://www.something.......";
    JalsahTime oneJalsah;
    List<JalsahTime> allJalsay =  List<JalsahTime>();
        print(url);
    var response = await http.get(url);
    if (response.statusCode == 200){
      var data = jsonDecode(response.body);
      print(data);
      for (var item in data){
        print("item = $item");
        oneJalsah = JalsahTime(item['id'], item['day'], item['start'], item['end'], item['date'], item['stateDay'], item['stateTime']);
        allJalsay.add(oneJalsah);
      }
      print("ALL = $allJalsay");
      print('jalsah done');
      return allJalsay;
    }
    else print(" day failed");
  }
}

here is my class

class JalsahTime{
  String id,day,start,end,date,stateDay,stateTime;
  JalsahTime(this.id, this.day, this.start, this.end, this.date, this.stateDay,
      this.stateTime);
}

Body:
Add toString method to your class

class JalsahTime{
  String id,day,start,end,date,stateDay,stateTime;
  JalsahTime(this.id, this.day, this.start, this.end, this.date, this.stateDay,
      this.stateTime);

  @override
  String toString(){
      return "Some representation of that instance: ${this.id}"
  }
}


问:
Find the total number of cycles in the given matrix
Gary has a board of size NxM. Each cell in the board is a coloured dot. There exist only 26 colours denoted by uppercase Latin characters (i.e. A,B,...,Z). Now Gary is getting bored and wants to play a game. The key to this game is to find a cycle that contains dots of the same colour. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:
1. These k dots are different: if i ≠ j then di is different from dj.
2. k is at least 4.
3. All dots belong to the same colour.
4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.

Input Format
Line 1:  Two integers N and M, the number of rows and columns of the board

Next N lines:  A string consisting of M characters, expressing colours of dots in each line. Each character is an uppercase Latin letter.

Output Format : Return 1 if there is a cycle else return 0

I thought that I'll make a 'visited' matrix which will mark 1 for an index if it has already been looked into.

Then, I'll traverse for each element and pass it to a new function which will work recursively and return 1 if the cycle exists.
3.I'll pass the visited matrix, dimensions of original matrix(will be same for visited matrix),int i, int j(i and j are the original indices passes to this function by our original function and does not change during recursive calls), int p, int q(p and q keep on changing to alternate eligible indices), count(if count>=4 and p and q becomes adjacent to i and j) return 1;

I'll also create an iseligible function to check if the given index is not out of bounds.

I need help with the approach too. I guess I've overcomplicated this problem. Please help me with it, like in what direction should I think.  I've already spent more than two days on it.

Solution.h

```<code>
int x[4]={0,0,1,-1};
int y[4]={1,-1,0,0};

int iseligible(char board[][MAXN], int n, int m, int i, int j, int** visited){

    if (i<m && j<n && i>=0 && j>=0 && visited[i][j]==0)
        return 1;

    return 0;
}

int solver(char board[][MAXN], int n, int m,int i, int j,int p, int q, int count, int** visited){

    //Base case-if our pq are surrounding of ij and count>=4

    for(int k=0;k<4;k++){

        if(count>=4 && p==i+x[k] && q==j+y[k]){
            return 1;
        }
    }

    for(int k=0;k<4;k++){
        if(iseligible(board, n, m, i+x[k], j+y[k], visited)==1){

            visited[i+x[k]][j+y[k]]==1;

            if(solver(board, n, m, i+x[k], j+y[k], i+x[k], j+y[k], 1, visited)){
                return 1;
            }

            if(solver(board, n, m, i, j, i+x[k], j+y[k], count+1, visited)==1){
                return 1;
            }

        }
    }

    return 0;
}

int solve(char board[][MAXN],int n, int m)
{
    int result=0;
    int** visited = new int*[m];

    for(int i=0;i<m;i++){
        visited[i] = new int[n];

        for(int j = 0; i<n; j++){
            visited[i][j] = 0;

        }
    }

    for(int i = 0;i<n;i++){
        for(int j = 0;j<m;j++){
            visited[i][j]=1;
            if(solver(board, n, m, i, j, i, j, 1, visited) == 1){
                return 1;
            }
        }
    }

    return 0;

}

</code>```

Input handling is done below and it cannot be altered

```<code>#include<bits/stdc++.h>
using namespace std;
#define MAXN 51
#include "solution.h"
int main()
{
    int N,M,i;
    char board[MAXN][MAXN];
    cin>>N>>M;
    for(i = 0;i < N; i++){
        cin>>board[i];
    }
    cout<<solve(board,N,M)<<endl;
}

</code>```

Input:
3 4
AAAA
ABCA
AAAA

Expected Output:
1

The output that I am getting:
Runtime error

答:
```<code>int xdir[4] = {1,-1,0,0};
int ydir[4] = {0,0,1,-1};
int visited[MAXN][MAXN];

bool eligible(char board[][MAXN], int n, int m, int i, int j, char curr){
    if(i>=0 && j>=0 && i<n && j<m && board[i][j]==curr)
        return true;
    return false;
}

int path_helper(char board[][MAXN], int n, int m, int i, int j, int fromx, int fromy, char curr){
    if(i>n || j>m)
        return 0;
    if(visited[i][j] == 1)
        return 1;
    if(board[i][j] != curr)
        return 0;

    visited[i][j] = 1;
    for(int k = 0 ; k < 4 ; k++){
        int dx = i + xdir[k];
        int dy = j + ydir[k];
        if(eligible(board,n,m,dx,dy,curr) && (dx!=fromx || dy!=fromy)){
            if(path_helper(board, n, m, dx, dy, i, j, curr) == 1)
                return 1;
        }
    }
    return 0;
}

int solve(char board[][MAXN],int n, int m)
{
    int ans = 0;
    memset(visited,0,sizeof(visited));
    for(int i = 0 ; i < n ; i++){
        for(int j = 0 ; j < m ; j++){
            if(visited[i][j] != 1){
                char curr = board[i][j];
                ans = path_helper(board, n, m, i, j, -1, -1, curr);
                if(ans==1)
                    return 1;
            }
        }
    }
    return ans;
}
</code>```

Body:
Gary has a board of size NxM. Each cell in the board is a coloured dot. There exist only 26 colours denoted by uppercase Latin characters (i.e. A,B,...,Z). Now Gary is getting bored and wants to play a game. The key to this game is to find a cycle that contains dots of the same colour. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:
1. These k dots are different: if i ≠ j then di is different from dj.
2. k is at least 4.
3. All dots belong to the same colour.
4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.

Input Format
Line 1:  Two integers N and M, the number of rows and columns of the board

Next N lines:  A string consisting of M characters, expressing colours of dots in each line. Each character is an uppercase Latin letter.

Output Format : Return 1 if there is a cycle else return 0

I thought that I'll make a 'visited' matrix which will mark 1 for an index if it has already been looked into.

Then, I'll traverse for each element and pass it to a new function which will work recursively and return 1 if the cycle exists.
3.I'll pass the visited matrix, dimensions of original matrix(will be same for visited matrix),int i, int j(i and j are the original indices passes to this function by our original function and does not change during recursive calls), int p, int q(p and q keep on changing to alternate eligible indices), count(if count>=4 and p and q becomes adjacent to i and j) return 1;

I'll also create an iseligible function to check if the given index is not out of bounds.

I need help with the approach too. I guess I've overcomplicated this problem. Please help me with it, like in what direction should I think.  I've already spent more than two days on it.

Solution.h

int x[4]={0,0,1,-1};
int y[4]={1,-1,0,0};

int iseligible(char board[][MAXN], int n, int m, int i, int j, int** visited){

    if (i<m && j<n && i>=0 && j>=0 && visited[i][j]==0)
        return 1;

    return 0;
}

int solver(char board[][MAXN], int n, int m,int i, int j,int p, int q, int count, int** visited){

    //Base case-if our pq are surrounding of ij and count>=4

    for(int k=0;k<4;k++){

        if(count>=4 && p==i+x[k] && q==j+y[k]){
            return 1;
        }
    }

    for(int k=0;k<4;k++){
        if(iseligible(board, n, m, i+x[k], j+y[k], visited)==1){

            visited[i+x[k]][j+y[k]]==1;

            if(solver(board, n, m, i+x[k], j+y[k], i+x[k], j+y[k], 1, visited)){
                return 1;
            }

            if(solver(board, n, m, i, j, i+x[k], j+y[k], count+1, visited)==1){
                return 1;
            }

        }
    }

    return 0;
}

int solve(char board[][MAXN],int n, int m)
{
    int result=0;
    int** visited = new int*[m];

    for(int i=0;i<m;i++){
        visited[i] = new int[n];

        for(int j = 0; i<n; j++){
            visited[i][j] = 0;

        }
    }

    for(int i = 0;i<n;i++){
        for(int j = 0;j<m;j++){
            visited[i][j]=1;
            if(solver(board, n, m, i, j, i, j, 1, visited) == 1){
                return 1;
            }
        }
    }

    return 0;

}

Input handling is done below and it cannot be altered

#include<bits/stdc++.h>
using namespace std;
#define MAXN 51
#include "solution.h"
int main()
{
    int N,M,i;
    char board[MAXN][MAXN];
    cin>>N>>M;
    for(i = 0;i < N; i++){
        cin>>board[i];
    }
    cout<<solve(board,N,M)<<endl;
}

Input:
3 4
AAAA
ABCA
AAAA

Expected Output:
1

The output that I am getting:
Runtime error


问:
Is there a way to assign automatic values to a 2D array in Python with a specific pattern without filling the whole array with just one value?
I'm trying to create a really basic snake-like console game just to test Python's functionality, yet I'm having issues with an algorithm I created for setting up the game map. I need the map borders to be set up as '#' and the map body as a space ' ' but for some reason the whole map is being shown as hashes, even after printing out the results in the decisive if function. Here's the code:

```<code>class GameMap:
def __init__(self):
    self.border_icon = '#'
    self.body_icon = ' '
    self.x_size = 0
    self.y_size = 0
    self.map_grid = []

def create_grid(self, map_size):
    if map_size == 1:
        self.x_size = 40
        self.y_size = 20
    elif map_size == 2:
        self.x_size = 80
        self.y_size = 40
    else:
        self.x_size = 120
        self.y_size = 60

    self.map_grid = [[None]*self.x_size]*self.y_size

    for row in range(self.y_size):
        for column in range(self.x_size):
            if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
                print('set: '+self.border_icon)
                self.map_grid[row][column] = self.border_icon
            else:
                print('set: '+self.body_icon)
                self.map_grid[row][column] = self.body_icon

def setup(self, map_type):
    map_templates = {
        1: 'Small Map (40x20)',
        2: 'Medium Map (80x40)',
        3: 'Big Map (120x60)'
    }
    if map_type not in map_templates:
        print('Invalid map type, starting a game with the default configuration...')
        map_type = 1

    print('Starting game: '+map_templates.get(map_type,'Invalid map type'))
    self.create_grid(map_type)
</code>```

This is the map class, in order to access it I just create a map object and call for the setup.
The issue is that whenever I display the matrix, the whole map is filled with '#' and no spaces whatsoever. Is there a reason for this?

答:
The problem is not in the For-loop, but, issue is in this line:

```<code>self.map_grid = [[None]*self.x_size]*self.y_size
</code>```

Say your self.x_size is 5 and self.y_size is 10, then, this line evaluates to this:

```<code>[[None, None, None, None, None]] * 10
</code>```

At this very moment you have a list having reference to inner list (which is its only element). Now, if you multiply with self.y_size, you are just getting 9 (in this case) more references to inner list. This is a very common misunderstanding among new Python developers.

There are 2 possible solutions for your problem:

Nested List Comprehension:

```<code>self.map_grid = [[None for _ in range(self.x_size)] for _ in range(self.y_size)]
</code>```

OR

```<code>self.map_grid = [[None] * self.x_size for _ in range(self.y_size)]
</code>```

Body:
I'm trying to create a really basic snake-like console game just to test Python's functionality, yet I'm having issues with an algorithm I created for setting up the game map. I need the map borders to be set up as '#' and the map body as a space ' ' but for some reason the whole map is being shown as hashes, even after printing out the results in the decisive if function. Here's the code:

class GameMap:
def __init__(self):
    self.border_icon = '#'
    self.body_icon = ' '
    self.x_size = 0
    self.y_size = 0
    self.map_grid = []

def create_grid(self, map_size):
    if map_size == 1:
        self.x_size = 40
        self.y_size = 20
    elif map_size == 2:
        self.x_size = 80
        self.y_size = 40
    else:
        self.x_size = 120
        self.y_size = 60

    self.map_grid = [[None]*self.x_size]*self.y_size

    for row in range(self.y_size):
        for column in range(self.x_size):
            if row==0 or row==self.y_size-1 or column==0 or column==self.x_size-1:
                print('set: '+self.border_icon)
                self.map_grid[row][column] = self.border_icon
            else:
                print('set: '+self.body_icon)
                self.map_grid[row][column] = self.body_icon

def setup(self, map_type):
    map_templates = {
        1: 'Small Map (40x20)',
        2: 'Medium Map (80x40)',
        3: 'Big Map (120x60)'
    }
    if map_type not in map_templates:
        print('Invalid map type, starting a game with the default configuration...')
        map_type = 1

    print('Starting game: '+map_templates.get(map_type,'Invalid map type'))
    self.create_grid(map_type)

This is the map class, in order to access it I just create a map object and call for the setup.
The issue is that whenever I display the matrix, the whole map is filled with '#' and no spaces whatsoever. Is there a reason for this?

Body:
The problem is not in the For-loop, but, issue is in this line:

self.map_grid = [[None]*self.x_size]*self.y_size

Say your self.x_size is 5 and self.y_size is 10, then, this line evaluates to this:

[[None, None, None, None, None]] * 10

At this very moment you have a list having reference to inner list (which is its only element). Now, if you multiply with self.y_size, you are just getting 9 (in this case) more references to inner list. This is a very common misunderstanding among new Python developers.

There are 2 possible solutions for your problem:

Nested List Comprehension:

self.map_grid = [[None for _ in range(self.x_size)] for _ in range(self.y_size)]

OR

self.map_grid = [[None] * self.x_size for _ in range(self.y_size)]


问:
Multiline plot for each id
I would like to plot multiple lines in Python for this dataset: (x = year, y = freq)

```<code>Student_ID  Year    Freq
A           2012    6
B           2008    22
C           2009    18
A           2010    7
B           2012    13
D           2012    31
D           2013    1
</code>```

where each student_id has data for different years. count is the result of a groupby.
I would like to have one line for each student_id.

I have tried with this:

```<code>df.groupby(['year'])['freq'].count().plot()
</code>```

but it does not plot one line for each student_id.

Any suggestions are more than welcome. Thank you for your help

答:
I wasn't sure from your question if you wanted count (which in your example is all ones) or sum, so I solved this with sum - if you'd like count, just swap it out for sum in the first line.

```<code>df_ = df.groupby(['Student_ID', 'Year'])['Freq'].sum()
print(df_)

> Student_ID  Year
A           2010     7
            2012     6
B           2008    22
            2012    13
C           2009    18
D           2012    31
            2013     1
Name: Freq, dtype: int64

fig, ax = plt.subplots()
for student in set(a[0] for a in df_.index):
    df_[student].plot(ax=ax, label=student)
    plt.legend()
    plt.show()
</code>```

Which gives you:

Title: Multiline plot for each id

Body:
I would like to plot multiple lines in Python for this dataset: (x = year, y = freq)

Student_ID  Year    Freq
A           2012    6
B           2008    22
C           2009    18
A           2010    7
B           2012    13
D           2012    31
D           2013    1

where each student_id has data for different years. count is the result of a groupby.
I would like to have one line for each student_id.

I have tried with this:

df.groupby(['year'])['freq'].count().plot()

but it does not plot one line for each student_id.

Any suggestions are more than welcome. Thank you for your help

Body:
I wasn't sure from your question if you wanted count (which in your example is all ones) or sum, so I solved this with sum - if you'd like count, just swap it out for sum in the first line.

df_ = df.groupby(['Student_ID', 'Year'])['Freq'].sum()
print(df_)

> Student_ID  Year
A           2010     7
            2012     6
B           2008    22
            2012    13
C           2009    18
D           2012    31
            2013     1
Name: Freq, dtype: int64

fig, ax = plt.subplots()
for student in set(a[0] for a in df_.index):
    df_[student].plot(ax=ax, label=student)
    plt.legend()
    plt.show()

Which gives you:


问:
PHP function foreach/while loop save multiple or array of values
I have this code which I want to save all of the column values taken from Mysql database.

```<code><?php
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
    $data=$db->query("select * from item");
    foreach($data as $k=>$v){
    return $v['item_name'];
    }
}
echo itemName($db); //output:item1
?>
</code>```

The problem is above code only returned the first row of data. Although I can use echo inside of the foreach loop like "echo $v['item_name'];", then call the function which will output all the values like item1 item2 item2 etc. My question is how can I use return to save all off the values equivalent like echo does, but not immediately echoed out.

答:
Collect data in array and return this array from your function:</p>

```<code>$db = mysqli_connect('localhost','mysqluser','password','test');

function itemName($db){
    $data=$db->query("select * from item");
    $result = [];
    foreach($data as $v){
        $result[] = $v['item_name'];
    }
    return $result;
}

print_r(itemName($db));
</code>```

Body:
I have this code which I want to save all of the column values taken from Mysql database.

<?php
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
    $data=$db->query("select * from item");
    foreach($data as $k=>$v){
    return $v['item_name'];
    }
}
echo itemName($db); //output:item1
?>

The problem is above code only returned the first row of data. Although I can use echo inside of the foreach loop like "echo $v['item_name'];", then call the function which will output all the values like item1 item2 item2 etc. My question is how can I use return to save all off the values equivalent like echo does, but not immediately echoed out.

Body:
Collect data in array and return this array from your function:

$db = mysqli_connect('localhost','mysqluser','password','test');

function itemName($db){
    $data=$db->query("select * from item");
    $result = [];
    foreach($data as $v){
        $result[] = $v['item_name'];
    }
    return $result;
}

print_r(itemName($db));