问:
NTP client in infinite loop (Not working )
I have designed a client from the reference given here.

I modified the code (see below) to fulfill these requirements

print timestamps in milliseonds

within infinite loop for getting NTP timestamps, RTT etc.

to define a cycle time (get time every x second)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#define NTP_TIMESTAMP_DELTA 2208988800ull
#define ENDIAN_SWAP32(data)                                                    \
  ((data >> 24) |               /* right shift 3 bytes */                      \
   ((data & 0x00ff0000) >> 8) | /* right shift 1 byte */                       \
   ((data & 0x0000ff00) << 8) | /* left shift 1 byte */                        \
   ((data & 0x000000ff) << 24)) /* left shift 3 bytes */

void error(char *msg) {
  perror(msg); // Print the error message to stderr.
  exit(0);     // Quit the process.
}

int main(int argc, char *argv[]) {
  int sockfd, n;    // Socket file descriptor and the n return result from
                    // writing/reading from the socket.
  int portno = 123; // NTP UDP port number
  int i, z = 0;
  struct timeval tv1, tv2;

  typedef struct {
    unsigned li : 2; // Only two bits. Leap indicator.
    unsigned vn : 3; // Only three bits. Version number of the protocol.
    unsigned
        mode : 3; // Only three bits. Mode. Client will pick mode 3 for client.

    uint8_t stratum; // Eight bits. Stratum level of the local clock.
    uint8_t poll; // Eight bits. Maximum interval between successive messages.
    uint8_t precision; // Eight bits. Precision of the local clock.

    uint32_t rootDelay; // 32 bits. Total round trip delay time.
    uint32_t
        rootDispersion; // 32 bits. Max error aloud from primary clock source.
    uint32_t refId;     // 32 bits. Reference clock identifier.

    uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.
    uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.

    uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.
    uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.

    uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.
    uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.

    uint32_t txTm_s; // 32 bits and the most important field the client cares
                     // about. Transmit time-stamp seconds.
    uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.

  } ntp_packet; // Total: 384 bits or 48 bytes.

  // Create and zero out the packet. All 48 bytes worth.

  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  memset(&packet, 0, sizeof(ntp_packet));
  *((char *)&packet + 0) =
      0x1b; // Represents 27 in base 10 or 00011011 in base 2.

  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
  struct sockaddr_in serv_addr;        // Server address data structure.
  struct hostent *server;              // Server data structure.

  sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket.

  if (sockfd < 0)
    error("ERROR opening socket");

  server = gethostbyname(argv[1]); // Convert URL to IP.

  if (server == NULL)
    error("ERROR, no such host");
  // Zero out the server address structure.
  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  // Copy the server's IP address to the server address structure.
  bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  // Convert the port number integer to network big-endian style and save it to
  // the server address structure.
  serv_addr.sin_port = htons(portno);
  // Call up the server using its IP address and port number.
  if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    error("ERROR connecting");
  printf("\nNTP client started \n\n");

  while (1) {

    z = z + 1;
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    memset(&packet, 0, sizeof(ntp_packet));
    *((char *)&packet + 0) =
        0x1b; // Represents 27 in base 10 or 00011011 in base 2.
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
    gettimeofday(&tv1, NULL);
    unsigned long long millisecondsSinceEpochStart =
        (unsigned long long)(tv1.tv_sec) * 1000 +
        (unsigned long long)(tv1.tv_usec) / 1000;
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));

    if (n < 0)
      error("ERROR writing to socket");

    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
    if (n < 0)
      error("ERROR reading from socket");
    gettimeofday(&tv2, NULL);
    unsigned long long millisecondsSinceEpochEnd =
        (unsigned long long)(tv2.tv_sec) * 1000 +
        (unsigned long long)(tv2.tv_usec) / 1000;

    packet.precision = ntohl(packet.precision); // Precision

    packet.rootDelay = ntohl(packet.rootDelay);

    packet.rxTm_s = ntohl(packet.rxTm_s); // Time-stamp seconds.
    packet.rxTm_f = ntohl(packet.rxTm_f); // Time-stamp fraction of a second.

    packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.
    packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.

    // packet.rootDelay = ntohl(packet.rootDelay); // RTT
    // time_t rootDelay = ( time_t ) ( packet.rootDelay - NTP_TIMESTAMP_DELTA );

    printf("\n................................................................."
           "...\n");
    printf("\nIteration Number : %d\n", z);
    printf("..................................................................."
           "..\n");
    printf("NTP Telegram Contains\n");
    for (i = 0; i < sizeof(ntp_packet); i++) {
      if (i != 0 && i % 8 == 0)
        printf("\n");
      printf("0x%2x ", ptr[i]);
    }
    printf("\n\n\n");

    printf("Client Send Timestamp T1(ms): %llu\n", millisecondsSinceEpochStart);

    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
    printf("%llu\n", packet.rxTm_f);

    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
    printf("%llu\n", packet.txTm_f);

    printf("Client Recieve Timestamp T4(ms): %llu\n",
           millisecondsSinceEpochEnd);

    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);

    printf("Precision (calculated by NTP): %llu\n", packet.precision);

    sleep(atoi(argv[2]));
  }
  return 0;
  close(sockfd);
}
</code>```

Makefile:

```<code>.PHONY: all clean tags

CFLAGS := -Wall -O2

all: client

client: client.c
    $(CC) $(CFLAGS) $^ -o $@
    strip -s $@

tags:
    ctags -R .

clean:
    -rm *.o client
</code>```

make and run the code using

```<code>./client 0.pool.ntp.org 1
</code>```

The problem I am facing and need your suggestions possible code changes and improvements

The code doesn't work infinitely, it stops in between and doesn't print any output after some iteration (no error message is shown)

The timestamps are not of same size although 64 bits

RTT and precision print the same value and doesn't get updated in each iteration (Sometimes both shows 0)

How to build T2 from packet.rxTm_s and packet.rxTm_f as one timestamp of 64bit.

答:
When I compiled your code with some warnings flags, I got some warnings:

25 warnings generated.

Some are clearly not useful but some are really scary:

```<code>warning: implicit conversion changes signedness: 'int' to 'size_t' (aka 'unsigned long') [-Wsign-conversion]
        server->h_length);
        ~~~~~~~~^~~~~~~~
warning: declaration shadows a local variable [-Wshadow]
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
               ^
note: previous declaration is here
  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
             ^
warning: declaration shadows a local variable [-Wshadow]
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
             ^
note: previous declaration is here
  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
           ^
warning: implicit declaration of function 'gettimeofday' is invalid in C99 [-Wimplicit-function-declaration]
    gettimeofday(&tv1, NULL);
    ^
warning: implicit declaration of function 'write' is invalid in C99 [-Wimplicit-function-declaration]
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));
        ^
warning: implicit declaration of function 'read' is invalid in C99 [-Wimplicit-function-declaration]
    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
        ^
warning: implicit conversion loses integer precision: 'unsigned int' to 'uint8_t' (aka 'unsigned char') [-Wconversion]
    packet.precision = ntohl(packet.precision); // Precision
                     ~ ^~~~~~~~~~~~~~~~~~~~~~~
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
                                         ~~~~    ^~~~~~~~~~~~~
                                         %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("%llu\n", packet.rxTm_f);
            ~~~~     ^~~~~~~~~~~~~
            %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
                                          ~~~~    ^~~~~~~~~~~~~
                                          %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("%llu\n", packet.txTm_f);
            ~~~~     ^~~~~~~~~~~~~
            %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);
                                     ~~~~     ^~~~~~~~~~~~~~~~
                                     %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint8_t' (aka 'unsigned char') [-Wformat]
    printf("Precision (calculated by NTP): %llu\n", packet.precision);
                                           ~~~~     ^~~~~~~~~~~~~~~~
                                           %hhu
warning: implicit declaration of function 'sleep' is invalid in C99 [-Wimplicit-function-declaration]
    sleep(atoi(argv[2]));
    ^
warning: implicit declaration of function 'close' is invalid in C99 [-Wimplicit-function-declaration]
  close(sockfd);
  ^
warning: unused parameter 'argc' [-Wunused-parameter]
int main(int argc, char *argv[]) {
             ^
warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare]
    for (i = 0; i < sizeof(ntp_packet); i++) {
                ~ ^ ~~~~~~~~~~~~~~~~~~
warning: 'return' will never be executed [-Wunreachable-code-return]
  return 0;
         ^
warning: code will never be executed [-Wunreachable-code]
  close(sockfd);
</code>```

I didn't keep them all but there are still 19! First of all you should fix all of them because they are important in my opinion, and ignoring those would likely cause undefined behavior. After you've cleaned all these warnings, you could try again to debug your code. (Try to get to zero warnings with clang -Weverything; not all warnings are useful but try to understand them before ignoring them).

Next, I tested your code and it seemed to work on my machine. Yet, there is a lot of potential undefined behavior in your code. Bit fields are quite inconvenient as their layout is implementation-defined.

Nevertheless, I get this output:

```<code>....................................................................
Iteration Number : 42
.....................................................................
NTP Telegram Contains
0x1c 0x 2 0x 3 0x 0 0xd7 0x 7 0x 0 0x 0
0x 0 0x 0 0x 8 0xad 0xf7 0x5c 0x9c 0x6b
0xdd 0xd1 0xe8 0x64 0xc1 0x31 0xc9 0x4a
0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0
0xca 0xe8 0xd1 0xdd 0x66 0x71 0xa4 0x25
0xca 0xe8 0xd1 0xdd 0xb8 0xb0 0xa6 0x25

Client Send Timestamp T1(ms): 1512536048971
server Recieve Timestamp T2: 3721521354.631533926
server Transmit Timestamp T3: 3721521354.631681208
Client Recieve Timestamp T4(ms): 1512536048973
RTT (calculated by NTP): 2007
Precision (calculated by NTP): 0

// after some iteration

....................................................................
Iteration Number : 69
.....................................................................
NTP Telegram Contains
0x1c 0x 2 0x 3 0x 0 0xd7 0x 7 0x 0 0x 0
0x 0 0x 0 0x 8 0xc7 0xf7 0x5c 0x9c 0x6b
0xdd 0xd1 0xe8 0x64 0xc1 0x31 0xc9 0x4a
0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0
0xe5 0xe8 0xd1 0xdd 0xcf 0x58 0x20 0x37
0xe5 0xe8 0xd1 0xdd 0x86 0xaf 0x22 0x37

Client Send Timestamp T1(ms): 1512536076040
server Recieve Timestamp T2: 3721521381.924866767
server Transmit Timestamp T3: 3721521381.925020038
Client Recieve Timestamp T4(ms): 1512536076042
RTT (calculated by NTP): 2007
Precision (calculated by NTP): 0
</code>```

Which looks good to me.

So to answer to your questions:

The code didn't stop in my machine and worked as expected. Of course the reason why your code stopped is obvious: you have called write() and read() that could block until the I/O is completed. Remember that you are using UDP protocol, some packets will never arrive to the server or some packets from server will never reach you. If you want to code a real server, use something like select() or poll() or epoll().

NTP is at version 4, your code asks for 3 (0x1b; // Represents 27 in base 10 or 00011011 in base 2. => 3 for version field. By the way, you create a bit field... USE IT; don't use magic number). So I suppose that somehow you end up with a mix of version 3 and 4; the thing that I don't understand is that documentation of NTP claims the protocol to be backwards-compatible. To answer this question you should read the RFC V3 of NTP protocol (obsolete).

I have no idea of what is it and why it doesn't change.

I have no idea.

So, you will ask why do I answer you if I don't give you the answer to your question? It's because you've clearly misunderstood critical things.

First this tutorial is ******** (Linus' favorite word), you can't expect to parse a protocol with 30 lines of code in C when the last RFC of NTP protocol has 6163 lines ! You MUST read this protocol if you want to implement your own parser.

Secondly, the code of this tutorial is very badly written, my "wtf-o-matic" showed me a very high value of "wtf (worse than failure) by line". Why to use unsigned and not uint8_t for the bit field (bit fields are 80% implementation defined anyway) ? Why ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; and not ntp_packet packet = {0}; ? Why and why and why use memset(&packet, 0, sizeof(ntp_packet)); just after ??? And what is that *((char *)&packet + 0) = 0x1b;, this IS ******** ! Well, there is more to say but I will just advice you to use getaddrinfo() in place of all the mess of gethostbyname(), htons() and etc...

As a conclusion: read the RFC that I linked (NTP V4); and stop using this  "tutorial". If you want implement your own NTP library (the good news is coming), you could use the nice skeleton provided by the RFC, I was so happy to find a code example in a RFC that I made a gist of the example for you. And the good news is that the RFC is reduce by half in terms of documentation lines to read! So GL, HF in your lecture.

Body:
I have designed a client from the reference given here.

I modified the code (see below) to fulfill these requirements

print timestamps in milliseonds

within infinite loop for getting NTP timestamps, RTT etc.

to define a cycle time (get time every x second)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#define NTP_TIMESTAMP_DELTA 2208988800ull
#define ENDIAN_SWAP32(data)                                                    \
  ((data >> 24) |               /* right shift 3 bytes */                      \
   ((data & 0x00ff0000) >> 8) | /* right shift 1 byte */                       \
   ((data & 0x0000ff00) << 8) | /* left shift 1 byte */                        \
   ((data & 0x000000ff) << 24)) /* left shift 3 bytes */

void error(char *msg) {
  perror(msg); // Print the error message to stderr.
  exit(0);     // Quit the process.
}

int main(int argc, char *argv[]) {
  int sockfd, n;    // Socket file descriptor and the n return result from
                    // writing/reading from the socket.
  int portno = 123; // NTP UDP port number
  int i, z = 0;
  struct timeval tv1, tv2;

  typedef struct {
    unsigned li : 2; // Only two bits. Leap indicator.
    unsigned vn : 3; // Only three bits. Version number of the protocol.
    unsigned
        mode : 3; // Only three bits. Mode. Client will pick mode 3 for client.

    uint8_t stratum; // Eight bits. Stratum level of the local clock.
    uint8_t poll; // Eight bits. Maximum interval between successive messages.
    uint8_t precision; // Eight bits. Precision of the local clock.

    uint32_t rootDelay; // 32 bits. Total round trip delay time.
    uint32_t
        rootDispersion; // 32 bits. Max error aloud from primary clock source.
    uint32_t refId;     // 32 bits. Reference clock identifier.

    uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.
    uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.

    uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.
    uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.

    uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.
    uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.

    uint32_t txTm_s; // 32 bits and the most important field the client cares
                     // about. Transmit time-stamp seconds.
    uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.

  } ntp_packet; // Total: 384 bits or 48 bytes.

  // Create and zero out the packet. All 48 bytes worth.

  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  memset(&packet, 0, sizeof(ntp_packet));
  *((char *)&packet + 0) =
      0x1b; // Represents 27 in base 10 or 00011011 in base 2.

  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
  struct sockaddr_in serv_addr;        // Server address data structure.
  struct hostent *server;              // Server data structure.

  sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket.

  if (sockfd < 0)
    error("ERROR opening socket");

  server = gethostbyname(argv[1]); // Convert URL to IP.

  if (server == NULL)
    error("ERROR, no such host");
  // Zero out the server address structure.
  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  // Copy the server's IP address to the server address structure.
  bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  // Convert the port number integer to network big-endian style and save it to
  // the server address structure.
  serv_addr.sin_port = htons(portno);
  // Call up the server using its IP address and port number.
  if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    error("ERROR connecting");
  printf("\nNTP client started \n\n");

  while (1) {

    z = z + 1;
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    memset(&packet, 0, sizeof(ntp_packet));
    *((char *)&packet + 0) =
        0x1b; // Represents 27 in base 10 or 00011011 in base 2.
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
    gettimeofday(&tv1, NULL);
    unsigned long long millisecondsSinceEpochStart =
        (unsigned long long)(tv1.tv_sec) * 1000 +
        (unsigned long long)(tv1.tv_usec) / 1000;
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));

    if (n < 0)
      error("ERROR writing to socket");

    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
    if (n < 0)
      error("ERROR reading from socket");
    gettimeofday(&tv2, NULL);
    unsigned long long millisecondsSinceEpochEnd =
        (unsigned long long)(tv2.tv_sec) * 1000 +
        (unsigned long long)(tv2.tv_usec) / 1000;

    packet.precision = ntohl(packet.precision); // Precision

    packet.rootDelay = ntohl(packet.rootDelay);

    packet.rxTm_s = ntohl(packet.rxTm_s); // Time-stamp seconds.
    packet.rxTm_f = ntohl(packet.rxTm_f); // Time-stamp fraction of a second.

    packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.
    packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.

    // packet.rootDelay = ntohl(packet.rootDelay); // RTT
    // time_t rootDelay = ( time_t ) ( packet.rootDelay - NTP_TIMESTAMP_DELTA );

    printf("\n................................................................."
           "...\n");
    printf("\nIteration Number : %d\n", z);
    printf("..................................................................."
           "..\n");
    printf("NTP Telegram Contains\n");
    for (i = 0; i < sizeof(ntp_packet); i++) {
      if (i != 0 && i % 8 == 0)
        printf("\n");
      printf("0x%2x ", ptr[i]);
    }
    printf("\n\n\n");

    printf("Client Send Timestamp T1(ms): %llu\n", millisecondsSinceEpochStart);

    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
    printf("%llu\n", packet.rxTm_f);

    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
    printf("%llu\n", packet.txTm_f);

    printf("Client Recieve Timestamp T4(ms): %llu\n",
           millisecondsSinceEpochEnd);

    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);

    printf("Precision (calculated by NTP): %llu\n", packet.precision);

    sleep(atoi(argv[2]));
  }
  return 0;
  close(sockfd);
}

Makefile:

.PHONY: all clean tags

CFLAGS := -Wall -O2

all: client

client: client.c
    $(CC) $(CFLAGS) $^ -o $@
    strip -s $@

tags:
    ctags -R .

clean:
    -rm *.o client

make and run the code using

./client 0.pool.ntp.org 1

The problem I am facing and need your suggestions possible code changes and improvements

The code doesn't work infinitely, it stops in between and doesn't print any output after some iteration (no error message is shown)

The timestamps are not of same size although 64 bits

RTT and precision print the same value and doesn't get updated in each iteration (Sometimes both shows 0)

How to build T2 from packet.rxTm_s and packet.rxTm_f as one timestamp of 64bit.

Body:
When I compiled your code with some warnings flags, I got some warnings:

25 warnings generated.

Some are clearly not useful but some are really scary:

warning: implicit conversion changes signedness: 'int' to 'size_t' (aka 'unsigned long') [-Wsign-conversion]
        server->h_length);
        ~~~~~~~~^~~~~~~~
warning: declaration shadows a local variable [-Wshadow]
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
               ^
note: previous declaration is here
  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
             ^
warning: declaration shadows a local variable [-Wshadow]
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
             ^
note: previous declaration is here
  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
           ^
warning: implicit declaration of function 'gettimeofday' is invalid in C99 [-Wimplicit-function-declaration]
    gettimeofday(&tv1, NULL);
    ^
warning: implicit declaration of function 'write' is invalid in C99 [-Wimplicit-function-declaration]
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));
        ^
warning: implicit declaration of function 'read' is invalid in C99 [-Wimplicit-function-declaration]
    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
        ^
warning: implicit conversion loses integer precision: 'unsigned int' to 'uint8_t' (aka 'unsigned char') [-Wconversion]
    packet.precision = ntohl(packet.precision); // Precision
                     ~ ^~~~~~~~~~~~~~~~~~~~~~~
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
                                         ~~~~    ^~~~~~~~~~~~~
                                         %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("%llu\n", packet.rxTm_f);
            ~~~~     ^~~~~~~~~~~~~
            %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
                                          ~~~~    ^~~~~~~~~~~~~
                                          %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("%llu\n", packet.txTm_f);
            ~~~~     ^~~~~~~~~~~~~
            %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint32_t' (aka 'unsigned int') [-Wformat]
    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);
                                     ~~~~     ^~~~~~~~~~~~~~~~
                                     %u
warning: format specifies type 'unsigned long long' but the argument has type 'uint8_t' (aka 'unsigned char') [-Wformat]
    printf("Precision (calculated by NTP): %llu\n", packet.precision);
                                           ~~~~     ^~~~~~~~~~~~~~~~
                                           %hhu
warning: implicit declaration of function 'sleep' is invalid in C99 [-Wimplicit-function-declaration]
    sleep(atoi(argv[2]));
    ^
warning: implicit declaration of function 'close' is invalid in C99 [-Wimplicit-function-declaration]
  close(sockfd);
  ^
warning: unused parameter 'argc' [-Wunused-parameter]
int main(int argc, char *argv[]) {
             ^
warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare]
    for (i = 0; i < sizeof(ntp_packet); i++) {
                ~ ^ ~~~~~~~~~~~~~~~~~~
warning: 'return' will never be executed [-Wunreachable-code-return]
  return 0;
         ^
warning: code will never be executed [-Wunreachable-code]
  close(sockfd);

I didn't keep them all but there are still 19! First of all you should fix all of them because they are important in my opinion, and ignoring those would likely cause undefined behavior. After you've cleaned all these warnings, you could try again to debug your code. (Try to get to zero warnings with clang -Weverything; not all warnings are useful but try to understand them before ignoring them).

Next, I tested your code and it seemed to work on my machine. Yet, there is a lot of potential undefined behavior in your code. Bit fields are quite inconvenient as their layout is implementation-defined.

Nevertheless, I get this output:

....................................................................
Iteration Number : 42
.....................................................................
NTP Telegram Contains
0x1c 0x 2 0x 3 0x 0 0xd7 0x 7 0x 0 0x 0
0x 0 0x 0 0x 8 0xad 0xf7 0x5c 0x9c 0x6b
0xdd 0xd1 0xe8 0x64 0xc1 0x31 0xc9 0x4a
0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0
0xca 0xe8 0xd1 0xdd 0x66 0x71 0xa4 0x25
0xca 0xe8 0xd1 0xdd 0xb8 0xb0 0xa6 0x25

Client Send Timestamp T1(ms): 1512536048971
server Recieve Timestamp T2: 3721521354.631533926
server Transmit Timestamp T3: 3721521354.631681208
Client Recieve Timestamp T4(ms): 1512536048973
RTT (calculated by NTP): 2007
Precision (calculated by NTP): 0

// after some iteration

....................................................................
Iteration Number : 69
.....................................................................
NTP Telegram Contains
0x1c 0x 2 0x 3 0x 0 0xd7 0x 7 0x 0 0x 0
0x 0 0x 0 0x 8 0xc7 0xf7 0x5c 0x9c 0x6b
0xdd 0xd1 0xe8 0x64 0xc1 0x31 0xc9 0x4a
0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0 0x 0
0xe5 0xe8 0xd1 0xdd 0xcf 0x58 0x20 0x37
0xe5 0xe8 0xd1 0xdd 0x86 0xaf 0x22 0x37

Client Send Timestamp T1(ms): 1512536076040
server Recieve Timestamp T2: 3721521381.924866767
server Transmit Timestamp T3: 3721521381.925020038
Client Recieve Timestamp T4(ms): 1512536076042
RTT (calculated by NTP): 2007
Precision (calculated by NTP): 0

Which looks good to me.

So to answer to your questions:

The code didn't stop in my machine and worked as expected. Of course the reason why your code stopped is obvious: you have called write() and read() that could block until the I/O is completed. Remember that you are using UDP protocol, some packets will never arrive to the server or some packets from server will never reach you. If you want to code a real server, use something like select() or poll() or epoll().

NTP is at version 4, your code asks for 3 (0x1b; // Represents 27 in base 10 or 00011011 in base 2. => 3 for version field. By the way, you create a bit field... USE IT; don't use magic number). So I suppose that somehow you end up with a mix of version 3 and 4; the thing that I don't understand is that documentation of NTP claims the protocol to be backwards-compatible. To answer this question you should read the RFC V3 of NTP protocol (obsolete).

I have no idea of what is it and why it doesn't change.

I have no idea.

So, you will ask why do I answer you if I don't give you the answer to your question? It's because you've clearly misunderstood critical things.

First this tutorial is ******** (Linus' favorite word), you can't expect to parse a protocol with 30 lines of code in C when the last RFC of NTP protocol has 6163 lines ! You MUST read this protocol if you want to implement your own parser.

Secondly, the code of this tutorial is very badly written, my "wtf-o-matic" showed me a very high value of "wtf (worse than failure) by line". Why to use unsigned and not uint8_t for the bit field (bit fields are 80% implementation defined anyway) ? Why ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; and not ntp_packet packet = {0}; ? Why and why and why use memset(&packet, 0, sizeof(ntp_packet)); just after ??? And what is that *((char *)&packet + 0) = 0x1b;, this IS ******** ! Well, there is more to say but I will just advice you to use getaddrinfo() in place of all the mess of gethostbyname(), htons() and etc...

As a conclusion: read the RFC that I linked (NTP V4); and stop using this  "tutorial". If you want implement your own NTP library (the good news is coming), you could use the nice skeleton provided by the RFC, I was so happy to find a code example in a RFC that I made a gist of the example for you. And the good news is that the RFC is reduce by half in terms of documentation lines to read! So GL, HF in your lecture.


来源: stackexchange

问:
producing related 'detail' for a summary query
Data:

```<code>ID          CITY         SEX            AGE
1           NYC          M              23
2           NYC          M              28
3           NYC          F              22
4           NYC          F              19
5           LA           M              29
6           LA           M              25
7           LA           F              18
8           LA           F              21
</code>```

Query: I want to produce the ID of the youngest person for each gender from each city. There are 2 genders, and 2 cities in the data above (although there may be more cities in the actual data).

I want to solve this using both Microsoft Access as well as plain SQL

Below is my solution using Microsoft Access. Do you know a better
solution?

I don't know how to do this with plain SQL. What is your solution?

Data (in Access)

Query 1 (used by Query 2)

Query 2 (uses Query 1, and produces the IDs that I was looking for)

答:
TRY THIS: Use sub query in join with GROUP BY but it will return the youngest all if there are more than one youngest with same AGE

```<code>SELECT t.*
FROM table_name t
INNER JOIN (SELECT MIN(age) age, city, sex
            FROM table_name GROUP BY city, sex) t1 ON t1.age = t.AGE
                                AND t1.city = t.city
                                AND t1.sex = t.sex
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Data:

ID          CITY         SEX            AGE
1           NYC          M              23
2           NYC          M              28
3           NYC          F              22
4           NYC          F              19
5           LA           M              29
6           LA           M              25
7           LA           F              18
8           LA           F              21

Query: I want to produce the ID of the youngest person for each gender from each city. There are 2 genders, and 2 cities in the data above (although there may be more cities in the actual data).

I want to solve this using both Microsoft Access as well as plain SQL

Below is my solution using Microsoft Access. Do you know a better
solution?

I don't know how to do this with plain SQL. What is your solution?

Data (in Access)

Query 1 (used by Query 2)

Query 2 (uses Query 1, and produces the IDs that I was looking for)

Body:
TRY THIS: Use sub query in join with GROUP BY but it will return the youngest all if there are more than one youngest with same AGE

SELECT t.*
FROM table_name t
INNER JOIN (SELECT MIN(age) age, city, sex
            FROM table_name GROUP BY city, sex) t1 ON t1.age = t.AGE
                                AND t1.city = t.city
                                AND t1.sex = t.sex


问:
advantage of creating node server in background
Until today in all my node\express projects, I have created  the HTTP server in some file

```<code>var server = http.createServer(app);

    http.globalAgent.maxSockets = maxSockets;
    server.listen(port, function() {
        logger.info('App starting on : ' + port );
    });
</code>```

and called that file directly to start the app. Recently i am noticing some boilerplates, using the approach  of calling a starter file and based on arguments, spawn a  child process, be it building the app or starting the app

```<code>in package json
"start": "babel-node tools/run.js"

in run .js
// Launch `node build/server.js` on a background thread
function spawnServer() {
  return cp.spawn(
    'node',
    [
      // Pre-load application dependencies to improve "hot reload" restart time
      ...Object.keys(pkg.dependencies).reduce(
        (requires, val) => requires.concat(['--require', val]),
        [],
      ),
      // If the parent Node.js process is running in debug (inspect) mode,
      // launch a debugger for Express.js app on the next port
      ...process.execArgv.map(arg => {
        if (arg.startsWith('--inspect')) {
          const match = arg.match(/^--inspect=(\S+:|)(\d+)$/);
          if (match) debugPort = Number(match[2]) + 1;
          return `--inspect=${match ? match[1] : '0.0.0.0:'}${debugPort}`;
        }
        return arg;
      }),
      '--no-lazy',
      // Enable "hot reload", it only works when debugger is off
      ...(isDebug
        ? ['./server.js']
        : [
            '--eval',
            'process.stdin.on("data", data => { if (data.toString() === "load") require("./server.js"); });',
          ]),
    ],
    { cwd: './build', stdio: ['pipe', 'inherit', 'inherit'], timeout: 3000 },
  );
}
</code>```

eg : https://github.com/kriasoft/nodejs-api-starter/

how is this advantageous?

Body:
Until today in all my node\express projects, I have created  the HTTP server in some file

var server = http.createServer(app);

    http.globalAgent.maxSockets = maxSockets;
    server.listen(port, function() {
        logger.info('App starting on : ' + port );
    });

and called that file directly to start the app. Recently i am noticing some boilerplates, using the approach  of calling a starter file and based on arguments, spawn a  child process, be it building the app or starting the app

in package json
"start": "babel-node tools/run.js"

in run .js
// Launch `node build/server.js` on a background thread
function spawnServer() {
  return cp.spawn(
    'node',
    [
      // Pre-load application dependencies to improve "hot reload" restart time
      ...Object.keys(pkg.dependencies).reduce(
        (requires, val) => requires.concat(['--require', val]),
        [],
      ),
      // If the parent Node.js process is running in debug (inspect) mode,
      // launch a debugger for Express.js app on the next port
      ...process.execArgv.map(arg => {
        if (arg.startsWith('--inspect')) {
          const match = arg.match(/^--inspect=(\S+:|)(\d+)$/);
          if (match) debugPort = Number(match[2]) + 1;
          return `--inspect=${match ? match[1] : '0.0.0.0:'}${debugPort}`;
        }
        return arg;
      }),
      '--no-lazy',
      // Enable "hot reload", it only works when debugger is off
      ...(isDebug
        ? ['./server.js']
        : [
            '--eval',
            'process.stdin.on("data", data => { if (data.toString() === "load") require("./server.js"); });',
          ]),
    ],
    { cwd: './build', stdio: ['pipe', 'inherit', 'inherit'], timeout: 3000 },
  );
}

eg : https://github.com/kriasoft/nodejs-api-starter/

how is this advantageous?

Body:
In my experience this is not a widespread practice.  It appears based on the comments that they're doing it in order to be able to do configuration on command line options based on the environment and so on.  To be honest, this seems a bit counterproductive to me.

What I've seen far more often is to start node from the command line with just npm start.  package.json has several options for defining what that will do, but most often I would just have it call something simple like node server.js or similar.  If you have multiple options for starting that you want to offer (for example, turning on the debug flags and such), then just add more scripts and call npm run <scriptname> to make it happen.

Any other special sauce would be baked into the process manager of choice (systemd is my preference but others like pm2 exist and work well), and between that and the environment variables you can do all or most of what's in the above script without all the indirection.   I feel like the example you posted would really up the 'wtf-factor' if I were starting to maintain the app and didn't know that at it was doing things like that for me under the hood.


问:
RecyclerView strange adapter and rows behaviour
My RecyclerView have two problems :

The first problem is when i am finished working with its activity and press back button it creates the same activity again but after removing some row (Mostly from the end) ,, I don't know if the problem is it  creates the view on multiple phases or what .

The second problem is when i press some button(Like button for example) it recreates the activity with the new result at each time it is pressed .

here is my Adapter

```<code>    package com.example.agh.grad.Adapters;

import android.Manifest; import android.app.Activity; import
android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.agh.grad.ItemClickListner; import com.example.agh.grad.Models.Services; import com.example.agh.grad.R; import com.example.agh.grad.SearchServices; import com.example.agh.grad.ServiceDetail; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.parceler.Parcels; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by cz on 17/06/17. */ public class recylerServiceAdapter extends RecyclerView.Adapter<recylerServiceAdapter.ViewHolder> { ArrayList<Services> service; Context context; ItemClickListner clickListner; public recylerServiceAdapter(ArrayList<Services> service, Context context) { this.service = service; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recyler_services, parent, false); ViewHolder viewHolder = new ViewHolder(v); context= parent.getContext(); return viewHolder; }

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.tvServiceName.setText(service.get(position).getName());
    holder.tvServiceDisrption.setText(service.get(position).getServiceShortDesrption());
    holder.tvServiceProvider.setText(service.get(position).getServiceProvider());
    holder.tvLikeCounter.setText(String.valueOf(service.get(position).getLikes()));
    holder.tvDislikeCounter.setText(String.valueOf(service.get(position).getDislikes()));
    holder.tvLocationDescrption.setText(service.get(position).getLocationAddress());

    holder.tvServiceName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

    /*   Intent myIntent=   new Intent(context,SearchServices.class);
    context.startActivity(myIntent);*/
}
 });

       holder.btnLike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
            DatabaseReference ref = firedatabase.getReference("Services");
            DatabaseReference wantedService =    ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
     final  Long uplikes=    service.get(holder.getAdapterPosition()).getLikes()+1;

            wantedService.child("likes").setValue(uplikes, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    holder.tvLikeCounter.setText(String.valueOf(uplikes));
                }
            });
         // TODO: 11/10/17  update on the database

            //// TODO: 05/12/17  Check state of buttons and act upon it

            holder.btnLike.setClickable(false);//// TODO: 05/12/17 set a clicked icon
            holder.btnDislike.setClickable(false);
        }
    });
    holder.btnDislike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
            DatabaseReference ref = firedatabase.getReference("Services");
            DatabaseReference wantedService =    ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
            final  Long dislikes=    service.get(holder.getAdapterPosition()).getLikes()-1;

            wantedService.child("likes").setValue(dislikes, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    holder.tvLikeCounter.setText(String.valueOf(dislikes));
                }
            });
        }
    });
    holder.btnCall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + service.get(holder.getAdapterPosition()).getPhoneNumber()));

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Ask for permission
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            context.startActivity(callIntent);
        }
    });

    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent myIntent=   new Intent(context,ServiceDetail.class);

            myIntent.putExtra(SearchServices.PARCELER_TAG, Parcels.wrap(service.get(holder.getAdapterPosition()) ));
            context.startActivity(myIntent);

            ((Activity)context).finish();
        }
    });

}

@Override
public int getItemCount() {
    return service.size();
}

public void setClickListener(ItemClickListner itemClickListener) {
    this.clickListner = itemClickListener;
}

public class ViewHolder extends RecyclerView.ViewHolder  {
    @BindView (R.id.serviceName) TextView tvServiceName;
    @BindView (R.id.serviceProvider)TextView tvServiceProvider;
    @BindView (R.id.serviceShortDescrption)TextView tvServiceDisrption;
    @BindView (R.id.tvLikeCounter)TextView tvLikeCounter;
    @BindView (R.id.tvDislikeCounter)TextView tvDislikeCounter ;
    @BindView (R.id.locationDescrption)TextView tvLocationDescrption;

    @BindView (R.id.btnLike) Button btnLike;
    @BindView (R.id.btnDislike)  Button btnDislike;
    @BindView (R.id.btnCall) Button btnCall;
    @BindView (R.id.serviceCard) CardView cardView;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setTag(itemView);

        ButterKnife.bind(this, itemView);

    }

}
}
</code>```

and here is my activity

```<code>            public class MainActivity extends AppCompatActivity  {

List<String> arrayServices = new ArrayList<>();

RecyclerView recyclerViewServices;
recylerServiceAdapter recylerServiceAdapter;
 ArrayList<Services> newServices;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = this.getIntent();
  //  arrayServices= intent.getStringArrayListExtra("newServices");
 //   System.out.println(arrayServices.size());
   newServices = Parcels.unwrap(intent.getParcelableExtra(SearchServices.PARCELER_TAG)) ;

Log.e( "onCreate: ",newServices.toString() );
    recyclerViewServices = (RecyclerView) findViewById(R.id.recylerViewServiceDetail);
    recyclerViewServices.setLayoutManager(new LinearLayoutManager(this));
    recylerServiceAdapter = new recylerServiceAdapter(newServices, getApplicationContext());
    recyclerViewServices.setAdapter(recylerServiceAdapter);

   }
      }
</code>```

and my activity_main.xml

```<code>        <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lightPrimary"
tools:context="com.example.agh.grad.MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recylerViewServiceDetail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="5dp"
    tools:layout_editor_absoluteY="5dp" />
  </RelativeLayout>
</code>```

答:
Instead of using this in onClick

```<code>holder.getAdapterPosition()
</code>```

use

```<code>public void onBindViewHolder(final ViewHolder holder,final int position)

position
</code>```

Body:
My RecyclerView have two problems :

The first problem is when i am finished working with its activity and press back button it creates the same activity again but after removing some row (Mostly from the end) ,, I don't know if the problem is it  creates the view on multiple phases or what .

The second problem is when i press some button(Like button for example) it recreates the activity with the new result at each time it is pressed .

here is my Adapter

    package com.example.agh.grad.Adapters;

import android.Manifest; import android.app.Activity; import
android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.agh.grad.ItemClickListner; import com.example.agh.grad.Models.Services; import com.example.agh.grad.R; import com.example.agh.grad.SearchServices; import com.example.agh.grad.ServiceDetail; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.parceler.Parcels; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by cz on 17/06/17. */ public class recylerServiceAdapter extends RecyclerView.Adapter<recylerServiceAdapter.ViewHolder> { ArrayList<Services> service; Context context; ItemClickListner clickListner; public recylerServiceAdapter(ArrayList<Services> service, Context context) { this.service = service; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recyler_services, parent, false); ViewHolder viewHolder = new ViewHolder(v); context= parent.getContext(); return viewHolder; }

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.tvServiceName.setText(service.get(position).getName());
    holder.tvServiceDisrption.setText(service.get(position).getServiceShortDesrption());
    holder.tvServiceProvider.setText(service.get(position).getServiceProvider());
    holder.tvLikeCounter.setText(String.valueOf(service.get(position).getLikes()));
    holder.tvDislikeCounter.setText(String.valueOf(service.get(position).getDislikes()));
    holder.tvLocationDescrption.setText(service.get(position).getLocationAddress());

    holder.tvServiceName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

    /*   Intent myIntent=   new Intent(context,SearchServices.class);
    context.startActivity(myIntent);*/
}
 });

       holder.btnLike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
            DatabaseReference ref = firedatabase.getReference("Services");
            DatabaseReference wantedService =    ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
     final  Long uplikes=    service.get(holder.getAdapterPosition()).getLikes()+1;

            wantedService.child("likes").setValue(uplikes, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    holder.tvLikeCounter.setText(String.valueOf(uplikes));
                }
            });
         // TODO: 11/10/17  update on the database

            //// TODO: 05/12/17  Check state of buttons and act upon it

            holder.btnLike.setClickable(false);//// TODO: 05/12/17 set a clicked icon
            holder.btnDislike.setClickable(false);
        }
    });
    holder.btnDislike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final FirebaseDatabase firedatabase = FirebaseDatabase.getInstance();
            DatabaseReference ref = firedatabase.getReference("Services");
            DatabaseReference wantedService =    ref.child(String.valueOf(service.get(holder.getAdapterPosition()).getName()));
            final  Long dislikes=    service.get(holder.getAdapterPosition()).getLikes()-1;

            wantedService.child("likes").setValue(dislikes, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    holder.tvLikeCounter.setText(String.valueOf(dislikes));
                }
            });
        }
    });
    holder.btnCall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + service.get(holder.getAdapterPosition()).getPhoneNumber()));

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Ask for permission
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            context.startActivity(callIntent);
        }
    });

    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent myIntent=   new Intent(context,ServiceDetail.class);

            myIntent.putExtra(SearchServices.PARCELER_TAG, Parcels.wrap(service.get(holder.getAdapterPosition()) ));
            context.startActivity(myIntent);

            ((Activity)context).finish();
        }
    });

}

@Override
public int getItemCount() {
    return service.size();
}

public void setClickListener(ItemClickListner itemClickListener) {
    this.clickListner = itemClickListener;
}

public class ViewHolder extends RecyclerView.ViewHolder  {
    @BindView (R.id.serviceName) TextView tvServiceName;
    @BindView (R.id.serviceProvider)TextView tvServiceProvider;
    @BindView (R.id.serviceShortDescrption)TextView tvServiceDisrption;
    @BindView (R.id.tvLikeCounter)TextView tvLikeCounter;
    @BindView (R.id.tvDislikeCounter)TextView tvDislikeCounter ;
    @BindView (R.id.locationDescrption)TextView tvLocationDescrption;

    @BindView (R.id.btnLike) Button btnLike;
    @BindView (R.id.btnDislike)  Button btnDislike;
    @BindView (R.id.btnCall) Button btnCall;
    @BindView (R.id.serviceCard) CardView cardView;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setTag(itemView);

        ButterKnife.bind(this, itemView);

    }

}
}

and here is my activity

            public class MainActivity extends AppCompatActivity  {

List<String> arrayServices = new ArrayList<>();

RecyclerView recyclerViewServices;
recylerServiceAdapter recylerServiceAdapter;
 ArrayList<Services> newServices;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = this.getIntent();
  //  arrayServices= intent.getStringArrayListExtra("newServices");
 //   System.out.println(arrayServices.size());
   newServices = Parcels.unwrap(intent.getParcelableExtra(SearchServices.PARCELER_TAG)) ;

Log.e( "onCreate: ",newServices.toString() );
    recyclerViewServices = (RecyclerView) findViewById(R.id.recylerViewServiceDetail);
    recyclerViewServices.setLayoutManager(new LinearLayoutManager(this));
    recylerServiceAdapter = new recylerServiceAdapter(newServices, getApplicationContext());
    recyclerViewServices.setAdapter(recylerServiceAdapter);

   }
      }

and my activity_main.xml

        <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lightPrimary"
tools:context="com.example.agh.grad.MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recylerViewServiceDetail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="5dp"
    tools:layout_editor_absoluteY="5dp" />
  </RelativeLayout>

Body:
Instead of using this in onClick

holder.getAdapterPosition()

use

public void onBindViewHolder(final ViewHolder holder,final int position)

position


问:
How to refresh a User object cached in Google App Engine?
I use this User class provided by Google App Engine: from webapp2_extras.appengine.auth.models import User

I want to make some change to an instance of User via Data Store in the Google cloud console: change the name attribute of a User to something else.

As far as I know the User object is cached in some way. If I make the change directly in data store, how can I locate it in the memcache and delete it? My goal is to force the cached User object to be refreshed.

答:
The memcache key used can be found in google.appengine.ext.context.py: Context.get():

```<code>if use_memcache:
  mkey = self._memcache_prefix + key.urlsafe()
</code>```

The prefix (in my version at least) is 'NDB9:'. So to get the memcache key you can use something similar to:

```<code>from google.appengine.ext import ndb

key = ndb.Key('User', 5229916580741120)
mkey = 'NDB9:' + key.urlsafe()
print mkey
</code>```

This results in something like: NDB9:ahpzfmR5bmFtaWMtdHJhdmVsbGVyLTItdGVzdHIRCxIEVXNlchiAgIDAzZKlCQw

To delete:

```<code>from google.appengine.api import memcache
value = memcache.get(mkey)
result = memcache.delete(mkey)
print "Memcache delete result={}".format(result)
if result == 2:
  print "{} memcache value has been deleted".format(key)
elif result == 1:
  print "{} memcache value not found".format(key)
else:
  print "Failed to delete {} memcache value".format(key)
</code>```

Caveat: without the memcache.get() call before memcache.delete() the delete result was always '1' (not found) using the interactive console. Not sure why that's the case.

Body:
The memcache key used can be found in google.appengine.ext.context.py: Context.get():

if use_memcache:
  mkey = self._memcache_prefix + key.urlsafe()

The prefix (in my version at least) is 'NDB9:'. So to get the memcache key you can use something similar to:

from google.appengine.ext import ndb

key = ndb.Key('User', 5229916580741120)
mkey = 'NDB9:' + key.urlsafe()
print mkey

This results in something like: NDB9:ahpzfmR5bmFtaWMtdHJhdmVsbGVyLTItdGVzdHIRCxIEVXNlchiAgIDAzZKlCQw

To delete:

from google.appengine.api import memcache
value = memcache.get(mkey)
result = memcache.delete(mkey)
print "Memcache delete result={}".format(result)
if result == 2:
  print "{} memcache value has been deleted".format(key)
elif result == 1:
  print "{} memcache value not found".format(key)
else:
  print "Failed to delete {} memcache value".format(key)

Caveat: without the memcache.get() call before memcache.delete() the delete result was always '1' (not found) using the interactive console. Not sure why that's the case.


问:
In Rails 3 how can you access the user_id of the last user in the database in your model?
Edit See Below:

```<code>class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

```<code>validates_inclusion_of :user_id, :in 0..(can't figure out this piece)
</code>```

I was able to easily ensure the number entered for User_ID in numeric with:

```<code>validates_numericality_of :user_id
</code>```

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

答:
Since you're just doing this for learnings sake:

(A)
Check for "last id" presuming it is the "largest id value":

```<code>class Post < ActiveRecord::Base
  last_user_id = ActiveRecord::Base.connection.select_one('SELECT MAX(ID) AS "MAX_ID" FROM users')["MAX_ID"]
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

or

(B) MAX() will get the max value of the ID field. This may not necessarily be the "latest" record inserted. If you really want to get the "last user inserted" you could do this (checks for the latest time of insertion of the record):

```<code>class Post < ActiveRecord::Base
  last_user_id = ActiveRecord::Base.connection.select_one('SELECT ID AS "LAST_ID" FROM users WHERE created_at = (SELECT MAX(created_at) from users LIMIT1)')["LAST_ID"]
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Edit See Below:

class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

validates_inclusion_of :user_id, :in 0..(can't figure out this piece)

I was able to easily ensure the number entered for User_ID in numeric with:

validates_numericality_of :user_id

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

Body:
Since you're just doing this for learnings sake:

(A)
Check for "last id" presuming it is the "largest id value":

class Post < ActiveRecord::Base
  last_user_id = ActiveRecord::Base.connection.select_one('SELECT MAX(ID) AS "MAX_ID" FROM users')["MAX_ID"]
  validates_inclusion_of :user_id, :in => 0..last_user_id
end

or

(B) MAX() will get the max value of the ID field. This may not necessarily be the "latest" record inserted. If you really want to get the "last user inserted" you could do this (checks for the latest time of insertion of the record):

class Post < ActiveRecord::Base
  last_user_id = ActiveRecord::Base.connection.select_one('SELECT ID AS "LAST_ID" FROM users WHERE created_at = (SELECT MAX(created_at) from users LIMIT1)')["LAST_ID"]
  validates_inclusion_of :user_id, :in => 0..last_user_id
end


问:
Node JS res.sendFile() not working
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

```<code>const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})
</code>```

This is my route.js

```<code>const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

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

This is my helpers/index.js

```<code>var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

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

Directory Structure

```<code>>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json
</code>```

答:
Change:

```<code>res.sendFile(main.html);
</code>```

to:

```<code>res.sendFile("main.html");
</code>```

Without the quotes, it's trying to interpret main as a Javascript object which it looks for the .html property on.  But, there is apparently no object named main so you get ReferenceError: main is not defined.  You want to pass a string here instead.

Same for res.sendFile("chat.html");

If the files are not local to this module's directory, then you need to build a more complete path that specifies their location.  Given the file hierarchy you show, I think that might be something like this:

```<code>const path = require('path');
const options = {root: path.join(__dirname, "../views")};

res.sendFile("main.html", options);
</code>```

Title: Node JS res.sendFile() not working

Body:
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})

This is my route.js

const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router

This is my helpers/index.js

var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

module.exports = exports;

Directory Structure

>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json

Body:
Change:

res.sendFile(main.html);

to:

res.sendFile("main.html");

Without the quotes, it's trying to interpret main as a Javascript object which it looks for the .html property on.  But, there is apparently no object named main so you get ReferenceError: main is not defined.  You want to pass a string here instead.

Same for res.sendFile("chat.html");

If the files are not local to this module's directory, then you need to build a more complete path that specifies their location.  Given the file hierarchy you show, I think that might be something like this:

const path = require('path');
const options = {root: path.join(__dirname, "../views")};

res.sendFile("main.html", options);


问:
Xamarin Forms error while writing anim R$anim.class
Hello i am update to visual studio community 2017 15.5 on debug i have this error</p>

```<code>obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error
</code>```

答: Did you solved your problem? Restarting VS help though.. weird error</p>

Body:
Hello i am update to visual studio community 2017 15.5 on debug i have this error

obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error


问:
cx_Freeze:Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings'
I downloaded cx_Freeze from here, installed it successfully on Ubuntu following this thread .

After run python3 setup.py build in cx_Freeze/samples/simple,then change the dir to cx_Freeze/samples/simple/build/exe.linux-i686-3.4,run the following command ,I got the error

```<code>➜  exe.linux-i686-3.4  ./hello
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
[1]    3950 abort      ./hello
➜  exe.linux-i686-3.4
</code>```

any idea on fixing this issue ?

答:
For python 3.x you can use 6.0b from git:

pip install git+https://github.com/anthony-tuininga/cx_Freeze.git

Got rid of the error for me.

Body:
I downloaded cx_Freeze from here, installed it successfully on Ubuntu following this thread .

After run python3 setup.py build in cx_Freeze/samples/simple,then change the dir to cx_Freeze/samples/simple/build/exe.linux-i686-3.4,run the following command ,I got the error

➜  exe.linux-i686-3.4  ./hello
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
[1]    3950 abort      ./hello
➜  exe.linux-i686-3.4

any idea on fixing this issue ?


问:
Laravel mismatching IDs
My website currently has a weird bug that only shows itself on the live version, but not on my local setup.

Essentially, in this scenario, a user is trying to ask an artist (another type of user) for a quote, hence the requestQuote function.

```<code>public function requestQuote(Request $request, AppMailer $mailer) {

    $reciUsername = $request->input('recipient');
    $recipientID = User::where('username', $reciUsername)->value('id');
    $recipient = User::where('username', $reciUsername)->first();
    $active_commissions_count = Commission::where('artist_id', $recipientID)
            ->where('complete', 0)
            ->where('stripe_charge_id', '!=', "")
            ->where('stripe_charge_id', '!=', null)
            ->count();

    $this->validate($request, [
        'message' => 'required|max:5000|min:10',
    ]);

    $message = Auth::user()->messages()->create([
        'body' => $request->input('message'),
        'subject' => 'Status: Commission requested!',
        'recipient_id' => $recipientID,
        'sender_read' => 1,
        'is_quote' => 1,
        'quote_expires' => Carbon\Carbon::now()->addWeeks(1),
    ]);

    $from = Auth::user()->username;
    $mailer->sendQuoteRequestEmailTo($recipient, $from);

     Auth::user()->update([
        'timeout' =>  Carbon\Carbon::now(),
     ]);

    dd("Message ID: " . $message->id . " - Message User ID: " . $message->user_id);

    return redirect()->back()->with('info', 'Quote sent.');
}
</code>```

This creates a message which the artist can then read. In this scenario, the recipient_id user is the artist, and the user_id user is the one who made the original quote. This is not supposed to change at any point during this transaction.

You'll notice there's a diedump at the end there.

In this scenario, the dd returns

"QUOTE REQUEST - Message ID: 30 - Message User ID: 2 - Recipient ID: 21"

Great. Everything works well so far, and the correct message is sent through, with the correct user being shown as having sent the quote.

The problem happens when the artist replies to the quote.

```<code>public function quoteReply(Request $request, $messageId, AppMailer $mailer) {

    $this->validate($request, [
        "reply-{$messageId}" => 'max:5000',
        "price" => 'required|min:10|max:9999|numeric',
        "date" => 'required|date',
            ], [
        'max' => 'The text body has a maximum of 5000 characters.',
        'price.max' => 'Commissions have a maximum of 9999 US dollars.',
        'price.min' => 'Commissions have a minimum of 10 US dollars.',
    ]);

    $message = Message::notReply()->find($messageId);

    if (!$message) {
        return redirect()->route('home')->with('info', 'Something went wrong.');
    }

    $date = $request->input('date');
    $date2 = DateTime::createFromFormat('m/d/Y', $date);
    $date3 = $date2->format("Y-m-d");

    $reply = message::create([
                'body' => $request->input("reply-{$messageId}"),
                'sender_read' => 3,
                'reci_read' => 3,
            ])->user()->associate(Auth::user());

    Message::where('id', $messageId)->update([
        'updated_at' => Carbon\Carbon::now(),
        'subject' => 'Status: Price quote delivered.',
        'quoted' => 1,
        'price' => $request->input('price'),
        'estimated_date' => $date3,
        'quote_expires' => Carbon\Carbon::now()->addWeeks(1),
    ]);

    $userID = $message->value('user_id');
    $recipientID = $message->value('recipient_id');
    $user = User::where('id', $userID)->first();

    if (Auth::user()->id == $userID) {
        Message::where('id', $messageId)->update(['reci_read' => 0]);
    }

    if (Auth::user()->id == $recipientID) {
        Message::where('id', $messageId)->update(['sender_read' => 0]);
    }

    $message->replies()->save($reply);

    $from = Auth::user()->username;
    $mailer->sendQuoteReplyEmailTo($user, $from);

    dd("QUOTE REPLY - Message ID: " . $message->id . " - Message User ID: " . $message->user_id . " - Message Recipient ID: " . $message->recipient_id . " - User ID: " . $user->id );

    return redirect()->back()->with('info', 'Price quote delivered.');
}
</code>```

This will return:

"QUOTE REPLY - Message ID: 30 - Message User ID: 2 - Message Recipient
  ID: 21 - User ID: 3"

I first noticed this problem when the wrong user was receiving email. In fact it's ALWAYS the same user getting the email. User 3. If I use a different user for the artist, and a different user for the person requesting the quote, $user always becomes user 3.

Despite this, the correct users are still getting correct messages. At the moment this is only affecting who's getting the correct email in the quoteReply function.

What could be causing this?

答:
Switching

```<code>$userID = $message->value('user_id');
</code>```

to

```<code>$userID = $message->user_id;
</code>```

Fixed my problem.

Title: Laravel mismatching IDs

Body:
My website currently has a weird bug that only shows itself on the live version, but not on my local setup.

Essentially, in this scenario, a user is trying to ask an artist (another type of user) for a quote, hence the requestQuote function.

public function requestQuote(Request $request, AppMailer $mailer) {

    $reciUsername = $request->input('recipient');
    $recipientID = User::where('username', $reciUsername)->value('id');
    $recipient = User::where('username', $reciUsername)->first();
    $active_commissions_count = Commission::where('artist_id', $recipientID)
            ->where('complete', 0)
            ->where('stripe_charge_id', '!=', "")
            ->where('stripe_charge_id', '!=', null)
            ->count();

    $this->validate($request, [
        'message' => 'required|max:5000|min:10',
    ]);

    $message = Auth::user()->messages()->create([
        'body' => $request->input('message'),
        'subject' => 'Status: Commission requested!',
        'recipient_id' => $recipientID,
        'sender_read' => 1,
        'is_quote' => 1,
        'quote_expires' => Carbon\Carbon::now()->addWeeks(1),
    ]);

    $from = Auth::user()->username;
    $mailer->sendQuoteRequestEmailTo($recipient, $from);

     Auth::user()->update([
        'timeout' =>  Carbon\Carbon::now(),
     ]);

    dd("Message ID: " . $message->id . " - Message User ID: " . $message->user_id);

    return redirect()->back()->with('info', 'Quote sent.');
}

This creates a message which the artist can then read. In this scenario, the recipient_id user is the artist, and the user_id user is the one who made the original quote. This is not supposed to change at any point during this transaction.

You'll notice there's a diedump at the end there.

In this scenario, the dd returns

"QUOTE REQUEST - Message ID: 30 - Message User ID: 2 - Recipient ID: 21"

Great. Everything works well so far, and the correct message is sent through, with the correct user being shown as having sent the quote.

The problem happens when the artist replies to the quote.

public function quoteReply(Request $request, $messageId, AppMailer $mailer) {

    $this->validate($request, [
        "reply-{$messageId}" => 'max:5000',
        "price" => 'required|min:10|max:9999|numeric',
        "date" => 'required|date',
            ], [
        'max' => 'The text body has a maximum of 5000 characters.',
        'price.max' => 'Commissions have a maximum of 9999 US dollars.',
        'price.min' => 'Commissions have a minimum of 10 US dollars.',
    ]);

    $message = Message::notReply()->find($messageId);

    if (!$message) {
        return redirect()->route('home')->with('info', 'Something went wrong.');
    }

    $date = $request->input('date');
    $date2 = DateTime::createFromFormat('m/d/Y', $date);
    $date3 = $date2->format("Y-m-d");

    $reply = message::create([
                'body' => $request->input("reply-{$messageId}"),
                'sender_read' => 3,
                'reci_read' => 3,
            ])->user()->associate(Auth::user());

    Message::where('id', $messageId)->update([
        'updated_at' => Carbon\Carbon::now(),
        'subject' => 'Status: Price quote delivered.',
        'quoted' => 1,
        'price' => $request->input('price'),
        'estimated_date' => $date3,
        'quote_expires' => Carbon\Carbon::now()->addWeeks(1),
    ]);

    $userID = $message->value('user_id');
    $recipientID = $message->value('recipient_id');
    $user = User::where('id', $userID)->first();

    if (Auth::user()->id == $userID) {
        Message::where('id', $messageId)->update(['reci_read' => 0]);
    }

    if (Auth::user()->id == $recipientID) {
        Message::where('id', $messageId)->update(['sender_read' => 0]);
    }

    $message->replies()->save($reply);

    $from = Auth::user()->username;
    $mailer->sendQuoteReplyEmailTo($user, $from);

    dd("QUOTE REPLY - Message ID: " . $message->id . " - Message User ID: " . $message->user_id . " - Message Recipient ID: " . $message->recipient_id . " - User ID: " . $user->id );

    return redirect()->back()->with('info', 'Price quote delivered.');
}

This will return:

"QUOTE REPLY - Message ID: 30 - Message User ID: 2 - Message Recipient
  ID: 21 - User ID: 3"

I first noticed this problem when the wrong user was receiving email. In fact it's ALWAYS the same user getting the email. User 3. If I use a different user for the artist, and a different user for the person requesting the quote, $user always becomes user 3.

Despite this, the correct users are still getting correct messages. At the moment this is only affecting who's getting the correct email in the quoteReply function.

What could be causing this?

Body:
Switching

$userID = $message->value('user_id');

to

$userID = $message->user_id;

Fixed my problem.


问:
Get error from my android login using php
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

```<code>public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}
</code>```

this is my androidmanifest.xml

```<code>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
</code>```

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

```<code>W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms
</code>```

答:
Please add permission

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

in your manifest file where you have declared other permissions

Body:
i rececntly learn about android and now i'm trying a simple login with my php. Please check my script first

public class MainActivity extends Activity {

    final Context context = this;
    private Button button;
    private EditText username;
    private EditText passsword;

    ProgressDialog progress;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void GoLogin(View v){

        username   = (EditText)findViewById(R.id.input_email);
        passsword   = (EditText)findViewById(R.id.input_password);

        String usernameval =  username.getText().toString();
        String passswordval =  md5(passsword.getText().toString());
        new AsyncLogin().execute(usernameval,passswordval);
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }
        protected String doInBackground(String... params) {
            try {

                url = new URL("http://127.0.0.1:84/fppb/Andro_login");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }

        }
        protected void onPostExecute(String result) {

            pdLoading.dismiss();
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            if(result.equalsIgnoreCase("true"))
            {
                Toast.makeText(MainActivity.this, "Login success", Toast.LENGTH_LONG).show();

            }else if (result.equalsIgnoreCase("false")){

                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "Cannot connect to main server", Toast.LENGTH_LONG).show();

            }
        }
    }

}

this is my androidmanifest.xml

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

when i try to run my app, i get this error

"Cannot connect to main server"

in my toast message after i submit at my form. How can i fix this ? thanks in advance ? sorry bad english

reference http://androidcss.com/android/android-php-mysql-login-tutorial/

after i read my log(s), i see this

W/System.err: java.net.SocketTimeoutException: failed to connect to /127.0.0.1 (port 84) from /10.0.2.15 (port 51319) after 10000ms

Body:
Please add permission

<uses-permission android:name="android.permission.INTERNET" />

in your manifest file where you have declared other permissions


问:
GCP Documentation - Task Queue bucket_size and rate
I read a lot of articles and answers here about Google Task, my doubt is "rate" and "bucket_size" behavior.

I read this documentation:
https://cloud.google.com/appengine/docs/standard/java/configyaml/queue

The snippet is:

Configuring the maximum number of concurrent requests

If using the default max_concurrent_requests settings are not
  sufficient, you can change the settings for max_concurrent_requests,
  as shown in the following example:

If your application queue has a rate of 20/s and a bucket size of 40,
  tasks in that queue execute at a rate of 20/s and can burst up to 40/s
  briefly. These settings work fine if task latency is relatively low;
  however, if latency increases significantly, you'll end up processing
  significantly more concurrent tasks. This extra processing load can
  consume extra instances and slow down your application.

For example, let's assume that your normal task latency is 0.3
  seconds. At this latency, you'll process at most around 40 tasks
  simultaneously. But if your task latency increases to 5 seconds, you
  could easily have over 100 tasks processing at once. This increase
  forces your application to consume more instances to process the extra
  tasks, potentially slowing down the entire application and interfering
  with user requests.

You can avoid this possibility by setting max_concurrent_requests to a
  lower value. For example, if you set max_concurrent_requests to 10,
  our example queue maintains about 20 tasks/second when latency is 0.3
  seconds. However, when the latency increases over 0.5 seconds, this
  setting throttles the processing rate to ensure that no more than 10
  tasks run simultaneously.

queue:

# Set the max number of concurrent requests to 50

- name: optimize-queue

    rate: 20/s

    bucket_size: 40

    max_concurrent_requests: 10

I understood that queue works like this:

The bucket is the unit that determine amount of tasks that are execute.

The rate is amount of bucket are fill to execute per period.

max_concurrent_requests is the max simultaneously can be executed.

This snippet here maybe strange:

But if your task latency increases to 5 seconds, you could easily have
  over 100 tasks processing at once. This increase forces your
  application to consume more instances to process the extra tasks,
  potentially slowing down the entire application and interfering with
  user requests.

Imagine that max_concurrent_requests is not setted.
For me, it is impossible execute more than 100 tasks because the bucket_size is 40. For me, the low tasks would impact on time that tasks will be wait for a empty bucket.

Why the documentation said that tasks can have over 100?

if the bucket is 40, can more than 40 run simultaneously?

Edit

The bucket is fill up just the all tasks were executed or if some bucket is free in next rate will be increase?
Example:
40 buckets are executing.
1 bucket finished.
Imagine that each bucket spend more than 0.5 seconds and some bucket more than 1s.
When 1 bucket is free, this will fill up in next second or the bucket wait all tasks finishing before bucket fill up again?

答:
Bucket size is defined more precisely in the doc you link, but one way to think of it is as a kind of initial burst limit.

Here's how I understand it would work, based on the parameters you provided in your question:

bucket_size: 40

rate: 20/s

max_concurrent_requests: 10

In the first second (t1) 40 tasks will start processing. At the same time 20 tokens (based on the rate) will be added to the bucket. Thus, at t2, 20 tasks will be primed for processing and another 20 tokens will be added to the bucket.

If there is no max_concurrent_setting, those 20 tasks would start processing. If max_concurrent_setting is 10, nothing will happen because more than 10 processes are already in use.

App Engine will continue to add tokens to the bucket at a rate of 20/s, but only if there is room in the bucket (bucket_size). Once there are 40 tokens in the bucket, it will stop until some of the running processes finish and there is more room.

After the initial burst of 40 tasks is finished, there should never be more than 10 tasks executing at a time.


问:
SQLite and iphone
I am sorry for asking such a noob question. I know that one way of storing data on the iphone via database is using SQLite, but after reading for a while it seems that the database is local and therefore each application has a copy of the database? is this right? if that is the case then what if I have two ipod with the same apps. and ipod A wants to update the database, then the data isn't reflected on ipod B?? Sorry for the noob questions</p>

答:
You overcome this by having a server which can synchronise the data between the apps. This is actually a much bigger problem than you might first think. In sonatribe.com we're having to consider situations where users aren't connected to the internet - so we queue the users actions and then push the data to the server when the device is connected. You then have to consider which database is the priority? Which one over writes the other when there are conflicts.

We also release new data for new events regularly - this data is then synchronised when the app is fired up.

One of the lessons we learned was that it's better to keep the number of calls down - connecting is expensive - but once connected the flow of data is fast.

FWIW - we went with MonoTouch - and the main reason was for the integration with WCF and the data capabilities (LINQ) of .NET. Using the SIlverlight profile and svcutil it's easy to get connected and communicate with web services passing complex objects over the wire - very handy for this sort of thing.

You also need to consider users who are on a limited data contract. We have the ability to turn off auto synch with the server in the settings. This is also useful for when our users are actually at the music festivals - in the UK, reception is renowned for being bad at events like this due to the sheer volume of people in one space. Although this is improving, users will appreciate the fact that they can stop the app communicating with a server on their behalf.

Title: SQLite and iphone


问:
Matlab One Hot Encoding - convert column with categoricals into several columns of logicals
CONTEXT

I have a large number of columns with categoricals, all with different, unrankable choices. To make my life easier for analysis, I'd like to take each of them and convert it to several columns with logicals. For example:

```<code>1   GENRE
2   Pop
3   Classical
4   Jazz
</code>```

...would turn into...

```<code>1   Pop Classical Jazz
2   1       0      0
3   0       1      0
4   0       0      1
</code>```

PROBLEM

I've tried using ind2vec but this only works with numericals or logicals. I've also come across this but am not sure it works with categoricals.  What is the right function to use in this case?

答:
ind2vec do work with the cell strings, and you could call cellstr function to get such a cell string.

This codes may help (From this ,I only changed a little)

```<code>data = categorical({'Pop'; 'Classical'; 'Jazz';});
GENRE = cellstr(data); %change categorical data into cell strings
[~, loc] = ismember(GENRE, unique(GENRE));
genre = ind2vec(loc')';
Gen=full(genre);
array2table(Gen, 'VariableNames', unique(GENRE))
</code>```

run such a code will return this:

ans =

```<code>Classical    Jazz    Pop
_________    ____    ___

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

you can call unique(GENRE) to check the categories(in cell strings). In the meanwhile, logical(Gen)(or call logical(full(genre))) contain columns with logical that you need.

P.s. categorical structure might be faster than cell string, but ind2vec function doesn't work with it. unique and accumarray might better.

Body:
CONTEXT

I have a large number of columns with categoricals, all with different, unrankable choices. To make my life easier for analysis, I'd like to take each of them and convert it to several columns with logicals. For example:

1   GENRE
2   Pop
3   Classical
4   Jazz

...would turn into...

1   Pop Classical Jazz
2   1       0      0
3   0       1      0
4   0       0      1

PROBLEM

I've tried using ind2vec but this only works with numericals or logicals. I've also come across this but am not sure it works with categoricals.  What is the right function to use in this case?

Body:
ind2vec do work with the cell strings, and you could call cellstr function to get such a cell string.

This codes may help (From this ,I only changed a little)

data = categorical({'Pop'; 'Classical'; 'Jazz';});
GENRE = cellstr(data); %change categorical data into cell strings
[~, loc] = ismember(GENRE, unique(GENRE));
genre = ind2vec(loc')';
Gen=full(genre);
array2table(Gen, 'VariableNames', unique(GENRE))

run such a code will return this:

ans =

Classical    Jazz    Pop
_________    ____    ___

0            0       1
1            0       0
0            1       0

you can call unique(GENRE) to check the categories(in cell strings). In the meanwhile, logical(Gen)(or call logical(full(genre))) contain columns with logical that you need.

P.s. categorical structure might be faster than cell string, but ind2vec function doesn't work with it. unique and accumarray might better.