text:
#include "mm_qcamera_socket.h"
#include "mm_qcamera_commands.h"
#include "mm_qcamera_dbg.h"

#define IP_ADDR                  "127.0.0.1"
#define TUNING_CHROMATIX_PORT     55555
#define TUNING_PREVIEW_PORT       55556

#define CURRENT_COMMAND_ACK_SUCCESS 1
#define CURRENT_COMMAND_ACK_FAILURE 2

pthread_t eztune_thread_id;

static ssize_t tuneserver_send_command_rsp(tuningserver_t *tsctrl,
  char *send_buf, uint32_t send_len)
{
  ssize_t rc;

  /* send ack back to client upon req */
  if (send_len <= 0) {
    ALOGE("%s:Invalid send len \n", __func__);
    return -1;
  }
  if (send_buf == NULL) {
    ALOGE("%s:Invalid send buf \n", __func__);
    return -1;
  }

  rc = send(tsctrl->clientsocket_id, send_buf, send_len, 0);
  if (rc < 0) {
    ALOGE("%s:RSP send returns error %s\n", __func__, strerror(errno));
  } else {
    rc = 0;
  }

  if (send_buf != NULL) {
    free(send_buf);
    send_buf = NULL;
  }
  return rc;
}

static void release_eztune_prevcmd_rsp(eztune_prevcmd_rsp *pHead)
{
  if (pHead != NULL ) {
    release_eztune_prevcmd_rsp((eztune_prevcmd_rsp *)pHead->next);
    free(pHead);
  }
}

static ssize_t tuneserver_ack(uint16_t a, uint32_t b, tuningserver_t *tsctrl)
{
  ssize_t rc;
  char ack_1[6];
  /*Ack the command here*/
  memcpy(ack_1, &a, 2);
  memcpy(ack_1+2, &b, 4);
  /* send echo back to client upon accept */
  rc = send(tsctrl->clientsocket_id, &ack_1, sizeof(ack_1), 0);
  if (rc < 0) {
    ALOGE("%s: eztune_server_run: send returns error %s\n", __func__,
      strerror(errno));
    return rc;
  } else if (rc < (int32_t)sizeof(ack_1)) {
    /*Shouldn't hit this for packets <1K; need to re-send if we do*/
  }
  return 0;
}

static ssize_t tuneserver_send_command_ack( uint8_t ack,
    tuningserver_t *tsctrl)
{
  ssize_t rc;
  /* send ack back to client upon req */
  rc = send(tsctrl->clientsocket_id, &ack, sizeof(ack), 0);
  if (rc < 0) {
    ALOGE("%s:ACK send returns error %s\n", __func__, strerror(errno));
    return rc;
  }
  return 0;
}

/** tuneserver_process_command
 *    @tsctrl: the server control object
 *
 *  Processes the command that the client sent
 *
 *  Return: >=0 on success, -1 on failure.
 **/
static int32_t tuneserver_process_command(tuningserver_t *tsctrl,
  char *send_buf, uint32_t send_len)
{
  tuneserver_protocol_t *p = tsctrl->proto;
  int result = 0;

  CDBG("%s: Current command is %d\n", __func__, p->current_cmd);
  switch (p->current_cmd) {
  case TUNESERVER_GET_LIST:
    if(tuneserver_send_command_ack(CURRENT_COMMAND_ACK_SUCCESS, tsctrl)) {
      ALOGE("%s: Ack Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    result = tuneserver_process_get_list_cmd(tsctrl, p->recv_buf,
      send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if(tuneserver_send_command_rsp(tsctrl, send_buf, send_len)) {
      ALOGE("%s: RSP Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    break;

  case TUNESERVER_GET_PARMS:
    if(tuneserver_send_command_ack(CURRENT_COMMAND_ACK_SUCCESS, tsctrl)) {
      ALOGE("%s: Ack Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    result = tuneserver_process_get_params_cmd(tsctrl, p->recv_buf,
      send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if(tuneserver_send_command_rsp(tsctrl, send_buf, send_len)) {
      ALOGE("%s: RSP Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    break;

  case TUNESERVER_SET_PARMS:
    if(tuneserver_send_command_ack(CURRENT_COMMAND_ACK_SUCCESS, tsctrl)) {
      ALOGE("%s: Ack Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    result = tuneserver_process_set_params_cmd(tsctrl, p->recv_buf,
      send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if(tuneserver_send_command_rsp(tsctrl, send_buf, send_len)) {
      ALOGE("%s: RSP Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    break;

  case TUNESERVER_MISC_CMDS: {
    if(tuneserver_send_command_ack(CURRENT_COMMAND_ACK_SUCCESS, tsctrl)) {
      ALOGE("%s: Ack Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    result = tuneserver_process_misc_cmd(tsctrl, p->recv_buf,
      send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if(tuneserver_send_command_rsp(tsctrl, send_buf, send_len)) {
      ALOGE("%s: RSP Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    break;
  }

  default:
    if(tuneserver_send_command_ack(CURRENT_COMMAND_ACK_SUCCESS, tsctrl)) {
      ALOGE("%s: Ack Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    ALOGE("%s: p->current_cmd: default\n", __func__);
    result = -1;
    break;
  }

  return result;
}

/** tuneserver_process_client_message
 *    @recv_buffer: received message from the client
 *    @tsctrl: the server control object
 *
 *  Processes the message from client and prepares for next
 *  message.
 *
 *  Return: >=0 on success, -1 on failure.
 **/
static int32_t tuneserver_process_client_message(void *recv_buffer,
  tuningserver_t *tsctrl)
{
  int rc = 0;
  tuneserver_protocol_t *p = tsctrl->proto;

  switch (tsctrl->proto->next_recv_code) {
  case TUNESERVER_RECV_COMMAND:
    p->current_cmd = *(uint16_t *)recv_buffer;
    p->next_recv_code = TUNESERVER_RECV_PAYLOAD_SIZE;
    p->next_recv_len = sizeof(uint32_t);
    break;

  case TUNESERVER_RECV_PAYLOAD_SIZE:
    p->next_recv_code = TUNESERVER_RECV_PAYLOAD;
    p->next_recv_len = *(uint32_t *)recv_buffer;
    p->recv_len = p->next_recv_len;
    if (p->next_recv_len > TUNESERVER_MAX_RECV)
      return -1;
    if (p->next_recv_len == 0) {
      p->next_recv_code = TUNESERVER_RECV_RESPONSE;
      p->next_recv_len = sizeof(uint32_t);
    }
    break;

  case TUNESERVER_RECV_PAYLOAD:
    p->recv_buf = malloc(p->next_recv_len);
    if (!p->recv_buf) {
      ALOGE("%s:Error allocating memory for recv_buf %s\n", __func__,
        strerror(errno));
      return -1;
    }
    memcpy(p->recv_buf, recv_buffer, p->next_recv_len);
    p->next_recv_code = TUNESERVER_RECV_RESPONSE;
    p->next_recv_len = sizeof(uint32_t);
    /*Process current command at this point*/
    break;

  case TUNESERVER_RECV_RESPONSE:
    p->next_recv_code = TUNESERVER_RECV_COMMAND;
    p->next_recv_len = 2;
    p->send_len = *(uint32_t *)recv_buffer;
    p->send_buf =  (char *)calloc(p->send_len, sizeof(char *));
    if (!p->send_buf) {
      ALOGE("%s:Error allocating memory for send_buf %s\n", __func__,
        strerror(errno));
      return -1;
    }
    rc = tuneserver_process_command(tsctrl, p->send_buf, p->send_len);
    free(p->recv_buf);
    p->recv_buf = NULL;
    p->recv_len = 0;
    break;

  default:
    ALOGE("%s: p->next_recv_code: default\n", __func__);
    rc = -1;
    break;
  }

  return rc;
}

/** tuneserver_ack_onaccept_initprotocol
 *    @tsctrl: the server control object
 *
 *  Acks a connection from the cient and sets up the
 *  protocol object to start receiving commands.
 *
 *  Return: >=0 on success, -1 on failure.
 **/
static ssize_t tuneserver_ack_onaccept_initprotocol(tuningserver_t *tsctrl)
{
  ssize_t rc = 0;
  uint32_t ack_status;

  ALOGE("%s starts\n", __func__);
/*
  if(tsctrl->camera_running) {
    ack_status = 1;
  } else {
    ack_status = 2;
  }
*/
  ack_status = 1;

  rc = tuneserver_ack(1, ack_status, tsctrl);

  tsctrl->proto = malloc(sizeof(tuneserver_protocol_t));
  if (!tsctrl->proto) {
    ALOGE("%s: malloc returns NULL with error %s\n", __func__, strerror(errno));
    return -1;
  }

  tsctrl->proto->current_cmd    = 0xFFFF;
  tsctrl->proto->next_recv_code = TUNESERVER_RECV_COMMAND;
  tsctrl->proto->next_recv_len  = 2;
  tsctrl->proto->recv_buf       = NULL;
  tsctrl->proto->send_buf       = NULL;

  CDBG("%s end\n", __func__);

  return rc;
}

/** tuneserver_check_status
 *    @tsctrl: the server control object
 *
 *  Checks if camera is running and stops it.
 *
 *  Return: >=0 on success, -1 on failure.
 **/
#if 0
static void tuneserver_check_status(tuningserver_t *tsctrl)
{
  if (tsctrl->camera_running == 1) {
    /*TODO: Stop camera here*/
    tuneserver_stop_cam(&tsctrl->lib_handle);
  }
  tsctrl->camera_running = 0;

  tuneserver_close_cam(&tsctrl->lib_handle);
}
#endif

static ssize_t prevserver_send_command_rsp(tuningserver_t *tsctrl,
  char *send_buf, uint32_t send_len)
{
  ssize_t rc;

  /* send ack back to client upon req */
  if (send_len <= 0) {
    ALOGE("%s:Invalid send len \n", __func__);
    return -1;
  }
  if (send_buf == NULL) {
    ALOGE("%s:Invalid send buf \n", __func__);
    return -1;
  }

  rc = send(tsctrl->pr_clientsocket_id, send_buf, send_len, 0);
  if (rc < 0) {
    ALOGE("%s:RSP send returns error %s\n", __func__, strerror(errno));
  } else {
    rc = 0;
  }
  if (send_buf != NULL) {
    free(send_buf);
    send_buf = NULL;
  }
  return rc;
}

static void prevserver_init_protocol(tuningserver_t *tsctrl)
{
  tsctrl->pr_proto = malloc(sizeof(prserver_protocol_t));
  if (!tsctrl->pr_proto) {
    ALOGE("%s: malloc returns NULL with error %s\n",
     __func__, strerror(errno));
    return;
  }

  tsctrl->pr_proto->current_cmd    = 0xFFFF;
  tsctrl->pr_proto->next_recv_code = TUNE_PREV_RECV_COMMAND;
  tsctrl->pr_proto->next_recv_len  = 2;
}

static int32_t prevserver_process_command(
  tuningserver_t *tsctrl, char **send_buf, uint32_t *send_len)
{
  prserver_protocol_t *p = tsctrl->pr_proto;
  int result = 0;
  eztune_prevcmd_rsp *rsp_ptr=NULL, *rspn_ptr=NULL, *head_ptr=NULL;

  CDBG("%s: Current command is %d\n", __func__, p->current_cmd);
  switch (p->current_cmd) {
  case TUNE_PREV_GET_INFO:
    result = tuneserver_preview_getinfo(tsctrl, send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__,
        p->current_cmd);
      return -1;
    }
    rsp_ptr = (eztune_prevcmd_rsp *)*send_buf;
    if ((!rsp_ptr) || (!rsp_ptr->send_buf)) {
      ALOGE("%s: RSP ptr is NULL %d\n", __func__, p->current_cmd);
      return -1;
    }
    if (prevserver_send_command_rsp(tsctrl,
      rsp_ptr->send_buf, rsp_ptr->send_len)) {
      ALOGE("%s: RSP Failed for TUNE_PREV_GET_INFO ver cmd %d\n", __func__,
        p->current_cmd);
      return -1;
    }
    rspn_ptr = (eztune_prevcmd_rsp *)rsp_ptr->next;
    if ((!rspn_ptr) || (!rspn_ptr->send_buf)) {
      ALOGE("%s: RSP1 ptr is NULL %d\n", __func__, p->current_cmd);
      return -1;
    }
    if (prevserver_send_command_rsp(tsctrl,
        rspn_ptr->send_buf, rspn_ptr->send_len)) {
      ALOGE("%s: RSP Failed for TUNE_PREV_GET_INFO caps cmd %d\n", __func__,
        p->current_cmd);
      return -1;
    }
    free(rspn_ptr);
    free(rsp_ptr);
    break;

  case TUNE_PREV_CH_CNK_SIZE:
    result = tuneserver_preview_getchunksize(tsctrl, send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if (prevserver_send_command_rsp(tsctrl, *send_buf, *send_len)) {
      ALOGE("%s: RSP Failed for TUNE_PREV_CH_CNK_SIZE cmd %d\n", __func__,
        p->current_cmd);
      return -1;
    }
    break;

  case TUNE_PREV_GET_PREV_FRAME:
    result = tuneserver_preview_getframe(tsctrl, send_buf, send_len);
    if (result < 0) {
      ALOGE("%s: RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    rsp_ptr = (eztune_prevcmd_rsp *)*send_buf;
    if ((!rsp_ptr) || (!rsp_ptr->send_buf)) {
      ALOGE("%s: RSP ptr is NULL %d\n", __func__, p->current_cmd);
      return -1;
    }
    head_ptr = rsp_ptr;

    while (rsp_ptr != NULL) {
      if ((!rsp_ptr) || (!rsp_ptr->send_buf)) {
        ALOGE("%s: RSP ptr is NULL %d\n", __func__, p->current_cmd);
        return -1;
      }
      if (prevserver_send_command_rsp(tsctrl,
        rsp_ptr->send_buf, rsp_ptr->send_len)) {
        ALOGE("%s: RSP Failed for TUNE_PREV_GET_INFO ver cmd %d\n", __func__,
          p->current_cmd);
        return -1;
      }
      rsp_ptr = (eztune_prevcmd_rsp *)rsp_ptr->next;
    }
    release_eztune_prevcmd_rsp(head_ptr);
    break;

  case TUNE_PREV_GET_JPG_SNAP:
  case TUNE_PREV_GET_RAW_SNAP:
  case TUNE_PREV_GET_RAW_PREV:
    result = tuneserver_preview_unsupported(tsctrl, send_buf, send_len);
    if (result < 0) {
       ALOGE("%s:RSP processing Failed for cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    if (prevserver_send_command_rsp(tsctrl, *send_buf, *send_len)) {
      ALOGE("%s:RSP Failed for UNSUPPORTED cmd %d\n", __func__, p->current_cmd);
      return -1;
    }
    break;

  default:
    ALOGE("%s: p->current_cmd: default\n", __func__);
    result = -1;
    break;
  }

  return result;
}

/** previewserver_process_client_message
 *    @recv_buffer: received message from the client
 *    @tsctrl: the server control object
 *
 *  Processes the message from client and prepares for next
 *  message.
 *
 *  Return: >=0 on success, -1 on failure.
 **/
static int32_t prevserver_process_client_message(void *recv_buffer,
  tuningserver_t *tsctrl)
{
  int rc = 0;
  prserver_protocol_t *p = tsctrl->pr_proto;

  switch (p->next_recv_code) {
  case TUNE_PREV_RECV_COMMAND:
    CDBG("%s  %d\n", __func__, __LINE__);
    p->current_cmd = *(uint16_t *)recv_buffer;
    if(p->current_cmd != TUNE_PREV_CH_CNK_SIZE) {
      rc = prevserver_process_command(tsctrl,
        &p->send_buf, (uint32_t *)&p->send_len);
      break;
    }
    p->next_recv_code = TUNE_PREV_RECV_NEWCNKSIZE;
    p->next_recv_len = sizeof(uint32_t);
    CDBG("%s TUNE_PREV_COMMAND X\n", __func__);
    break;
  case TUNE_PREV_RECV_NEWCNKSIZE:
    CDBG("%s  %d\n", __func__, __LINE__);
    p->new_cnk_size = *(uint32_t *)recv_buffer;
    p->next_recv_code = TUNE_PREV_RECV_COMMAND;
    p->next_recv_len  = 2;
    rc = prevserver_process_command(tsctrl,
      &p->send_buf, (uint32_t *)&p->send_len);
    break;
  default:
    ALOGE("%s prev_proc->next_recv_code: default\n", __func__);
    rc = -1;
    break;
  }

  return rc;
}

/** tunning_server_socket_listen
 *    @ip_addr: the ip addr to listen
 *    @port: the port to listen
 *
 *  Setup a listen socket for eztune.
 *
 *  Return: >0 on success, <=0 on failure.
 **/
int tunning_server_socket_listen(const char* ip_addr, uint16_t port)
{
  int sock_fd = -1;
  mm_qcamera_sock_addr_t server_addr;
  int result;
  int option;
  int socket_flag;

  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.addr_in.sin_family = AF_INET;
  server_addr.addr_in.sin_port = (__be16) htons(port);
  server_addr.addr_in.sin_addr.s_addr = inet_addr(ip_addr);

  if (server_addr.addr_in.sin_addr.s_addr == INADDR_NONE) {
    ALOGE("[ERR] %s invalid address.\n", __func__);
    return -1;
  }

  /* Create an AF_INET stream socket to receive incoming connection ON */
  sock_fd = socket(AF_INET, SOCK_STREAM, 0);
  if (sock_fd < 0) {
    ALOGE("[ERR] %s socket failed\n", __func__);
    return sock_fd;
  }

  // set listen socket to non-block, but why??
  socket_flag = fcntl(sock_fd, F_GETFL, 0);
  fcntl(sock_fd, F_SETFL, socket_flag | O_NONBLOCK);

  /* reuse in case it is in timeout */
  option = 1;
  result = setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR,
    &option, sizeof(option));

  if (result < 0) {
    ALOGE("eztune setsockopt failed");
    close(sock_fd);
    sock_fd = -1;
    return sock_fd;
  }

  result = bind(sock_fd, &server_addr.addr, sizeof(server_addr.addr_in));
  if (result < 0) {
    ALOGE("eztune socket bind failed");
    close(sock_fd);
    sock_fd = -1;
    return sock_fd;
  }

  result = listen(sock_fd, 1);
  if (result < 0) {
    ALOGE("eztune socket listen failed");
    close(sock_fd);
    sock_fd = -1;
    return sock_fd;
  }

  CDBG_HIGH("%s. sock_fd: %d, listen at port: %d\n", __func__, sock_fd, port);

  return sock_fd;
}

/** main
 *
 *  Creates the server, and starts waiting for
 *  connections/messages from a prospective
 *  client
 *
 **/
void *eztune_proc(void *data)
{
  int server_socket = -1, client_socket = -1;
  int prev_server_socket = -1, prev_client_socket = -1;

  mm_qcamera_sock_addr_t addr_client_inet;
  socklen_t addr_client_len = sizeof(addr_client_inet.addr_in);
  int result;
  fd_set tsfds;
  int num_fds = 0;
  ssize_t recv_bytes;
  char buf[TUNESERVER_MAX_RECV];

  mm_camera_lib_handle *lib_handle = (mm_camera_lib_handle *)data;

  ALOGE(">>> Starting tune server <<< \n");

  // for eztune chromatix params
  server_socket = tunning_server_socket_listen(IP_ADDR, TUNING_CHROMATIX_PORT);
  if (server_socket <= 0) {
    ALOGE("[ERR] fail to setup listen socket for eztune chromatix parms...");
    return NULL;
  }
  prev_server_socket = tunning_server_socket_listen(IP_ADDR, TUNING_PREVIEW_PORT);
  if (prev_server_socket <= 0) {
    ALOGE("[ERR] fail to setup listen socket for eztune preview...\n");
    return NULL;
  }
  num_fds = TUNESERVER_MAX(server_socket, prev_server_socket);
  CDBG_HIGH("num_fds = %d\n", num_fds);

  do {
    FD_ZERO(&tsfds);
    FD_SET(server_socket, &tsfds);
    FD_SET(prev_server_socket, &tsfds);
    if (client_socket > 0) {
      FD_SET(client_socket, &tsfds);
    }
    if (prev_client_socket > 0) {
      FD_SET( prev_client_socket, &tsfds);
    }

    /* no timeout */
    result = select(num_fds + 1, &tsfds, NULL, NULL, NULL);
    if (result < 0) {
      ALOGE("[ERR] select failed: %s\n", strerror(errno));
      continue;
    }

    /*
     ** (1) CHROMATIX SERVER
     */
    if (FD_ISSET(server_socket, &tsfds)) {
      CDBG("Receiving New client connection\n");

      client_socket = accept(server_socket,
        &addr_client_inet.addr, &addr_client_len);
      if (client_socket == -1) {
        ALOGE("accept failed %s", strerror(errno));
        continue;
      }

      ALOGE("accept a new connect on 55555, sd(%d)\n", client_socket);
      num_fds = TUNESERVER_MAX(num_fds, client_socket);

      // open camera and get handle - this is needed to
      // be able to set parameters without starting
      // preview stream
      /*if (!tsctrl.camera_running) {
        result = tuneserver_open_cam(&tsctrl.lib_handle, &tsctrl);
        if(result) {
          printf("\n Camera Open Fail !!! \n");
          close(server_socket);
          return EXIT_FAILURE;
        }
      }*/
      result = tuneserver_open_cam(lib_handle);
      if(result) {
        ALOGE("\n Tuning Library open failed!!!\n");
        close(server_socket);
        return NULL;
      }
      lib_handle->tsctrl.clientsocket_id = client_socket;
      if (tuneserver_ack_onaccept_initprotocol(&lib_handle->tsctrl) < 0) {
        ALOGE("%s: Error while acking\n", __func__);
        close(client_socket);
        continue;
      }
      tuneserver_initialize_tuningp(lib_handle, client_socket,
        lib_handle->tsctrl.proto->send_buf, lib_handle->tsctrl.proto->send_len);
    }

    if (FD_ISSET(client_socket, &tsfds)) {
      if (lib_handle->tsctrl.proto == NULL) {
        ALOGE("%s: Cannot receive msg without connect\n", __func__);
        continue;
      }

      /*Receive message and process it*/
      recv_bytes = recv(client_socket, (void *)buf,
        lib_handle->tsctrl.proto->next_recv_len, 0);
      CDBG("Receive %lld bytes \n", (long long int) recv_bytes);

      if (recv_bytes == -1) {
        ALOGE("%s: Receive failed with error %s\n", __func__, strerror(errno));
        //tuneserver_check_status(&tsctrl);
        continue;
      } else if (recv_bytes == 0) {
        ALOGE("%s %d: connection has been terminated\n", __func__, __LINE__);

        tuneserver_deinitialize_tuningp(&lib_handle->tsctrl, client_socket,
          lib_handle->tsctrl.proto->send_buf,
          lib_handle->tsctrl.proto->send_len);
        free(lib_handle->tsctrl.proto);
        lib_handle->tsctrl.proto = NULL;

        close(client_socket);
        client_socket = 0;
        //tuneserver_check_status(&tsctrl);
      } else {
        CDBG("%s: Processing socket command\n", __func__);

        result = tuneserver_process_client_message(buf, &lib_handle->tsctrl);

        if (result < 0) {
          ALOGE("%s %d Protocol violated\n", __func__, __LINE__);

          free(lib_handle->tsctrl.proto);
          lib_handle->tsctrl.proto = NULL;

          close(client_socket);
          client_socket = 0;
          //tuneserver_check_status(&tsctrl);
          continue;
        }
      }
    }

    /*
     ** (2) PREVIEW SERVER
     */
    if (FD_ISSET(prev_server_socket, &tsfds)) {
      CDBG("Receiving New Preview client connection\n");

      prev_client_socket = accept(prev_server_socket,
        &addr_client_inet.addr, &addr_client_len);
      if (prev_client_socket == -1) {
        ALOGE("accept failed %s", strerror(errno));
        continue;
      }

      lib_handle->tsctrl.pr_clientsocket_id = prev_client_socket;

      CDBG("Accepted a new connection, fd(%d)\n", prev_client_socket);
      num_fds = TUNESERVER_MAX(num_fds, prev_client_socket);

      // start camera
      /*if (!tsctrl.camera_running) {
        result = 0;
        result = tuneserver_open_cam(&tsctrl.lib_handle, &tsctrl);
        if(result) {
          printf("\n Camera Open Fail !!! \n");
          return EXIT_FAILURE;
        }
      }*/
      cam_dimension_t dim;
      //dim.width = lib_handle->test_obj.buffer_width;
      //dim.height = lib_handle->test_obj.buffer_height;
      dim.width = DEFAULT_PREVIEW_WIDTH;
      dim.height = DEFAULT_PREVIEW_HEIGHT;

      CDBG("preview dimension info: w(%d), h(%d)\n", dim.width, dim.height);
      // we have to make sure that camera is running, before init connection,
      // because we need to know the frame size for allocating the memory.
      prevserver_init_protocol(&lib_handle->tsctrl);

      result = tuneserver_initialize_prevtuningp(lib_handle, prev_client_socket,
        dim, (char **)&lib_handle->tsctrl.proto->send_buf,
        &lib_handle->tsctrl.proto->send_len);
      if (result < 0) {
        ALOGE("tuneserver_initialize_prevtuningp error!");
        close(prev_client_socket);
        prev_client_socket = 0;
      }
    }

    if (FD_ISSET(prev_client_socket, &tsfds)) {
      recv_bytes = recv(prev_client_socket, (void *)buf,
        lib_handle->tsctrl.pr_proto->next_recv_len, 0);

      CDBG("%s prev_client_socket=%d\n", __func__, prev_client_socket);
      CDBG("%s next_recv_len=%d\n", __func__, buf[0]+buf[1]*256);

      if (recv_bytes <= 0) {
        if (recv_bytes == 0) {
          ALOGE("client close the connection.\n");
        } else {
          ALOGE("receive error: %s\n", strerror(errno));
        }

        //tuneserver_check_status(&tsctrl);
        // if recv error, we should close the connection, free the proto data,
        // AND wait for a new connecton..
        // close_connection();
        // stop_camera()
        // cleanup_proto_data();
        tuneserver_deinitialize_prevtuningp(&lib_handle->tsctrl,
          (char **)&lib_handle->tsctrl.proto->send_buf,
          &lib_handle->tsctrl.proto->send_len);
        close(prev_client_socket);
        prev_client_socket = 0;
      } else {
        result = prevserver_process_client_message((void *)buf,
          &lib_handle->tsctrl);
        if (result < 0) {
          ALOGE("%s %d Protocol violated\n", __func__, __LINE__);

          //free(tsctrl->preivew_proto);
          //free(tsctrl);
          //max_fd = ezt_parms_listen_sd + 1;
          tuneserver_deinitialize_prevtuningp(&lib_handle->tsctrl,
            (char **)&lib_handle->tsctrl.proto->send_buf,
            &lib_handle->tsctrl.proto->send_len);
          close(prev_client_socket);
          prev_client_socket = 0;
          //tuneserver_check_status(&tsctrl);
        }
        //sleep(1);
      }
    }
  } while (1);

  if (server_socket > 0) {
    close(server_socket);
  }
  if (client_socket > 0) {
    close(client_socket);
  }
  if (prev_server_socket > 0) {
    close(prev_server_socket);
  }
  if (prev_client_socket > 0) {
    close(prev_client_socket);
  }

  return EXIT_SUCCESS;
}

int eztune_server_start (void *lib_handle)
{
  return pthread_create(&eztune_thread_id, NULL,  eztune_proc, lib_handle);
}


text:
create class test_class (bigint_col bigint, char_col char(10));
insert into test_class(bigint_col, char_col) values (-100, 'minus');
insert into test_class(bigint_col, char_col) values (0, 'zero');
insert into test_class(bigint_col, char_col) values (100, 'plus');
insert into test_class(bigint_col, char_col) values (109, 'plus');
insert into test_class(bigint_col, char_col) values (100, 'plus');
insert into test_class(bigint_col, char_col) values (109, 'plus');
insert into test_class(bigint_col, char_col) values (NULL, 'null');

select char_col, VARIANCE(bigint_col) from test_class group by char_col order by 1;
select char_col, VARIANCE(DISTINCT bigint_col) from test_class group by char_col order by 1;
select char_col, VARIANCE(UNIQUE bigint_col) from test_class group by char_col order by 1;
select char_col, VARIANCE(ALL bigint_col) from test_class group by char_col order by 1;

drop class test_class;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\WebBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ConflictoDeInteresRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ConflictoDeInteresRepository extends EntityRepository
{
}


text:
package org.simpleframework.http.socket.table;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketTableRow {

   private final Map<String, WebSocketTableCell> cells;
   private final WebSocketValueEncoder encoder;
   private final WebSocketTableSchema schema;
   private final int index;

   public WebSocketTableRow(WebSocketTableSchema schema, int index) {
      this.cells = new ConcurrentHashMap<String, WebSocketTableCell>();
      this.encoder = new WebSocketValueEncoder();
      this.index = index;
      this.schema = schema;
   }

   public int getIndex(){
      return index;
   }

   public void setValue(String column, String value){
      WebSocketTableCell cell = getValue(column);

      if(cell == null) {
         WebSocketTableCell newCell = new WebSocketTableCell(column, value);
         List<String> columns = schema.columnNames();
         boolean match = false;
         for(String name : columns) {
            if(name.equals(column)) {
               match = true;
            }
         }
         if(!match) {
            throw new IllegalStateException("Could not find " + column + " in schema");
         }
         cells.put(column, newCell);
      } else {
         String previous = cell.getValue();

         if(previous != null && !previous.equals(value)) {
            WebSocketTableCell replaceCell = new WebSocketTableCell(column, value);
            cells.put(column, replaceCell);
         }
      }
   }

   public WebSocketTableCell getValue(String column) {
      return cells.get(column);
   }

   public String calculateChange(long lastUpdateDone) {
      StringBuilder builder = new StringBuilder();
      builder.append(index);
      builder.append(":");
      String delim = "";
      int count = 0;
      List<String> columns = schema.columnNames();
      for(int i = 0; i < columns.size(); i++){
         String column = columns.get(i);
         WebSocketTableCell cell = cells.get(column);
         if(cell != null) {
            long cellChanged = cell.getTimeStamp();
            long difference = cellChanged - lastUpdateDone;

            if(difference > 0) { // positive means change happened later than update
               builder.append(delim);
               builder.append(i);
               builder.append("=");
               builder.append(cell.getValue());
               count++;
               delim = ",";
            }
         }
      }
      if(count <= 0) {
         return "";
      }
      return builder.toString();
   }
}


text:
import serialWrapper
import packetBuilder
import packetParser
import socket
import Queue
import sys
import multiprocessing

from serial.tools import list_ports

commands_to_stm = packetBuilder.CommandsList()
current_module = sys.modules[__name__]
com_port = None

def create_connection_to_stm():
    port_number = get_com_port_number()
    return serialWrapper.SerialWrapper(port_number)

def get_com_port_number():
    vid = 1155
    pid = 22336
    snr = '3677346C3034'

    for port in list_ports.comports():
        if (port.serial_number == snr) and (port.pid == pid) and (port.vid == vid):
            return '/dev/' + port.name

def process_request(command, parameters):
    if parameters is '':
        reply = getattr(current_module, command)()
    else:
        reply = getattr(current_module, command)(parameters)
    return reply

def send_request(packet):
    return com_port.sendRequest(packet.bytearray).reply

def switch_on_pid():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOnPid)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_pid():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffPid)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_robot():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffRobot)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_on_tajectory_regulator():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOnTrajectoryRegulator)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_tajectory_regulator():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffTrajectoryRegulator)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_on_kinematic_calculator():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOnKinematicCalculation)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_kinematic_calculator():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffKinematicCalculation)
    reply_on_request = send_request(packet)
    return reply_on_request

def set_coordinates_without_movement(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.setCoordinates, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def set_coordinates_with_movement(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.setCorectCoordinates, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def get_current_coordinates():
    packet = packetBuilder.BuildPacket(commands_to_stm.getCurentCoordinates)
    reply_on_request = send_request(packet)
    return reply_on_request

def set_movement_speed(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.setMovementSpeed, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def go_to_global_point(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.addPointToStack, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def set_cube_manipulator_angle(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.setManipulatorAngle, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def close_cube_collector():
    packet = packetBuilder.BuildPacket(commands_to_stm.closeCubeCollector)
    reply_on_request = send_request(packet)
    return reply_on_request

def open_cube_collector():
    packet = packetBuilder.BuildPacket(commands_to_stm.openCubeCollector)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_on_vibration_table(parameter):
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOnVibrationTable, parameter)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_vibration_table():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffVibrationTable)
    reply_on_request = send_request(packet)
    return reply_on_request

def open_cubes_border():
    packet = packetBuilder.BuildPacket(commands_to_stm.openCubeBorder)
    reply_on_request = send_request(packet)
    return reply_on_request

def close_cubes_border():
    packet = packetBuilder.BuildPacket(commands_to_stm.closeCubeBorder)
    reply_on_request = send_request(packet)
    return reply_on_request

def is_point_was_reached():
    packet = packetBuilder.BuildPacket(commands_to_stm.isPointWasReached)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_on_collision_avoidance():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOnCollisionAvoidance)
    reply_on_request = send_request(packet)
    return reply_on_request

def switch_off_collision_avoidance():
    packet = packetBuilder.BuildPacket(commands_to_stm.switchOffCollisionAvoidance)
    reply_on_request = send_request(packet)
    return reply_on_request

def get_ik_data():
    packet = packetBuilder.BuildPacket(commands_to_stm.getDataIKSensors)
    reply_on_request = send_request(packet)
    return reply_on_request

def get_us_data():
    packet = packetBuilder.BuildPacket(commands_to_stm.getDataUSSensors)
    reply_on_request = send_request(packet)
    return reply_on_request

def get_robot_speeds():
    packet = packetBuilder.BuildPacket(commands_to_stm.getCurrentSpeed)
    reply_on_request = send_request(packet)
    return reply_on_request

def move_with_correction(parameters):
    packet = packetBuilder.BuildPacket(commands_to_stm.moveWithCorrection, parameters)
    reply_on_request = send_request(packet)
    return reply_on_request

def get_manipulator_angle():
    packet = packetBuilder.BuildPacket(commands_to_stm.getManipulatorAngle)
    reply_on_request = send_request(packet)
    return reply_on_request

def open_manipulator_big_angle():
    packet = packetBuilder.BuildPacket(commands_to_stm.openCubeManipulatorBigAngle)
    reply_on_request = send_request(packet)
    return reply_on_request

def open_cone_crasher():
    packet = packetBuilder.BuildPacket(commands_to_stm.openConeCrasher)
    reply_on_request = send_request(packet)
    return reply_on_request

def close_cone_crasher():
    packet = packetBuilder.BuildPacket(commands_to_stm.closeConeCrasher)
    reply_on_request = send_request(packet)
    return reply_on_request

def stmMainLoop(input_command_queue, reply_to_fsm_queue, reply_to_localization_queue):
    global com_port
    com_port = create_connection_to_stm()

    while(True):
        incoming_command = input_command_queue.get()
        #print incoming_command
        if incoming_command['request_source'] == 'fsm':
            reply = process_request(incoming_command['command'],
                                    incoming_command['parameters'])
            reply_to_fsm_queue.put(reply)
        elif incoming_command['request_source'] == 'localisation':
            reply = process_request(incoming_command['command'],
                                    incoming_command['parameters'])
            reply_to_localization_queue.put(reply)


text:
module.exports = {
    modules: {
        "fs": "fs",
        "request": "request",
        "trumpet": "trumpet",
        "zlib": "zlib",
        "JSONStream": "JSONStream",
        "iconv": "iconv",
        "es": "event-stream",
        "csv": "csv-streamify",
        "cp": "child_process",
        "Handlebars": "handlebars",
        "sprintf": "sprintf"
    },

    Readable: {
        "Read File": function(fileName /* input/people.csv|input/people.csv.gz|input/people_utf8.csv|input/people_euc-jp.csv|input/people_euc-jp.csv.gz|input/people.json|input/people.json.gz|input/people.tsv|input/people.tsv.gz */) {
            var fs = require("fs");
            return fs.createReadStream(fileName);
        },

        "HTTP GET Request": function(url /* http://localhost:8945/input/people.csv|http://localhost:8945/input/people.csv.gz|http://localhost:8945/input/people_utf8.csv|http://localhost:8945/input/people_euc-jp.csv|http://localhost:8945/input/people_euc-jp.csv.gz|http://localhost:8945/input/people.json|http://localhost:8945/input/people.json.gz|http://localhost:8945/input/people.tsv|http://localhost:8945/input/people.tsv.gz */) {
            var request = require("request");
            return request(url);
        }
    },

    Writable: {
        "Write File": function(fileName /* output/people.html|output/people.json|output/people.json.gz|output/people.csv|output/people.csv.gz|output/people.tsv|output/people.tsv.gz */) {
            var fs = require("fs");
            return fs.createWriteStream(fileName);
        },

        "HTTP PUT Request": function(url /* http://localhost:8945/output/people.html|http://localhost:8945/output/people.json|http://localhost:8945/output/people.json.gz|http://localhost:8945/output/people.csv|http://localhost:8945/output/people.csv.gz|http://localhost:8945/output/people.tsv|http://localhost:8945/output/people.tsv.gz */) {
            var request = require("request");
            return request.put(url);
        },

        "Insert HTML": function(inFile /* input/people_table_tmpl.html|input/people_ul_tmpl.html */, fileName /* output/people.html */, selector /* tbody|ul */) {
            var fs = require("fs");
            var trumpet = require("trumpet");
            var tr = trumpet();
            var trOut = fs.createReadStream(inFile)
                .pipe(tr)
                .pipe(fs.createWriteStream(fileName));
            return tr.select(selector).createWriteStream();
        }
    },

    Transform: {
        "Un-Gzip": function() {
            var zlib = require("zlib");
            return zlib.createGunzip();
        },

        "Gzip": function() {
            var zlib = require("zlib");
            return zlib.createGzip();
        },

        "Parse JSON": function(jsonPath /* * */) {
            var JSONStream = require("JSONStream");
            return JSONStream.parse(jsonPath);
        },

        "Turn Into JSON Array String": function() {
            var JSONStream = require("JSONStream");
            return JSONStream.stringify();
        },

        "Change Encoding": function(from /* EUC-JP */, to /* UTF-8 */) {
            var iconv = require("iconv");
            return new iconv.Iconv(from, to);
        },

        "Replace": function(from /* John */, to /* Bob */) {
            var es = require("event-stream");
            return es.replace(from, to);
        },

        "Split Strings": function(separator /* \n|\t|, */) {
            var es = require("event-stream");
            return es.split(separator);
        },

        "Split Strings into Array": function(separator /* \t|,|\n */) {
            var es = require("event-stream");
            return es.mapSync(function(data) {
                return data.split(separator);
            });
        },

        "Join Strings": function(separator /* \n|\t|, */) {
            var es = require("event-stream");
            return es.join(separator);
        },

        "Concat Strings": function() {
            var es = require("event-stream");
            return es.wait();
        },

        "Wrap Strings": function(start /*

Name	City
\n|
\n|
|Name,URL,City\n|Name\tURL\tCity\n */, end /* \n
|\n
| */) {
            var es = require("event-stream");
            return es.mapSync(function(data) {
                return start + data + end;
            });
        },

        "Parse CSV as Object": function() {
            var csv = require("csv-streamify");
            return csv({objectMode: true, columns: true});
        },

        "Parse TSV as Array": function() {
            var csv = require("csv-streamify");
            return csv({objectMode: true, delimiter: "\t"});
        },

        "Filter Using Grep": function(filter /* Brooklyn|New York|San Francisco */) {
            // You don't actually want to do it this way...
            var cp = require("child_process");
            var es = require("event-stream");
            var grep = cp.exec("grep " + filter);
            return es.duplex(grep.stdin, grep.stdout);
        },

        "Convert Object w/ Handlebars": function(source /*
{{Name}}	{{City}}
|
{{Name}} ({{City}})
 */) {
            var Handlebars = require("handlebars");
            var es = require("event-stream");
            var tmpl = Handlebars.compile(source);
            return es.mapSync(tmpl);
        },

        "Convert Array w/ Sprintf": function(format /*
%1$s	%3$s
|
%1$s (%3$s)
|%s,%s,"%s"|%s\t%s\t%s */) {
            var sprintf = require("sprintf");
            var es = require("event-stream");
            return es.mapSync(function(data) {
                return sprintf.vsprintf(format, data);
            });
        },

        "Convert Object w/ Sprintf": function(format /*
%(Name)s	%(City)s
|
%(Name)s (%(City)s)
|%(Name)s,%(URL)s,"%(City)s"|%(Name)s\t%(URL)s\t%(City)s */) {
            var sprintf = require("sprintf");
            var es = require("event-stream");
            return es.mapSync(function(data) {
                return sprintf.sprintf(format, data);
            });
        }
    }
};


text:
namespace ktt
{

CudaStream::CudaStream(const QueueId id) :
    m_Id(id),
    m_OwningStream(true)
{
    Logger::LogDebug("Initializing CUDA stream with id " + std::to_string(id));
    CheckError(cuStreamCreate(&m_Stream, CU_STREAM_DEFAULT), "cuStreamCreate");
}

CudaStream::CudaStream(const QueueId id, ComputeQueue stream) :
    m_Id(id),
    m_OwningStream(false)
{
    Logger::LogDebug("Initializing CUDA stream with id " + std::to_string(id));
    m_Stream = static_cast<CUstream>(stream);

    if (m_Stream == nullptr)
    {
        throw KttException("The provided user CUDA stream is not valid");
    }
}

CudaStream::~CudaStream()
{
    Logger::LogDebug("Releasing CUDA stream with id " + std::to_string(m_Id));

    if (m_OwningStream)
    {
        CheckError(cuStreamDestroy(m_Stream), "cuStreamDestroy");
    }
}

void CudaStream::Synchronize() const
{
    Logger::LogDebug("Synchronizing CUDA stream with id " + std::to_string(m_Id));
    CheckError(cuStreamSynchronize(m_Stream), "cuStreamSynchronize");
}

CUstream CudaStream::GetStream() const
{
    return m_Stream;
}

QueueId CudaStream::GetId() const
{
    return m_Id;
}

} // namespace ktt

#endif // KTT_API_CUDA


text:
A Ruby on Rails application generator that sets up the default Flatiron School stack. This stack includes:

1. Testing
  * RSpec
  * Capybara
  * Database Cleaner
  * SimpleCov
  * Guard
2. Frontend
  * Disabled Turbolinks
  * Bootstrap
  * Google Analytics
  * Precompiled assets in production
3. Deployment
  * Options to set up gem groups for either Heroku or Ninefold deployment
  * Automatically installs Heroku command line tools if they are missing
  * For Heroku deployment, adds bin files for two-line setup and deploy
4. Optional Devise setup
5. Airbrake integration

## Usage

`flatiron-rails new <app_name>`


text:
(function () {
'use strict';

  angular
    .module('app.controllers')
    .controller('HeaderRestController', HeaderRestController);

  function HeaderRestController($state,
                                $rootScope,
                                actions) {

    var vmHeader = this;
    vmHeader.searchForm = false;
    vmHeader.totalRest = 0;
    vmHeader.toggleSearch = toggleSearch;
    vmHeader.newItem = newItem

    init();

    function init() {
      vmHeader.showNewMenu = ($state.current.name === 'restaurant.menu');
      vmHeader.showNewRest = ($state.current.name === 'restaurant.list');
    }

    function newItem() {
      /*comunicate header and menu*/
      actions.newItem();
    }

    function toggleSearch() {
      vmHeader.searchForm = !vmHeader.searchForm;
      $rootScope.$broadcast('_SHOW_SEARCH_', vmHeader.searchForm);
    }

  }

})();


text:
package com.sksamuel.elastic4s.http.search.queries.specialized

import com.sksamuel.elastic4s.http.search.queries.QueryBuilderFn
import com.sksamuel.elastic4s.searches.queries.funcscorer.FunctionScoreQueryDefinition
import org.elasticsearch.common.bytes.BytesArray
import org.elasticsearch.common.xcontent.{XContentBuilder, XContentFactory, XContentType}

object FunctionScoreQueryBodyFn {

  def apply(q: FunctionScoreQueryDefinition): XContentBuilder = {
    val builder = XContentFactory.jsonBuilder()
    builder.startObject()
    builder.startObject("function_score")

    q.query.map(qDef => builder.rawField("query", QueryBuilderFn(qDef).bytes(), XContentType.JSON))
    q.minScore.map(builder.field("min_score", _))
    q.boost.map(builder.field("boost", _))
    q.maxBoost.map(builder.field("max_boost", _))
    q.scoreMode.map(sm => builder.field("score_mode", sm.toString.toLowerCase))
    q.boostMode.map(bm => builder.field("boost_mode", bm.toString.toLowerCase))

    if (q.scorers.nonEmpty) {
      builder.startArray("functions")
      val arrayBody = new BytesArray(q.scorers.map(scorer => FilterFunctionBodyFn(scorer).string).mkString(","))
      builder.rawValue(arrayBody, XContentType.JSON)
      builder.endArray()
    }

    builder.endObject()
    builder.endObject()
    builder
  }
}


text:
package publicsuffix

import (
	"bufio"
	"fmt"
	"io"
	"net/http/cookiejar"
	"os"
	"strings"

	"golang.org/x/net/idna"
)

const (
	// Version identifies the current library version.
	// This is a pro forma convention given that Go dependencies
	// tends to be fetched directly from the repo.
	Version = "0.15.0"

	// NormalType represents a normal rule such as "com"
	NormalType = 1
	// WildcardType represents a wildcard rule such as "*.com"
	WildcardType = 2
	// ExceptionType represents an exception to a wildard rule
	ExceptionType = 3

	listTokenPrivateDomains = "===BEGIN PRIVATE DOMAINS==="
	listTokenComment        = "//"
)

// DefaultList is the default List and it is used by Parse and Domain.
var DefaultList = NewList()

// DefaultRule is the default Rule that represents "*".
var DefaultRule = MustNewRule("*")

// DefaultParserOptions are the default options used to parse a Public Suffix list.
var DefaultParserOptions = &ParserOption{PrivateDomains: true, ASCIIEncoded: false}

// DefaultFindOptions are the default options used to perform the lookup of rules in the list.
var DefaultFindOptions = &FindOptions{IgnorePrivate: false, DefaultRule: DefaultRule}

// Rule represents a single rule in a Public Suffix List.
type Rule struct {
	Type    int
	Value   string
	Length  int
	Private bool
}

// ParserOption are the options you can use to customize the way a List
// is parsed from a file or a string.
type ParserOption struct {
	// Set to false to skip the private domains when parsing.
	// Default to true, which means the private domains are included.
	PrivateDomains bool

	// Set to false if the input is encoded in U-labels (Unicode)
	// as opposite to A-labels.
	// Default to false, which means the list is containing Unicode domains.
	// This is the default because the original PSL currently contains Unicode.
	ASCIIEncoded bool
}

// FindOptions are the options you can use to customize the way a Rule
// is searched within the list.
type FindOptions struct {
	// Set to true to ignore the rules within the "Private" section of the Public Suffix List.
	IgnorePrivate bool

	// The default rule to use when no rule matches the input.
	// The format Public Suffix algorithm states that the rule "*" should be used when no other rule matches,
	// but some consumers may have different needs.
	DefaultRule *Rule
}

// List represents a Public Suffix List.
type List struct {
	// rules is kept private because you should not access rules directly
	rules map[string]*Rule
}

// NewList creates a new empty list.
func NewList() *List {
	return &List{
		rules: map[string]*Rule{},
	}
}

// NewListFromString parses a string that represents a Public Suffix source
// and returns a List initialized with the rules in the source.
func NewListFromString(src string, options *ParserOption) (*List, error) {
	l := NewList()
	_, err := l.LoadString(src, options)
	return l, err
}

// NewListFromFile parses a string that represents a Public Suffix source
// and returns a List initialized with the rules in the source.
func NewListFromFile(path string, options *ParserOption) (*List, error) {
	l := NewList()
	_, err := l.LoadFile(path, options)
	return l, err
}

// Load parses and loads a set of rules from an io.Reader into the current list.
func (l *List) Load(r io.Reader, options *ParserOption) ([]Rule, error) {
	return l.parse(r, options)
}

// LoadString parses and loads a set of rules from a String into the current list.
func (l *List) LoadString(src string, options *ParserOption) ([]Rule, error) {
	r := strings.NewReader(src)
	return l.parse(r, options)
}

// LoadFile parses and loads a set of rules from a File into the current list.
func (l *List) LoadFile(path string, options *ParserOption) ([]Rule, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return l.parse(f, options)
}

// AddRule adds a new rule to the list.
//
// The exact position of the rule into the list is unpredictable.
// The list may be optimized internally for lookups, therefore the algorithm
// will decide the best position for the new rule.
func (l *List) AddRule(r *Rule) error {
	l.rules[r.Value] = r
	return nil
}

// Size returns the size of the list, which is the number of rules.
func (l *List) Size() int {
	return len(l.rules)
}

func (l *List) parse(r io.Reader, options *ParserOption) ([]Rule, error) {
	if options == nil {
		options = DefaultParserOptions
	}
	var rules []Rule

	scanner := bufio.NewScanner(r)
	var section int // 1 == ICANN, 2 == PRIVATE

Scanning:
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		switch {

		// skip blank lines
		case line == "":
			break

		// include private domains or stop scanner
		case strings.Contains(line, listTokenPrivateDomains):
			if !options.PrivateDomains {
				break Scanning
			}
			section = 2

		// skip comments
		case strings.HasPrefix(line, listTokenComment):
			break

		default:
			var rule *Rule
			var err error

			if options.ASCIIEncoded {
				rule, err = NewRule(line)
			} else {
				rule, err = NewRuleUnicode(line)
			}
			if err != nil {
				return []Rule{}, err
			}

			rule.Private = (section == 2)
			l.AddRule(rule)
			rules = append(rules, *rule)
		}

	}

	return rules, scanner.Err()
}

// Find and returns the most appropriate rule for the domain name.
func (l *List) Find(name string, options *FindOptions) *Rule {
	if options == nil {
		options = DefaultFindOptions
	}

	part := name
	for {
		rule, ok := l.rules[part]

		if ok && rule.Match(name) && !(options.IgnorePrivate && rule.Private) {
			return rule
		}

		i := strings.IndexRune(part, '.')
		if i < 0 {
			return options.DefaultRule
		}

		part = part[i+1:]
	}

}

// NewRule parses the rule content, creates and returns a Rule.
//
// The content of the rule MUST be encoded in ASCII (A-labels).
func NewRule(content string) (*Rule, error) {
	var rule *Rule
	var value string

	switch content[0] {
	case '*': // wildcard
		if content == "*" {
			value = ""
		} else {
			value = content[2:]
		}
		rule = &Rule{Type: WildcardType, Value: value, Length: len(Labels(value)) + 1}
	case '!': // exception
		value = content[1:]
		rule = &Rule{Type: ExceptionType, Value: value, Length: len(Labels(value))}
	default: // normal
		value = content
		rule = &Rule{Type: NormalType, Value: value, Length: len(Labels(value))}
	}

	return rule, nil
}

// NewRuleUnicode is like NewRule, but expects the content to be encoded in Unicode (U-labels).
func NewRuleUnicode(content string) (*Rule, error) {
	var err error

	content, err = ToASCII(content)
	if err != nil {
		return nil, err
	}

	return NewRule(content)
}

// MustNewRule is like NewRule, but panics if the content cannot be parsed.
func MustNewRule(content string) *Rule {
	rule, err := NewRule(content)
	if err != nil {
		panic(err)
	}
	return rule
}

// Match checks if the rule matches the name.
//
// A domain name is said to match a rule if and only if all of the following conditions are met:
// - When the domain and rule are split into corresponding labels,
//   that the domain contains as many or more labels than the rule.
// - Beginning with the right-most labels of both the domain and the rule,
//   and continuing for all labels in the rule, one finds that for every pair,
//   either they are identical, or that the label from the rule is "*".
//
// See https://publicsuffix.org/list/
func (r *Rule) Match(name string) bool {
	left := strings.TrimSuffix(name, r.Value)

	// the name contains as many labels than the rule
	// this is a match, unless it's a wildcard
	// because the wildcard requires one more label
	if left == "" {
		return r.Type != WildcardType
	}

	// if there is one more label, the rule match
	// because either the rule is shorter than the domain
	// or the rule is a wildcard and there is one more label
	return left[len(left)-1:] == "."
}

// Decompose takes a name as input and decomposes it into a tuple of <TRD+SLD, TLD>,
// according to the rule definition and type.
func (r *Rule) Decompose(name string) (result [2]string) {
	if r == DefaultRule {
		i := strings.LastIndexByte(name, '.')
		if i < 0 {
			return
		}
		result[0], result[1] = name[:i], name[i+1:]
		return
	}
	switch r.Type {
	case NormalType:
		name = strings.TrimSuffix(name, r.Value)
		if len(name) == 0 {
			return
		}
		result[0], result[1] = name[:len(name)-1], r.Value
	case WildcardType:
		name := strings.TrimSuffix(name, r.Value)
		if len(name) == 0 {
			return
		}
		name = name[:len(name)-1]
		i := strings.LastIndexByte(name, '.')
		if i < 0 {
			return
		}
		result[0], result[1] = name[:i], name[i+1:]+"."+r.Value
	case ExceptionType:
		i := strings.IndexRune(r.Value, '.')
		if i < 0 {
			return
		}
		suffix := r.Value[i+1:]
		name = strings.TrimSuffix(name, suffix)
		if len(name) == 0 {
			return
		}
		result[0], result[1] = name[:len(name)-1], suffix
	}
	return
}

// Labels decomposes given domain name into labels,
// corresponding to the dot-separated tokens.
func Labels(name string) []string {
	return strings.Split(name, ".")
}

// DomainName represents a domain name.
type DomainName struct {
	TLD  string
	SLD  string
	TRD  string
	Rule *Rule
}

// String joins the components of the domain name into a single string.
// Empty labels are skipped.
//
// Examples:
//
// 	DomainName{"com", "example"}.String()
//	// example.com
// 	DomainName{"com", "example", "www"}.String()
//	// www.example.com
//
func (d *DomainName) String() string {
	switch {
	case d.TLD == "":
		return ""
	case d.SLD == "":
		return d.TLD
	case d.TRD == "":
		return d.SLD + "." + d.TLD
	default:
		return d.TRD + "." + d.SLD + "." + d.TLD
	}
}

// Domain extract and return the domain name from the input
// using the default (Public Suffix) List.
//
// Examples:
//
// 	publicsuffix.Domain("example.com")
//	// example.com
// 	publicsuffix.Domain("www.example.com")
//	// example.com
// 	publicsuffix.Domain("www.example.co.uk")
//	// example.co.uk
//
func Domain(name string) (string, error) {
	return DomainFromListWithOptions(DefaultList, name, DefaultFindOptions)
}

// Parse decomposes the name into TLD, SLD, TRD
// using the default (Public Suffix) List,
// and returns the result as a DomainName
//
// Examples:
//
//	list := NewList()
//
// 	publicsuffix.Parse("example.com")
//	// &DomainName{"com", "example"}
// 	publicsuffix.Parse("www.example.com")
//	// &DomainName{"com", "example", "www"}
// 	publicsuffix.Parse("www.example.co.uk")
//	// &DomainName{"co.uk", "example"}
//
func Parse(name string) (*DomainName, error) {
	return ParseFromListWithOptions(DefaultList, name, DefaultFindOptions)
}

// DomainFromListWithOptions extract and return the domain name from the input
// using the (Public Suffix) list passed as argument.
//
// Examples:
//
//	list := NewList()
//
// 	publicsuffix.DomainFromListWithOptions(list, "example.com")
//	// example.com
// 	publicsuffix.DomainFromListWithOptions(list, "www.example.com")
//	// example.com
// 	publicsuffix.DomainFromListWithOptions(list, "www.example.co.uk")
//	// example.co.uk
//
func DomainFromListWithOptions(l *List, name string, options *FindOptions) (string, error) {
	dn, err := ParseFromListWithOptions(l, name, options)
	if err != nil {
		return "", err
	}
	return dn.SLD + "." + dn.TLD, nil
}

// ParseFromListWithOptions decomposes the name into TLD, SLD, TRD
// using the (Public Suffix) list passed as argument,
// and returns the result as a DomainName
//
// Examples:
//
//	list := NewList()
//
// 	publicsuffix.ParseFromListWithOptions(list, "example.com")
//	// &DomainName{"com", "example"}
// 	publicsuffix.ParseFromListWithOptions(list, "www.example.com")
//	// &DomainName{"com", "example", "www"}
// 	publicsuffix.ParseFromListWithOptions(list, "www.example.co.uk")
//	// &DomainName{"co.uk", "example"}
//
func ParseFromListWithOptions(l *List, name string, options *FindOptions) (*DomainName, error) {
	n, err := normalize(name)
	if err != nil {
		return nil, err
	}

	r := l.Find(n, options)
	if r == nil {
		return nil, fmt.Errorf("no rule matching name %s", name)
	}

	parts := r.Decompose(n)
	left, tld := parts[0], parts[1]
	if tld == "" {
		return nil, fmt.Errorf("%s is a suffix", n)
	}

	dn := &DomainName{
		Rule: r,
		TLD:  tld,
	}
	if i := strings.LastIndexByte(left, '.'); i < 0 {
		dn.SLD = left
	} else {
		dn.TRD = left[:i]
		dn.SLD = left[i+1:]
	}
	return dn, nil
}

func normalize(name string) (string, error) {
	ret := strings.ToLower(name)

	if ret == "" {
		return "", fmt.Errorf("name is blank")
	}
	if ret[0] == '.' {
		return "", fmt.Errorf("name %s starts with a dot", ret)
	}

	return ret, nil
}

// ToASCII is a wrapper for idna.ToASCII.
//
// This wrapper exists because idna.ToASCII backward-compatibility was broken twice in few months
// and I can't call this package directly anymore. The wrapper performs some terrible-but-necessary
// before-after replacements to make sure an already ASCII input always results in the same output
// even if passed through ToASCII.
//
// See golang/net@67957fd0b1, golang/net@f2499483f9, golang/net@78ebe5c8b6,
// and weppos/publicsuffix-go#66.
func ToASCII(s string) (string, error) {
	// .example.com should be .example.com
	// ..example.com should be ..example.com
	if strings.HasPrefix(s, ".") {
		dotIndex := 0
		for i := 0; i < len(s); i++ {
			if s[i] == '.' {
				dotIndex = i
			} else {
				break
			}
		}
		out, err := idna.ToASCII(s[dotIndex+1:])
		out = s[:dotIndex+1] + out
		return out, err
	}

	return idna.ToASCII(s)
}

// ToUnicode is a wrapper for idna.ToUnicode.
//
// See ToASCII for more details about why this wrapper exists.
func ToUnicode(s string) (string, error) {
	return idna.ToUnicode(s)
}

// CookieJarList implements the cookiejar.PublicSuffixList interface.
var CookieJarList cookiejar.PublicSuffixList = cookiejarList{DefaultList}

type cookiejarList struct {
	List *List
}

// PublicSuffix implements cookiejar.PublicSuffixList.
func (l cookiejarList) PublicSuffix(domain string) string {
	rule := l.List.Find(domain, nil)
	return rule.Decompose(domain)[1]
}

// PublicSuffix implements cookiejar.String.
func (cookiejarList) String() string {
	return defaultListVersion
}


text:
// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.caja.plugin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;

import com.google.caja.SomethingWidgyHappenedError;
import com.google.caja.util.TestFlag;
import com.google.gwt.thirdparty.guava.common.base.Charsets;

/**
 * Wrapper around a WebDriver instance.
 */

class WebDriverHandle {
  private RemoteWebDriver driver = null;
  private boolean canExecuteScript = true;
  private boolean reportedVersion = false;
  private String firstWindow = null;
  private int windowSeq = 0;
  private boolean windowOpened = false;

  // Don't keep more than this many failed test windows. (Otherwise
  // a broken tree can overload a machine with browser windows.)
  private static final int MAX_FAILS_KEPT = 9;
  private static int failsKept = 0;

  WebDriver begin() {
    if (driver == null) {
      driver = makeDriver();
      firstWindow = driver.getWindowHandle();
      reportVersion(driver);
      try {
        driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
      } catch (WebDriverException e) {
        Echo.echo("failed to set pageLoadTimeout: " + e);
        // harmless, ignore
      }
      try {
        driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
      } catch (WebDriverException e) {
        Echo.echo("failed to setScriptTimeout: " + e);
        // harmless, ignore
      }
    }
    // Try to open a new window
    String name = "cajatest" + (windowSeq++);
    windowOpened = (Boolean) executeScript(
        "return !!window.open('', '" + name + "');");
    if (windowOpened) {
      driver.switchTo().window(name);
    }
    return driver;
  }

  // Selenium 2.33 has trouble executing script on Firefox 23 and later
  private Object executeScript(String script) {
    if (canExecuteScript) {
      try {
        return driver.executeScript(script);
      } catch (WebDriverException e) {
        canExecuteScript = false;
        Echo.echo("executeScript failed: " + e);
      }
    }
    return null;
  }

  private void reportVersion(RemoteWebDriver driver) {
    if (reportedVersion) { return; }
    reportedVersion = true;
    Capabilities caps = driver.getCapabilities();
    String name = caps.getBrowserName();
    if (name == null) { name = "unknown"; }
    String version = caps.getVersion();
    if (version == null) { version = "unknown"; }
    // Firefox's version is something like "20.0", which doesn't tell
    // you the exact build, so we also try to report buildID.
    String build = (String) executeScript(
        "return String(navigator.buildID || '')");
    if (build != null && !"".equals(build)) {
      version += " build " + build;
    }
    Echo.echo("webdriver: browser " + name + " version " + version);
  }

  void end(boolean passed) {
    // If a test fails, drop the driver handle without close or quit,
    // leaving the browser open, which is helpful for debugging.
    if (!passed && !TestFlag.BROWSER_CLOSE.truthy()
        && failsKept++ < MAX_FAILS_KEPT) {
      driver = null;
    } else {
      try {
        // If we're reusing the same browser, close the current window.
        if (windowOpened) {
          driver.close();
          driver.switchTo().window(firstWindow);
        } else {
          driver.get("about:blank");
        }
      } catch (Exception e) {
        Echo.echo("window cleanup failed: " + e);
        closeDriver();
      }
    }
  }

  void release() {
    closeDriver();
  }

  private void closeDriver() {
    if (driver != null) {
      try {
        driver.quit();
      } finally {
        driver = null;
      }
    }
  }

  private static RemoteWebDriver makeDriver() {
    DesiredCapabilities dc = new DesiredCapabilities();

    String browserType = TestFlag.BROWSER.getString("firefox");

    if ("chrome".equals(browserType)) {
      // Chrome driver is odd in that the path to Chrome is specified
      // by a desiredCapability when you start a session. The other
      // browser drivers will read a java system property on start.
      // This applies to both remote Chrome and local Chrome.
      ChromeOptions chromeOpts = new ChromeOptions();
      String chromeBin = TestFlag.CHROME_BINARY.getString(null);
      if (chromeBin != null) {
        chromeOpts.setBinary(chromeBin);
      }
      String chromeArgs = TestFlag.CHROME_ARGS.getString(null);
      if (chromeArgs != null) {
        String[] args = chromeArgs.split(";");
        chromeOpts.addArguments(args);
      }
      dc.setCapability(ChromeOptions.CAPABILITY, chromeOpts);
    }

    String url = TestFlag.WEBDRIVER_URL.getString("");

    if (!"".equals(url)) {
      dc.setBrowserName(browserType);
      dc.setJavascriptEnabled(true);
      try {
        return new RemoteWebDriver(new URL(url), dc);
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }
    } else if ("chrome".equals(browserType)) {
      return new ChromeDriver(dc);
    } else if ("firefox".equals(browserType)) {
      return new FirefoxDriver();
    } else if ("safari".equals(browserType)) {
      // TODO(felix8a): local safari doesn't work yet
      return new SafariDriver();
    } else {
      throw new RuntimeException("No local driver for browser type '"
          + browserType + "'");
    }
  }

  public void captureResults(String name) {
    if (driver == null) { return; }

    String dir = TestFlag.CAPTURE_TO.getString("");
    if ("".equals(dir)) { return; }

    if (!dir.endsWith("/")) { dir = dir + "/"; }
    mkdirs(dir);

    // Try to capture the final html
    try {
      String source = driver.getPageSource();
      if (source != null) {
        saveToFile(dir + name + ".capture.html", source);
      }
    } catch (WebDriverException e) {
      Echo.echo("capture html failed: " + e);
    }

    // Try to capture a screenshot
    if (driver instanceof TakesScreenshot) {
      TakesScreenshot ss = (TakesScreenshot) driver;
      try {
        byte[] bytes = ss.getScreenshotAs(OutputType.BYTES);
        saveToFile(dir + name + ".capture.png", bytes);
      } catch (WebDriverException e) {
        Echo.echo("capture screenshot failed: " + e);
      }
    }

    // Try to capture logs
    try {
      Logs logs = driver.manage().logs();
      if (logs != null) {
        if (logs.getAvailableLogTypes().contains(LogType.BROWSER)) {
          LogEntries entries = logs.get(LogType.BROWSER);
          if (entries != null) {
            StringBuilder sb = new StringBuilder();
            for (LogEntry e : entries) {
              sb.append(e.toString() + "\n");
            }
            saveToFile(dir + name + ".capture.log", sb.toString());
          }
        }
      }
    } catch (WebDriverException e) {
      Echo.echo("capture logs failed: " + e);
    }
  }

  private static void mkdirs(String dirName) {
    File dir = new File(dirName);
    if (!dir.isDirectory() && !dir.mkdirs()) {
      Echo.echo("couldn't mkdir " + dirName);
    }
  }

  private static void saveToFile(String fileName, String str) {
    saveToFile(fileName, str.getBytes(Charsets.UTF_8));
  }

  private static void saveToFile(String fileName, byte[] bytes) {
    FileOutputStream out = null;
    try {
      out = new FileOutputStream(fileName);
      try {
        out.write(bytes);
      } finally {
        out.close();
      }
    } catch (IOException e) {
      throw new SomethingWidgyHappenedError(e);
    }
  }
}


text:
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/queue_op.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

REGISTER_KERNEL_BUILDER(Name("QueueEnqueue").Device(DEVICE_CPU), EnqueueOp);
REGISTER_KERNEL_BUILDER(Name("QueueEnqueueV2").Device(DEVICE_CPU), EnqueueOp);

REGISTER_KERNEL_BUILDER(Name("QueueEnqueueMany").Device(DEVICE_CPU),
                        EnqueueManyOp);
REGISTER_KERNEL_BUILDER(Name("QueueEnqueueManyV2").Device(DEVICE_CPU),
                        EnqueueManyOp);

REGISTER_KERNEL_BUILDER(Name("QueueDequeue").Device(DEVICE_CPU), DequeueOp);
REGISTER_KERNEL_BUILDER(Name("QueueDequeueV2").Device(DEVICE_CPU), DequeueOp);

REGISTER_KERNEL_BUILDER(Name("QueueDequeueMany").Device(DEVICE_CPU),
                        DequeueManyOp);
REGISTER_KERNEL_BUILDER(Name("QueueDequeueManyV2").Device(DEVICE_CPU),
                        DequeueManyOp);

REGISTER_KERNEL_BUILDER(Name("QueueDequeueUpTo").Device(DEVICE_CPU),
                        DequeueUpToOp);
REGISTER_KERNEL_BUILDER(Name("QueueDequeueUpToV2").Device(DEVICE_CPU),
                        DequeueUpToOp);

REGISTER_KERNEL_BUILDER(Name("QueueClose").Device(DEVICE_CPU), QueueCloseOp);
REGISTER_KERNEL_BUILDER(Name("QueueCloseV2").Device(DEVICE_CPU), QueueCloseOp);

REGISTER_KERNEL_BUILDER(Name("QueueSize").Device(DEVICE_CPU), QueueSizeOp);
REGISTER_KERNEL_BUILDER(Name("QueueSizeV2").Device(DEVICE_CPU), QueueSizeOp);

REGISTER_KERNEL_BUILDER(Name("QueueIsClosed").Device(DEVICE_CPU),
                        QueueIsClosedOp);
REGISTER_KERNEL_BUILDER(Name("QueueIsClosedV2").Device(DEVICE_CPU),
                        QueueIsClosedOp);

REGISTER_KERNEL_BUILDER(
    Name("QueueEnqueueV2").Device(DEVICE_DEFAULT).HostMemory("handle"),
    EnqueueOp);
REGISTER_KERNEL_BUILDER(
    Name("QueueDequeueV2").Device(DEVICE_DEFAULT).HostMemory("handle"),
    DequeueOp);
REGISTER_KERNEL_BUILDER(
    Name("QueueCloseV2").Device(DEVICE_DEFAULT).HostMemory("handle"),
    QueueCloseOp);
REGISTER_KERNEL_BUILDER(Name("QueueSizeV2")
                            .Device(DEVICE_DEFAULT)
                            .HostMemory("size")
                            .HostMemory("handle"),
                        QueueSizeOp);
REGISTER_KERNEL_BUILDER(
    Name("QueueIsClosedV2").Device(DEVICE_DEFAULT).HostMemory("handle"),
    QueueIsClosedOp);

class FakeQueueOp : public OpKernel {
 public:
  explicit FakeQueueOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context,
                   context->allocate_persistent(DT_STRING, TensorShape({2}),
                                                &handle_, nullptr));
  }

  void Compute(OpKernelContext* context) override {
    const ResourceHandle& ref = context->input(0).flat<ResourceHandle>()(0);
    handle_.AccessTensor(context)->flat<tstring>()(0) = ref.container();
    handle_.AccessTensor(context)->flat<tstring>()(1) = ref.name();
    context->set_output_ref(0, &mu_, handle_.AccessTensor(context));
  }

 private:
  mutex mu_;
  PersistentTensor handle_;
};

REGISTER_KERNEL_BUILDER(Name("FakeQueue").Device(DEVICE_CPU), FakeQueueOp);

}  // namespace tensorflow


text:
<?php

namespace yii\apidoc\models;

use yii\apidoc\helpers\PrettyPrinter;
use yii\base\Object;

/**
 * Represents API documentation information for a [[FunctionDoc|function]] or [[MethodDoc|method]] `param`.
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class ParamDoc extends Object
{
    public $name;
    public $typeHint;
    public $isOptional;
    public $defaultValue;
    public $isPassedByReference;

    // will be set by creating class
    public $description;
    public $type;
    public $types;
    public $sourceFile;

    /**
     * @param \phpDocumentor\Reflection\FunctionReflector\ArgumentReflector $reflector
     * @param Context $context
     * @param array $config
     */
    public function __construct($reflector = null, $context = null, $config = [])
    {
        parent::__construct($config);

        if ($reflector === null) {
            return;
        }

        $this->name = $reflector->getName();
        $this->typeHint = $reflector->getType();
        $this->isOptional = $reflector->getDefault() !== null;

        // bypass $reflector->getDefault() for short array syntax
        if ($reflector->getNode()->default) {
            $this->defaultValue = PrettyPrinter::getRepresentationOfValue($reflector->getNode()->default);
        }
        $this->isPassedByReference = $reflector->isByRef();
    }
}


text:
/* To be inserted in other files to bypass the chksrc tests */
/* NOCHKSRC */

/* A Bison parser, made by GNU Bison 2.3.  */

/* Skeleton interface for Bison's Yacc-like parsers in C

   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
   Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.  */

/* As a special exception, you may create a larger work that contains
   part or all of the Bison parser skeleton and distribute that work
   under terms of your choice, so long as that work isn't itself a
   parser generator using the skeleton or a modified version thereof
   as a parser skeleton.  Alternatively, if you modify or redistribute
   the parser skeleton itself, you may (at your option) remove this
   special exception, which will cause the skeleton and the resulting
   Bison output files to be licensed under the GNU General Public
   License without this special exception.

   This special exception was added by the Free Software Foundation in
   version 2.2 of Bison.  */

/* Tokens.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
   /* Put the tokens into the symbol table, so that GDB and other debuggers
      know about them.  */
   enum yytokentype {
     TOK_IDENTIFIER = 258,
     TOK_STRING_LITERAL = 259,
     TOK_BINARY = 260,
     TOK_NEGATIVE_BINARY = 261,
     TOK_HEXADECIMAL = 262,
     TOK_NEGATIVE_HEXADECIMAL = 263,
     TOK_INTEGER = 264,
     TOK_NEGATIVE_INTEGER = 265,
     TOK_REAL = 266,
     TOK_NEGATIVE_REAL = 267,
     TOK_TRUE = 268,
     TOK_FALSE = 269,
     TOK_SCOPED_PROPERTY = 270,
     TOK_LPAR = 271,
     TOK_RPAR = 272,
     TOK_HASH = 273,
     TOK_DOT = 274,
     TOK_LBRKT = 275,
     TOK_RBRKT = 276,
     TOK_UNDERSCORE = 277,
     TOK_COMMA = 278,
     TOK_CONCAT = 279,
     TOK_DBL_PIPE = 280,
     TOK_PLUS = 281,
     TOK_MINUS = 282,
     TOK_TIMES = 283,
     TOK_DIV = 284,
     TOK_IS = 285,
     TOK_NULL = 286,
     TOK_EQ = 287,
     TOK_NE = 288,
     TOK_GT = 289,
     TOK_LT = 290,
     TOK_GE = 291,
     TOK_LE = 292,
     TOK_ISA = 293,
     TOK_LIKE = 294,
     TOK_NOT = 295,
     TOK_AND = 296,
     TOK_OR = 297,
     TOK_SCOPE = 298,
     TOK_ANY = 299,
     TOK_EVERY = 300,
     TOK_IN = 301,
     TOK_SATISFIES = 302,
     TOK_STAR = 303,
     TOK_DOTDOT = 304,
     TOK_SHARP = 305,
     TOK_DISTINCT = 306,
     TOK_SELECT = 307,
     TOK_FIRST = 308,
     TOK_FROM = 309,
     TOK_WHERE = 310,
     TOK_ORDER = 311,
     TOK_BY = 312,
     TOK_ASC = 313,
     TOK_DESC = 314,
     TOK_AS = 315,
     TOK_UNEXPECTED_CHAR = 316
   };
#endif
/* Tokens.  */
#define TOK_IDENTIFIER 258
#define TOK_STRING_LITERAL 259
#define TOK_BINARY 260
#define TOK_NEGATIVE_BINARY 261
#define TOK_HEXADECIMAL 262
#define TOK_NEGATIVE_HEXADECIMAL 263
#define TOK_INTEGER 264
#define TOK_NEGATIVE_INTEGER 265
#define TOK_REAL 266
#define TOK_NEGATIVE_REAL 267
#define TOK_TRUE 268
#define TOK_FALSE 269
#define TOK_SCOPED_PROPERTY 270
#define TOK_LPAR 271
#define TOK_RPAR 272
#define TOK_HASH 273
#define TOK_DOT 274
#define TOK_LBRKT 275
#define TOK_RBRKT 276
#define TOK_UNDERSCORE 277
#define TOK_COMMA 278
#define TOK_CONCAT 279
#define TOK_DBL_PIPE 280
#define TOK_PLUS 281
#define TOK_MINUS 282
#define TOK_TIMES 283
#define TOK_DIV 284
#define TOK_IS 285
#define TOK_NULL 286
#define TOK_EQ 287
#define TOK_NE 288
#define TOK_GT 289
#define TOK_LT 290
#define TOK_GE 291
#define TOK_LE 292
#define TOK_ISA 293
#define TOK_LIKE 294
#define TOK_NOT 295
#define TOK_AND 296
#define TOK_OR 297
#define TOK_SCOPE 298
#define TOK_ANY 299
#define TOK_EVERY 300
#define TOK_IN 301
#define TOK_SATISFIES 302
#define TOK_STAR 303
#define TOK_DOTDOT 304
#define TOK_SHARP 305
#define TOK_DISTINCT 306
#define TOK_SELECT 307
#define TOK_FIRST 308
#define TOK_FROM 309
#define TOK_WHERE 310
#define TOK_ORDER 311
#define TOK_BY 312
#define TOK_ASC 313
#define TOK_DESC 314
#define TOK_AS 315
#define TOK_UNEXPECTED_CHAR 316

#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
#line 133 "CQL.y"
{
    char * strValue;
    String * _string;
    CQLValue * _value;
    CQLIdentifier * _identifier;
    CQLChainedIdentifier * _chainedIdentifier;
    CQLPredicate * _predicate;
    ExpressionOpType _opType;
    void * _node;
}
/* Line 1489 of yacc.c.  */
#line 182 "CQLtemp.h"
	YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif

extern YYSTYPE CQL_lval;


text:
package business.fundamentalModel;

public class FundamentalModelAPI {
public static final String PFG = "PFG";
public static final String PhT = "PhilTown";
public static final String Custom = "Custom";

	public static final String[] FUNDAMENTAL_MODEL_LIST = { PFG, PhT, Custom };

	public static AbstractFundamentalModel getFundamentalModel(String str) {
		if (str.equals(PFG)) {
			return (new PFG());
		} else if (str.equals(PhT)) {
			return (new PhilTown());
		} else if (str.equals(Custom)) {
			return (new Custom());
		}
		return null;
	}

}


text:
#ifndef __TIMERFUNCS_H__
#define __TIMERFUNCS_H__

extern int timer_went_off;

extern int setup_ms_timer( int ms_interval );
extern int cleanup_from_timeout(void);
extern void delayAwhile(int time /* seconds */);
extern void delayMsec(int time /* milliseconds */);

#endif


text:
var _ = require('underscore')
  , BLOCK_SIZE = require('./constants').BLOCK_SIZE
  , AudioNode = require('./AudioNode')
  , AudioBuffer = require('./AudioBuffer')
  , readOnlyAttr = require('./utils').readOnlyAttr

class ScriptProcessorNode extends AudioNode {

  constructor(context, bufferSize, numberOfInputChannels, numberOfOutputChannels) {
    if (!_.contains([256, 512, 1024, 2048, 4096, 8192, 16384], bufferSize))
      throw new Error('invalid bufferSize')
    super(context, 1, 1, numberOfInputChannels, 'explicit', 'speakers')

    this.numberOfOutputChannels = numberOfOutputChannels
    readOnlyAttr(this, 'bufferSize', bufferSize)
  }

  set onaudioprocess(onaudioprocess) {

    var inputBuffer = new AudioBuffer(this.channelCount, 0, this.context.sampleRate)
      , outputBuffer = new AudioBuffer(this.numberOfOutputChannels, 0, this.context.sampleRate)

    this._tick = function() {
      AudioNode.prototype._tick.apply(this, arguments)

      // Pull some data and add it to `inputBuffer`
      inputBuffer = inputBuffer.concat(this._inputs[0]._tick())

      // When enough data in `inputBuffer`, we run `onaudioprocess`
      if (inputBuffer.length === this.bufferSize) {
        var audioProcEvent = this._processingEvent(inputBuffer)
        onaudioprocess(audioProcEvent)
        inputBuffer = new AudioBuffer(this.channelCount, 0, this.context.sampleRate)
        outputBuffer = outputBuffer.concat(audioProcEvent.outputBuffer)
      } else if (inputBuffer.length >= this.bufferSize) throw new Error('this shouldnt happen')

      // When data has been processed, we return it
      if (outputBuffer.length >= BLOCK_SIZE) {
        var returnedBuffer = outputBuffer.slice(0, BLOCK_SIZE)
        outputBuffer = outputBuffer.slice(BLOCK_SIZE)
        return returnedBuffer
      } else return new AudioBuffer(this.numberOfOutputChannels, BLOCK_SIZE, this.context.sampleRate)
    }
  }

  _processingEvent(inBuffer) {
    return new AudioProcessingEvent(
      this.context.currentTime,
      inBuffer,
      new AudioBuffer(this.numberOfOutputChannels, this.bufferSize, this.context.sampleRate)
    )
  }

  _tick() {
    super._tick(arguments)
    return new AudioBuffer(this.numberOfOutputChannels, BLOCK_SIZE, this.context.sampleRate)
  }

}

class AudioProcessingEvent {

  constructor(playbackTime, inputBuffer, outputBuffer) {
    this.playbackTime = playbackTime
    this.inputBuffer = inputBuffer
    this.outputBuffer = outputBuffer
  }

}

module.exports = ScriptProcessorNode


text:
class Admin::EuCouncilRegulationsController < Admin::EventsController
  # this needs to be specified, because otherwise defaults to 'event'
  defaults :resource_class => EuCouncilRegulation,
    :collection_name => 'eu_council_regulations', :instance_name => 'eu_council_regulation'

  protected

  def collection
    @eu_council_regulations ||= end_of_association_chain.
      order('effective_at DESC, name ASC').
      page(params[:page]).
      search(params[:query])
  end

  def list_template
    'admin/eu_regulations_common/list'
  end
end


text:
lambda collection
========

__A lambda function that runs in [AWS Lambda](http://aws.amazon.com/lambda/)__

1. triggered by incoming message in [AWS SQS](http://aws.amazon.com/sqs/)
2. Forwards messages to lambda function [dp-augmentation-svc](https://github.com/skawtus/dp-augmentation-svc) for augmentation.
3. Batch deletes handled messages from the queue.


text:
package com.ksoichiro.task.exception;

public class DuplicateTagNameException extends RuntimeException {
    public DuplicateTagNameException(String msg) {
        super(msg);
    }
}


text:
extern "C" {
#endif

MOJO_GLES2_EXPORT void MojoGLES2Initialize(MojoAsyncWaiter* async_waiter);
MOJO_GLES2_EXPORT void MojoGLES2Terminate();
MOJO_GLES2_EXPORT MojoGLES2Context MojoGLES2CreateContext(
    MojoHandle handle,
    MojoGLES2ContextLost lost_callback,
    MojoGLES2DrawAnimationFrame animation_callback,
    void* closure);
MOJO_GLES2_EXPORT void MojoGLES2DestroyContext(MojoGLES2Context context);
MOJO_GLES2_EXPORT void MojoGLES2MakeCurrent(MojoGLES2Context context);
MOJO_GLES2_EXPORT void MojoGLES2SwapBuffers();
// TODO(piman): this doesn't belong here.
MOJO_GLES2_EXPORT void MojoGLES2RequestAnimationFrames(
    MojoGLES2Context context);
MOJO_GLES2_EXPORT void MojoGLES2CancelAnimationFrames(MojoGLES2Context context);

// TODO(piman): We shouldn't have to leak those 2 interfaces, especially in a
// type-unsafe way.
MOJO_GLES2_EXPORT void* MojoGLES2GetGLES2Interface(MojoGLES2Context context);
MOJO_GLES2_EXPORT void* MojoGLES2GetContextSupport(MojoGLES2Context context);

#define VISIT_GL_CALL(Function, ReturnType, PARAMETERS, ARGUMENTS) \
  MOJO_GLES2_EXPORT ReturnType GL_APIENTRY gl##Function PARAMETERS;
#include "mojo/public/gles2/gles2_call_visitor_autogen.h"
#undef VISIT_GL_CALL

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // MOJO_PUBLIC_GLES2_GLES2_H_


text:
namespace ash {
class Shelf;
class TrayContainer;
class TrayEventFilter;

// Base class for some children of StatusAreaWidget. This class handles setting
// and animating the background when the Launcher is shown/hidden. It also
// inherits from ActionableView so that the tray items can override
// PerformAction when clicked on.
class ASH_EXPORT TrayBackgroundView : public ActionableView,
                                      public ui::ImplicitAnimationObserver,
                                      public ShelfBackgroundAnimatorObserver,
                                      public TrayBubbleView::Delegate,
                                      public VirtualKeyboardModel::Observer {
 public:
  static const char kViewClassName[];

  explicit TrayBackgroundView(Shelf* shelf);
  ~TrayBackgroundView() override;

  // Called after the tray has been added to the widget containing it.
  virtual void Initialize();

  // Initializes animations for the bubble.
  static void InitializeBubbleAnimations(views::Widget* bubble_widget);

  // ActionableView:
  std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override;
  std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight()
      const override;

  // VirtualKeyboardModel::Observer:
  void OnVirtualKeyboardVisibilityChanged() override;

  // Returns the associated tray bubble view, if one exists. Otherwise returns
  // nullptr.
  virtual TrayBubbleView* GetBubbleView();

  // Closes the associated tray bubble view if it exists and is currently
  // showing.
  virtual void CloseBubble();

  // Shows the associated tray bubble if one exists. |show_by_click| indicates
  // whether the showing operation is initiated by mouse or gesture click.
  virtual void ShowBubble(bool show_by_click);

  // Calculates the ideal bounds that this view should have depending on the
  // constraints.
  virtual void CalculateTargetBounds();

  // Makes this view's bounds and layout match its calculated target bounds.
  virtual void UpdateLayout();

  // Called to update the tray button after the login status changes.
  virtual void UpdateAfterLoginStatusChange();

  // Called whenever the status area's collapse state changes.
  virtual void UpdateAfterStatusAreaCollapseChange();

  // Called whenever the system color mode changes.
  virtual void UpdateAfterColorModeChange();

  // Called when the anchor (tray or bubble) may have moved or changed.
  virtual void AnchorUpdated() {}

  // Called from GetAccessibleNodeData, must return a valid accessible name.
  virtual base::string16 GetAccessibleNameForTray() = 0;

  // Called when the bubble is resized.
  virtual void BubbleResized(const TrayBubbleView* bubble_view);

  // Hides the bubble associated with |bubble_view|. Called when the widget
  // is closed.
  virtual void HideBubbleWithView(const TrayBubbleView* bubble_view) = 0;

  // Called by the bubble wrapper when a click event occurs outside the bubble.
  // May close the bubble.
  virtual void ClickedOutsideBubble() = 0;

  void SetIsActive(bool is_active);
  bool is_active() const { return is_active_; }

  TrayContainer* tray_container() const { return tray_container_; }
  TrayEventFilter* tray_event_filter() { return tray_event_filter_.get(); }
  Shelf* shelf() { return shelf_; }

  // Updates the arrow visibility based on the launcher visibility.
  void UpdateBubbleViewArrow(TrayBubbleView* bubble_view);

  // Updates the visibility of this tray's separator.
  void set_separator_visibility(bool visible) { separator_visible_ = visible; }

  // Sets whether to show the view when the status area is collapsed.
  void set_show_when_collapsed(bool show_when_collapsed) {
    show_when_collapsed_ = show_when_collapsed;
  }

  // Gets the anchor for bubbles, which is tray_container().
  views::View* GetBubbleAnchor() const;

  // Gets additional insets for positioning bubbles relative to
  // tray_container().
  gfx::Insets GetBubbleAnchorInsets() const;

  // Returns the container window for the bubble (on the proper display).
  aura::Window* GetBubbleWindowContainer();

  // Helper function that calculates background bounds relative to local bounds
  // based on background insets returned from GetBackgroundInsets().
  gfx::Rect GetBackgroundBounds() const;

  // Sets whether the tray item should be shown by default (e.g. it is
  // activated). The effective visibility of the tray item is determined by the
  // current state of the status tray (i.e. whether the virtual keyboard is
  // showing or if it is collapsed).
  virtual void SetVisiblePreferred(bool visible_preferred);
  bool visible_preferred() const { return visible_preferred_; }

 protected:
  // ActionableView:
  void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
  bool ShouldEnterPushedState(const ui::Event& event) override;
  bool PerformAction(const ui::Event& event) override;
  void HandlePerformActionResult(bool action_performed,
                                 const ui::Event& event) override;
  views::PaintInfo::ScaleType GetPaintScaleType() const override;

  void set_show_with_virtual_keyboard(bool show_with_virtual_keyboard) {
    show_with_virtual_keyboard_ = show_with_virtual_keyboard;
  }

 private:
  class TrayWidgetObserver;

  void StartVisibilityAnimation(bool visible);

  // views::View:
  void AboutToRequestFocusFromTabTraversal(bool reverse) override;
  void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
  void ChildPreferredSizeChanged(views::View* child) override;
  const char* GetClassName() const override;

  // ui::ImplicitAnimationObserver:
  void OnImplicitAnimationsCompleted() override;
  bool RequiresNotificationWhenAnimatorDestroyed() const override;

  // Applies transformations to the |layer()| to animate the view when
  // SetVisible(false) is called.
  void HideTransformation();

  // Helper function that calculates background insets relative to local bounds.
  gfx::Insets GetBackgroundInsets() const;

  // Updates the background layer.
  virtual void UpdateBackground();

  // Returns the effective visibility of the tray item based on the current
  // state.
  bool GetEffectiveVisibility();

  // The shelf containing the system tray for this view.
  Shelf* shelf_;

  // Convenience pointer to the contents view.
  TrayContainer* tray_container_;

  // Determines if the view is active. This changes how  the ink drop ripples
  // behave.
  bool is_active_;

  // Visibility of this tray's separator which is a line of 1x32px and 4px to
  // right of tray.
  bool separator_visible_;

  // During virtual keyboard is shown, visibility changes to TrayBackgroundView
  // are ignored. In such case, preferred visibility is reflected after the
  // virtual keyboard is hidden.
  bool visible_preferred_;

  // If true, the view always shows up when virtual keyboard is visible.
  bool show_with_virtual_keyboard_;

  // If true, the view is visible when the status area is collapsed.
  bool show_when_collapsed_;

  std::unique_ptr<TrayWidgetObserver> widget_observer_;
  std::unique_ptr<TrayEventFilter> tray_event_filter_;

  DISALLOW_COPY_AND_ASSIGN(TrayBackgroundView);
};

}  // namespace ash

#endif  // ASH_SYSTEM_TRAY_TRAY_BACKGROUND_VIEW_H_


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using NUnit.Framework;

namespace Orleankka.Features
{
    namespace Sticky_actors
    {
        using Meta;
        using Testing;

        [Serializable]
        public class Deactivate : Command
        {}

        [Sticky]
        public class TestActor : Actor
        {
            public override Task OnActivate()
            {
                var stream = System.StreamOf("sms", "sticky");
                return stream.Push("alive!");
            }

            void On(Deactivate q) => Activation.DeactivateOnIdle();
        }

        [TestFixture, RequiresSilo]
        [Category("Slow")]
        public class Tests
        {
            IActorSystem system;

            [SetUp]
            public void SetUp()
            {
                system = TestActorSystem.Instance;
            }

            [Test]
            public async void Sticky_actors_shoud_be_automatically_resurrected()
            {
                var events = new List<string>();

                var stream = system.StreamOf("sms", "sticky");
                await stream.Subscribe<string>(e => events.Add(e));

                var sticky = system.ActorOf<TestActor>("sticky");
                await sticky.Tell(new Deactivate());

                // first activation (from Deactivate message)
                Assert.That(events.Count, Is.EqualTo(1));

                // wait until min reminder timeout (1 minute)
                Thread.Sleep(TimeSpan.FromMinutes(1.5));

                // auto-reactivation (from automatically registered reminder message)
                Assert.That(events.Count, Is.EqualTo(2));
            }
        }
    }
}