text:
/**
 * @file
 * Sequential API Internal module
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

#include "lwip/opt.h"

#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */

#include "lwip/api_msg.h"

#include "lwip/ip.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include "lwip/raw.h"

#include "lwip/memp.h"
#include "lwip/tcpip.h"
#include "lwip/igmp.h"
#include "lwip/dns.h"

/* forward declarations */
#if LWIP_TCP
static err_t do_writemore(struct netconn *conn);
static void do_close_internal(struct netconn *conn);
#endif

#if LWIP_RAW
/**
 * Receive callback function for RAW netconns.
 * Doesn't 'eat' the packet, only references it and sends it to
 * conn->recvmbox
 *
 * @see raw.h (struct raw_pcb.recv) for parameters and return value
 */
static u8_t
recv_raw(void *arg, struct raw_pcb *pcb, struct pbuf *p,
    struct ip_addr *addr)
{
  struct pbuf *q;
  struct netbuf *buf;
  struct netconn *conn;
#if LWIP_SO_RCVBUF
  int recv_avail;
#endif /* LWIP_SO_RCVBUF */

  LWIP_UNUSED_ARG(addr);
  conn = arg;

#if LWIP_SO_RCVBUF
  SYS_ARCH_GET(conn->recv_avail, recv_avail);
  if ((conn != NULL) && (conn->recvmbox != SYS_MBOX_NULL) &&
      ((recv_avail + (int)(p->tot_len)) <= conn->recv_bufsize)) {
#else  /* LWIP_SO_RCVBUF */
  if ((conn != NULL) && (conn->recvmbox != SYS_MBOX_NULL)) {
#endif /* LWIP_SO_RCVBUF */
    /* copy the whole packet into new pbufs */
    q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
    if(q != NULL) {
      if (pbuf_copy(q, p) != ERR_OK) {
        pbuf_free(q);
        q = NULL;
      }
    }

    if(q != NULL) {
      buf = memp_malloc(MEMP_NETBUF);
      if (buf == NULL) {
        pbuf_free(q);
        return 0;
      }

      buf->p = q;
      buf->ptr = q;
      buf->addr = &(((struct ip_hdr*)(q->payload))->src);
      buf->port = pcb->protocol;

      SYS_ARCH_INC(conn->recv_avail, q->tot_len);
      /* Register event with callback */
      API_EVENT(conn, NETCONN_EVT_RCVPLUS, q->tot_len);
      if (sys_mbox_trypost(conn->recvmbox, buf) != ERR_OK) {
        netbuf_delete(buf);
      }
    }
  }

  return 0; /* do not eat the packet */
}
#endif /* LWIP_RAW*/

#if LWIP_UDP
/**
 * Receive callback function for UDP netconns.
 * Posts the packet to conn->recvmbox or deletes it on memory error.
 *
 * @see udp.h (struct udp_pcb.recv) for parameters
 */
static void
recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p,
   struct ip_addr *addr, u16_t port)
{
  struct netbuf *buf;
  struct netconn *conn;
#if LWIP_SO_RCVBUF
  int recv_avail;
#endif /* LWIP_SO_RCVBUF */

  LWIP_UNUSED_ARG(pcb); /* only used for asserts... */
  LWIP_ASSERT("recv_udp must have a pcb argument", pcb != NULL);
  LWIP_ASSERT("recv_udp must have an argument", arg != NULL);
  conn = arg;
  LWIP_ASSERT("recv_udp: recv for wrong pcb!", conn->pcb.udp == pcb);

#if LWIP_SO_RCVBUF
  SYS_ARCH_GET(conn->recv_avail, recv_avail);
  if ((conn == NULL) || (conn->recvmbox == SYS_MBOX_NULL) ||
      ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize)) {
#else  /* LWIP_SO_RCVBUF */
  if ((conn == NULL) || (conn->recvmbox == SYS_MBOX_NULL)) {
#endif /* LWIP_SO_RCVBUF */
    pbuf_free(p);
    return;
  }

  buf = memp_malloc(MEMP_NETBUF);
  if (buf == NULL) {
    pbuf_free(p);
    return;
  } else {
    buf->p = p;
    buf->ptr = p;
    buf->addr = addr;
    buf->port = port;
  }

  SYS_ARCH_INC(conn->recv_avail, p->tot_len);
  /* Register event with callback */
  API_EVENT(conn, NETCONN_EVT_RCVPLUS, p->tot_len);
  if (sys_mbox_trypost(conn->recvmbox, buf) != ERR_OK) {
    netbuf_delete(buf);
    return;
  }
}
#endif /* LWIP_UDP */

#if LWIP_TCP
/**
 * Receive callback function for TCP netconns.
 * Posts the packet to conn->recvmbox, but doesn't delete it on errors.
 *
 * @see tcp.h (struct tcp_pcb.recv) for parameters and return value
 */
static err_t
recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
  struct netconn *conn;
  u16_t len;

  LWIP_UNUSED_ARG(pcb);
  LWIP_ASSERT("recv_tcp must have a pcb argument", pcb != NULL);
  LWIP_ASSERT("recv_tcp must have an argument", arg != NULL);
  conn = arg;
  LWIP_ASSERT("recv_tcp: recv for wrong pcb!", conn->pcb.tcp == pcb);

  if ((conn == NULL) || (conn->recvmbox == SYS_MBOX_NULL)) {
    return ERR_VAL;
  }

  conn->err = err;
  if (p != NULL) {
    len = p->tot_len;
    SYS_ARCH_INC(conn->recv_avail, len);
  } else {
    len = 0;
  }
  /* Register event with callback */
  API_EVENT(conn, NETCONN_EVT_RCVPLUS, len);
  if (sys_mbox_trypost(conn->recvmbox, p) != ERR_OK) {
    return ERR_MEM;
  }

  return ERR_OK;
}

/**
 * Poll callback function for TCP netconns.
 * Wakes up an application thread that waits for a connection to close
 * or data to be sent. The application thread then takes the
 * appropriate action to go on.
 *
 * Signals the conn->sem.
 * netconn_close waits for conn->sem if closing failed.
 *
 * @see tcp.h (struct tcp_pcb.poll) for parameters and return value
 */
static err_t
poll_tcp(void *arg, struct tcp_pcb *pcb)
{
  struct netconn *conn = arg;

  LWIP_UNUSED_ARG(pcb);
  LWIP_ASSERT("conn != NULL", (conn != NULL));

  if (conn->state == NETCONN_WRITE) {
    do_writemore(conn);
  } else if (conn->state == NETCONN_CLOSE) {
    do_close_internal(conn);
  }

  return ERR_OK;
}

/**
 * Sent callback function for TCP netconns.
 * Signals the conn->sem and calls API_EVENT.
 * netconn_write waits for conn->sem if send buffer is low.
 *
 * @see tcp.h (struct tcp_pcb.sent) for parameters and return value
 */
static err_t
sent_tcp(void *arg, struct tcp_pcb *pcb, u16_t len)
{
  struct netconn *conn = arg;

  LWIP_UNUSED_ARG(pcb);
  LWIP_ASSERT("conn != NULL", (conn != NULL));

  if (conn->state == NETCONN_WRITE) {
    LWIP_ASSERT("conn->pcb.tcp != NULL", conn->pcb.tcp != NULL);
    do_writemore(conn);
  } else if (conn->state == NETCONN_CLOSE) {
    do_close_internal(conn);
  }

  if (conn) {
    if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT)) {
      API_EVENT(conn, NETCONN_EVT_SENDPLUS, len);
    }
  }

  return ERR_OK;
}

/**
 * Error callback function for TCP netconns.
 * Signals conn->sem, posts to all conn mboxes and calls API_EVENT.
 * The application thread has then to decide what to do.
 *
 * @see tcp.h (struct tcp_pcb.err) for parameters
 */
static void
err_tcp(void *arg, err_t err)
{
  struct netconn *conn;

  conn = arg;
  LWIP_ASSERT("conn != NULL", (conn != NULL));

  conn->pcb.tcp = NULL;

  conn->err = err;
  if (conn->recvmbox != SYS_MBOX_NULL) {
    /* Register event with callback */
    API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
    sys_mbox_post(conn->recvmbox, NULL);
  }
  if (conn->op_completed != SYS_SEM_NULL && conn->state == NETCONN_CONNECT) {
    conn->state = NETCONN_NONE;
    sys_sem_signal(conn->op_completed);
  }
  if (conn->acceptmbox != SYS_MBOX_NULL) {
    /* Register event with callback */
    API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
    sys_mbox_post(conn->acceptmbox, NULL);
  }
  if ((conn->state == NETCONN_WRITE) || (conn->state == NETCONN_CLOSE)) {
    /* calling do_writemore/do_close_internal is not necessary
       since the pcb has already been deleted! */
    conn->state = NETCONN_NONE;
    /* wake up the waiting task */
    sys_sem_signal(conn->op_completed);
  }
}

/**
 * Setup a tcp_pcb with the correct callback function pointers
 * and their arguments.
 *
 * @param conn the TCP netconn to setup
 */
static void
setup_tcp(struct netconn *conn)
{
  struct tcp_pcb *pcb;

  pcb = conn->pcb.tcp;
  tcp_arg(pcb, conn);
  tcp_recv(pcb, recv_tcp);
  tcp_sent(pcb, sent_tcp);
  tcp_poll(pcb, poll_tcp, 4);
  tcp_err(pcb, err_tcp);
}

/**
 * Accept callback function for TCP netconns.
 * Allocates a new netconn and posts that to conn->acceptmbox.
 *
 * @see tcp.h (struct tcp_pcb_listen.accept) for parameters and return value
 */
static err_t
accept_function(void *arg, struct tcp_pcb *newpcb, err_t err)
{
  struct netconn *newconn;
  struct netconn *conn;

#if API_MSG_DEBUG
#if TCP_DEBUG
  tcp_debug_print_state(newpcb->state);
#endif /* TCP_DEBUG */
#endif /* API_MSG_DEBUG */
  conn = (struct netconn *)arg;

  LWIP_ERROR("accept_function: invalid conn->acceptmbox",
             conn->acceptmbox != SYS_MBOX_NULL, return ERR_VAL;);

  /* We have to set the callback here even though
   * the new socket is unknown. conn->socket is marked as -1. */
  newconn = netconn_alloc(conn->type, conn->callback);
  if (newconn == NULL) {
    return ERR_MEM;
  }
  newconn->pcb.tcp = newpcb;
  setup_tcp(newconn);
  newconn->err = err;
  /* Register event with callback */
  API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);

  if (sys_mbox_trypost(conn->acceptmbox, newconn) != ERR_OK) {
    /* When returning != ERR_OK, the connection is aborted in tcp_process(),
       so do nothing here! */
    newconn->pcb.tcp = NULL;
    netconn_free(newconn);
    return ERR_MEM;
  }
  return ERR_OK;
}
#endif /* LWIP_TCP */

/**
 * Create a new pcb of a specific type.
 * Called from do_newconn().
 *
 * @param msg the api_msg_msg describing the connection type
 * @return msg->conn->err, but the return value is currently ignored
 */
static err_t
pcb_new(struct api_msg_msg *msg)
{
   msg->conn->err = ERR_OK;

   LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL);

   /* Allocate a PCB for this connection */
   switch(NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
   case NETCONN_RAW:
     msg->conn->pcb.raw = raw_new(msg->msg.n.proto);
     if(msg->conn->pcb.raw == NULL) {
       msg->conn->err = ERR_MEM;
       break;
     }
     raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
     break;
#endif /* LWIP_RAW */
#if LWIP_UDP
   case NETCONN_UDP:
     msg->conn->pcb.udp = udp_new();
     if(msg->conn->pcb.udp == NULL) {
       msg->conn->err = ERR_MEM;
       break;
     }
#if LWIP_UDPLITE
     if (msg->conn->type==NETCONN_UDPLITE) {
       udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
     }
#endif /* LWIP_UDPLITE */
     if (msg->conn->type==NETCONN_UDPNOCHKSUM) {
       udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
     }
     udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
     break;
#endif /* LWIP_UDP */
#if LWIP_TCP
   case NETCONN_TCP:
     msg->conn->pcb.tcp = tcp_new();
     if(msg->conn->pcb.tcp == NULL) {
       msg->conn->err = ERR_MEM;
       break;
     }
     setup_tcp(msg->conn);
     break;
#endif /* LWIP_TCP */
   default:
     /* Unsupported netconn type, e.g. protocol disabled */
     msg->conn->err = ERR_VAL;
     break;
   }

  return msg->conn->err;
}

/**
 * Create a new pcb of a specific type inside a netconn.
 * Called from netconn_new_with_proto_and_callback.
 *
 * @param msg the api_msg_msg describing the connection type
 */
void
do_newconn(struct api_msg_msg *msg)
{
   if(msg->conn->pcb.tcp == NULL) {
     pcb_new(msg);
   }
   /* Else? This "new" connection already has a PCB allocated. */
   /* Is this an error condition? Should it be deleted? */
   /* We currently just are happy and return. */

   TCPIP_APIMSG_ACK(msg);
}

/**
 * Create a new netconn (of a specific type) that has a callback function.
 * The corresponding pcb is NOT created!
 *
 * @param t the type of 'connection' to create (@see enum netconn_type)
 * @param proto the IP protocol for RAW IP pcbs
 * @param callback a function to call on status changes (RX available, TX'ed)
 * @return a newly allocated struct netconn or
 *         NULL on memory error
 */
struct netconn*
netconn_alloc(enum netconn_type t, netconn_callback callback)
{
  struct netconn *conn;
  int size;

  conn = memp_malloc(MEMP_NETCONN);
  if (conn == NULL) {
    return NULL;
  }

  conn->err = ERR_OK;
  conn->type = t;
  conn->pcb.tcp = NULL;

#if (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_UDP_RECVMBOX_SIZE) && \
    (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_TCP_RECVMBOX_SIZE)
  size = DEFAULT_RAW_RECVMBOX_SIZE;
#else
  switch(NETCONNTYPE_GROUP(t)) {
#if LWIP_RAW
  case NETCONN_RAW:
    size = DEFAULT_RAW_RECVMBOX_SIZE;
    break;
#endif /* LWIP_RAW */
#if LWIP_UDP
  case NETCONN_UDP:
    size = DEFAULT_UDP_RECVMBOX_SIZE;
    break;
#endif /* LWIP_UDP */
#if LWIP_TCP
  case NETCONN_TCP:
    size = DEFAULT_TCP_RECVMBOX_SIZE;
    break;
#endif /* LWIP_TCP */
  default:
    LWIP_ASSERT("netconn_alloc: undefined netconn_type", 0);
    break;
  }
#endif

  if ((conn->op_completed = sys_sem_new(0)) == SYS_SEM_NULL) {
    memp_free(MEMP_NETCONN, conn);
    return NULL;
  }
  if ((conn->recvmbox = sys_mbox_new(size)) == SYS_MBOX_NULL) {
    sys_sem_free(conn->op_completed);
    memp_free(MEMP_NETCONN, conn);
    return NULL;
  }

  conn->acceptmbox   = SYS_MBOX_NULL;
  conn->state        = NETCONN_NONE;
  /* initialize socket to -1 since 0 is a valid socket */
  conn->socket       = -1;
  conn->callback     = callback;
  conn->recv_avail   = 0;
#if LWIP_SO_RCVTIMEO
  conn->recv_timeout = 0;
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
  conn->recv_bufsize = INT_MAX;
#endif /* LWIP_SO_RCVBUF */
  return conn;
}

/**
 * Delete a netconn and all its resources.
 * The pcb is NOT freed (since we might not be in the right thread context do this).
 *
 * @param conn the netconn to free
 */
void
netconn_free(struct netconn *conn)
{
  void *mem;
  LWIP_ASSERT("PCB must be deallocated outside this function", conn->pcb.tcp == NULL);

  /* Drain the recvmbox. */
  if (conn->recvmbox != SYS_MBOX_NULL) {
    while (sys_mbox_tryfetch(conn->recvmbox, &mem) != SYS_MBOX_EMPTY) {
      if (conn->type == NETCONN_TCP) {
        if(mem != NULL) {
          pbuf_free((struct pbuf *)mem);
        }
      } else {
        netbuf_delete((struct netbuf *)mem);
      }
    }
    sys_mbox_free(conn->recvmbox);
    conn->recvmbox = SYS_MBOX_NULL;
  }

  /* Drain the acceptmbox. */
  if (conn->acceptmbox != SYS_MBOX_NULL) {
    while (sys_mbox_tryfetch(conn->acceptmbox, &mem) != SYS_MBOX_EMPTY) {
      netconn_delete((struct netconn *)mem);
    }
    sys_mbox_free(conn->acceptmbox);
    conn->acceptmbox = SYS_MBOX_NULL;
  }

  sys_sem_free(conn->op_completed);
  conn->op_completed = SYS_SEM_NULL;

  memp_free(MEMP_NETCONN, conn);
}

#if LWIP_TCP
/**
 * Internal helper function to close a TCP netconn: since this sometimes
 * doesn't work at the first attempt, this function is called from multiple
 * places.
 *
 * @param conn the TCP netconn to close
 */
static void
do_close_internal(struct netconn *conn)
{
  err_t err;

  LWIP_ASSERT("invalid conn", (conn != NULL));
  LWIP_ASSERT("this is for tcp netconns only", (conn->type == NETCONN_TCP));
  LWIP_ASSERT("conn must be in state NETCONN_CLOSE", (conn->state == NETCONN_CLOSE));
  LWIP_ASSERT("pcb already closed", (conn->pcb.tcp != NULL));

  /* Set back some callback pointers */
  if (conn->pcb.tcp->state == LISTEN) {
    tcp_arg(conn->pcb.tcp, NULL);
    tcp_accept(conn->pcb.tcp, NULL);
  } else {
    tcp_recv(conn->pcb.tcp, NULL);
  }
  /* Try to close the connection */
  err = tcp_close(conn->pcb.tcp);
  if (err == ERR_OK) {
    /* Closing succeeded */
    conn->state = NETCONN_NONE;
    /* Set back some callback pointers as conn is going away */
    tcp_err(conn->pcb.tcp, NULL);
    tcp_poll(conn->pcb.tcp, NULL, 4);
    tcp_sent(conn->pcb.tcp, NULL);
    tcp_recv(conn->pcb.tcp, NULL);
    tcp_arg(conn->pcb.tcp, NULL);
    conn->pcb.tcp = NULL;
    conn->err = ERR_OK;
    /* Trigger select() in socket layer. This send should something else so the
       errorfd is set, not the read and write fd! */
    API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
    API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);
    /* wake up the application task */
    sys_sem_signal(conn->op_completed);
  }
  /* If closing didn't succeed, we get called again either
     from poll_tcp or from sent_tcp */
}
#endif /* LWIP_TCP */

/**
 * Delete the pcb inside a netconn.
 * Called from netconn_delete.
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_delconn(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.tcp != NULL) {
    switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
    case NETCONN_RAW:
      raw_remove(msg->conn->pcb.raw);
      break;
#endif /* LWIP_RAW */
#if LWIP_UDP
    case NETCONN_UDP:
      msg->conn->pcb.udp->recv_arg = NULL;
      udp_remove(msg->conn->pcb.udp);
      break;
#endif /* LWIP_UDP */
#if LWIP_TCP
    case NETCONN_TCP:
      msg->conn->state = NETCONN_CLOSE;
      do_close_internal(msg->conn);
      /* API_EVENT is called inside do_close_internal, before releasing
         the application thread, so we can return at this point! */
      return;
#endif /* LWIP_TCP */
    default:
      break;
    }
  }
  /* tcp netconns don't come here! */

  /* Trigger select() in socket layer. This send should something else so the
     errorfd is set, not the read and write fd! */
  API_EVENT(msg->conn, NETCONN_EVT_RCVPLUS, 0);
  API_EVENT(msg->conn, NETCONN_EVT_SENDPLUS, 0);

  if (msg->conn->op_completed != SYS_SEM_NULL) {
    sys_sem_signal(msg->conn->op_completed);
  }
}

/**
 * Bind a pcb contained in a netconn
 * Called from netconn_bind.
 *
 * @param msg the api_msg_msg pointing to the connection and containing
 *            the IP address and port to bind to
 */
void
do_bind(struct api_msg_msg *msg)
{
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
      case NETCONN_RAW:
        msg->conn->err = raw_bind(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
        break;
#endif /* LWIP_RAW */
#if LWIP_UDP
      case NETCONN_UDP:
        msg->conn->err = udp_bind(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
        break;
#endif /* LWIP_UDP */
#if LWIP_TCP
      case NETCONN_TCP:
        msg->conn->err = tcp_bind(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port);
        break;
#endif /* LWIP_TCP */
      default:
        break;
      }
    } else {
      /* msg->conn->pcb is NULL */
      msg->conn->err = ERR_VAL;
    }
  }
  TCPIP_APIMSG_ACK(msg);
}

#if LWIP_TCP
/**
 * TCP callback function if a connection (opened by tcp_connect/do_connect) has
 * been established (or reset by the remote host).
 *
 * @see tcp.h (struct tcp_pcb.connected) for parameters and return values
 */
static err_t
do_connected(void *arg, struct tcp_pcb *pcb, err_t err)
{
  struct netconn *conn;

  LWIP_UNUSED_ARG(pcb);

  conn = arg;

  if (conn == NULL) {
    return ERR_VAL;
  }

  conn->err = err;
  if ((conn->type == NETCONN_TCP) && (err == ERR_OK)) {
    setup_tcp(conn);
  }
  conn->state = NETCONN_NONE;
  sys_sem_signal(conn->op_completed);
  return ERR_OK;
}
#endif /* LWIP_TCP */

/**
 * Connect a pcb contained inside a netconn
 * Called from netconn_connect.
 *
 * @param msg the api_msg_msg pointing to the connection and containing
 *            the IP address and port to connect to
 */
void
do_connect(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.tcp == NULL) {
    sys_sem_signal(msg->conn->op_completed);
    return;
  }

  switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
  case NETCONN_RAW:
    msg->conn->err = raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
    sys_sem_signal(msg->conn->op_completed);
    break;
#endif /* LWIP_RAW */
#if LWIP_UDP
  case NETCONN_UDP:
    msg->conn->err = udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
    sys_sem_signal(msg->conn->op_completed);
    break;
#endif /* LWIP_UDP */
#if LWIP_TCP
  case NETCONN_TCP:
    msg->conn->state = NETCONN_CONNECT;
    setup_tcp(msg->conn);
    msg->conn->err = tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port,
                                 do_connected);
    /* sys_sem_signal() is called from do_connected (or err_tcp()),
     * when the connection is established! */
    break;
#endif /* LWIP_TCP */
  default:
    break;
  }
}

/**
 * Connect a pcb contained inside a netconn
 * Only used for UDP netconns.
 * Called from netconn_disconnect.
 *
 * @param msg the api_msg_msg pointing to the connection to disconnect
 */
void
do_disconnect(struct api_msg_msg *msg)
{
#if LWIP_UDP
  if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) {
    udp_disconnect(msg->conn->pcb.udp);
  }
#endif /* LWIP_UDP */
  TCPIP_APIMSG_ACK(msg);
}

/**
 * Set a TCP pcb contained in a netconn into listen mode
 * Called from netconn_listen.
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_listen(struct api_msg_msg *msg)
{
#if LWIP_TCP
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      if (msg->conn->type == NETCONN_TCP) {
        if (msg->conn->pcb.tcp->state == CLOSED) {
#if TCP_LISTEN_BACKLOG
          struct tcp_pcb* lpcb = tcp_listen_with_backlog(msg->conn->pcb.tcp, msg->msg.lb.backlog);
#else  /* TCP_LISTEN_BACKLOG */
          struct tcp_pcb* lpcb = tcp_listen(msg->conn->pcb.tcp);
#endif /* TCP_LISTEN_BACKLOG */
          if (lpcb == NULL) {
            msg->conn->err = ERR_MEM;
          } else {
            /* delete the recvmbox and allocate the acceptmbox */
            if (msg->conn->recvmbox != SYS_MBOX_NULL) {
              /** @todo: should we drain the recvmbox here? */
              sys_mbox_free(msg->conn->recvmbox);
              msg->conn->recvmbox = SYS_MBOX_NULL;
            }
            if (msg->conn->acceptmbox == SYS_MBOX_NULL) {
              if ((msg->conn->acceptmbox = sys_mbox_new(DEFAULT_ACCEPTMBOX_SIZE)) == SYS_MBOX_NULL) {
                msg->conn->err = ERR_MEM;
              }
            }
            if (msg->conn->err == ERR_OK) {
              msg->conn->state = NETCONN_LISTEN;
              msg->conn->pcb.tcp = lpcb;
              tcp_arg(msg->conn->pcb.tcp, msg->conn);
              tcp_accept(msg->conn->pcb.tcp, accept_function);
            }
          }
        } else {
          msg->conn->err = ERR_CONN;
        }
      }
    }
  }
#endif /* LWIP_TCP */
  TCPIP_APIMSG_ACK(msg);
}

/**
 * Send some data on a RAW or UDP pcb contained in a netconn
 * Called from netconn_send
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_send(struct api_msg_msg *msg)
{
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
      case NETCONN_RAW:
        if (msg->msg.b->addr == NULL) {
          msg->conn->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p);
        } else {
          msg->conn->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, msg->msg.b->addr);
        }
        break;
#endif
#if LWIP_UDP
      case NETCONN_UDP:
        if (msg->msg.b->addr == NULL) {
          msg->conn->err = udp_send(msg->conn->pcb.udp, msg->msg.b->p);
        } else {
          msg->conn->err = udp_sendto(msg->conn->pcb.udp, msg->msg.b->p, msg->msg.b->addr, msg->msg.b->port);
        }
        break;
#endif /* LWIP_UDP */
      default:
        break;
      }
    }
  }
  TCPIP_APIMSG_ACK(msg);
}

/**
 * Recv some data from a RAW or UDP pcb contained in a netconn
 * Called from netconn_recv
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_recv(struct api_msg_msg *msg)
{
#if LWIP_TCP
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      if (msg->conn->type == NETCONN_TCP) {
#if TCP_LISTEN_BACKLOG
        if (msg->conn->pcb.tcp->state == LISTEN) {
          tcp_accepted(msg->conn->pcb.tcp);
        } else
#endif /* TCP_LISTEN_BACKLOG */
        {
          tcp_recved(msg->conn->pcb.tcp, msg->msg.r.len);
        }
      }
    }
  }
#endif /* LWIP_TCP */
  TCPIP_APIMSG_ACK(msg);
}

#if LWIP_TCP
/**
 * See if more data needs to be written from a previous call to netconn_write.
 * Called initially from do_write. If the first call can't send all data
 * (because of low memory or empty send-buffer), this function is called again
 * from sent_tcp() or poll_tcp() to send more data. If all data is sent, the
 * blocking application thread (waiting in netconn_write) is released.
 *
 * @param conn netconn (that is currently in state NETCONN_WRITE) to process
 * @return ERR_OK
 *         ERR_MEM if LWIP_TCPIP_CORE_LOCKING=1 and sending hasn't yet finished
 */
static err_t
do_writemore(struct netconn *conn)
{
  err_t err;
  void *dataptr;
  u16_t len, available;
  u8_t write_finished = 0;

  LWIP_ASSERT("conn->state == NETCONN_WRITE", (conn->state == NETCONN_WRITE));

  dataptr = (u8_t*)conn->write_msg->msg.w.dataptr + conn->write_offset;
  if ((conn->write_msg->msg.w.len - conn->write_offset > 0xffff)) { /* max_u16_t */
    len = 0xffff;
#if LWIP_TCPIP_CORE_LOCKING
    conn->write_delayed = 1;
#endif
  } else {
    len = conn->write_msg->msg.w.len - conn->write_offset;
  }
  available = tcp_sndbuf(conn->pcb.tcp);
  if (available < len) {
    /* don't try to write more than sendbuf */
    len = available;
#if LWIP_TCPIP_CORE_LOCKING
    conn->write_delayed = 1;
#endif
  }

  err = tcp_write(conn->pcb.tcp, dataptr, len, conn->write_msg->msg.w.apiflags);
  LWIP_ASSERT("do_writemore: invalid length!", ((conn->write_offset + len) <= conn->write_msg->msg.w.len));
  if (err == ERR_OK) {
    conn->write_offset += len;
    if (conn->write_offset == conn->write_msg->msg.w.len) {
      /* everything was written */
      write_finished = 1;
      conn->write_msg = NULL;
      conn->write_offset = 0;
    }
    err = tcp_output_nagle(conn->pcb.tcp);
    conn->err = err;
    if ((err == ERR_OK) && (tcp_sndbuf(conn->pcb.tcp) <= TCP_SNDLOWAT)) {
      API_EVENT(conn, NETCONN_EVT_SENDMINUS, len);
    }
  } else if (err == ERR_MEM) {
    /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called
       we do NOT return to the application thread, since ERR_MEM is
       only a temporary error! */

    /* tcp_enqueue returned ERR_MEM, try tcp_output anyway */
    err = tcp_output(conn->pcb.tcp);

#if LWIP_TCPIP_CORE_LOCKING
    conn->write_delayed = 1;
#endif
  } else {
    /* On errors != ERR_MEM, we don't try writing any more but return
       the error to the application thread. */
    conn->err = err;
    write_finished = 1;
  }

  if (write_finished) {
    /* everything was written: set back connection state
       and back to application task */
    conn->state = NETCONN_NONE;
#if LWIP_TCPIP_CORE_LOCKING
    if (conn->write_delayed != 0)
#endif
    {
      sys_sem_signal(conn->op_completed);
    }
  }
#if LWIP_TCPIP_CORE_LOCKING
  else
    return ERR_MEM;
#endif
  return ERR_OK;
}
#endif /* LWIP_TCP */

/**
 * Send some data on a TCP pcb contained in a netconn
 * Called from netconn_write
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_write(struct api_msg_msg *msg)
{
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if ((msg->conn->pcb.tcp != NULL) && (msg->conn->type == NETCONN_TCP)) {
#if LWIP_TCP
      msg->conn->state = NETCONN_WRITE;
      /* set all the variables used by do_writemore */
      msg->conn->write_msg = msg;
      msg->conn->write_offset = 0;
#if LWIP_TCPIP_CORE_LOCKING
      msg->conn->write_delayed = 0;
      if (do_writemore(msg->conn) != ERR_OK) {
        LWIP_ASSERT("state!", msg->conn->state == NETCONN_WRITE);
        UNLOCK_TCPIP_CORE();
        sys_arch_sem_wait(msg->conn->op_completed, 0);
        LOCK_TCPIP_CORE();
        LWIP_ASSERT("state!", msg->conn->state == NETCONN_NONE);
      }
#else
      do_writemore(msg->conn);
#endif
      /* for both cases: if do_writemore was called, don't ACK the APIMSG! */
      return;
#endif /* LWIP_TCP */
#if (LWIP_UDP || LWIP_RAW)
    } else {
      msg->conn->err = ERR_VAL;
#endif /* (LWIP_UDP || LWIP_RAW) */
    }
  }
  TCPIP_APIMSG_ACK(msg);
}

/**
 * Return a connection's local or remote address
 * Called from netconn_getaddr
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_getaddr(struct api_msg_msg *msg)
{
  if (msg->conn->pcb.ip != NULL) {
    *(msg->msg.ad.ipaddr) = (msg->msg.ad.local?msg->conn->pcb.ip->local_ip:msg->conn->pcb.ip->remote_ip);

    switch (NETCONNTYPE_GROUP(msg->conn->type)) {
#if LWIP_RAW
    case NETCONN_RAW:
      if (msg->msg.ad.local) {
        *(msg->msg.ad.port) = msg->conn->pcb.raw->protocol;
      } else {
        /* return an error as connecting is only a helper for upper layers */
        msg->conn->err = ERR_CONN;
      }
      break;
#endif /* LWIP_RAW */
#if LWIP_UDP
    case NETCONN_UDP:
      if (msg->msg.ad.local) {
        *(msg->msg.ad.port) = msg->conn->pcb.udp->local_port;
      } else {
        if ((msg->conn->pcb.udp->flags & UDP_FLAGS_CONNECTED) == 0) {
          msg->conn->err = ERR_CONN;
        } else {
          *(msg->msg.ad.port) = msg->conn->pcb.udp->remote_port;
        }
      }
      break;
#endif /* LWIP_UDP */
#if LWIP_TCP
    case NETCONN_TCP:
      *(msg->msg.ad.port) = (msg->msg.ad.local?msg->conn->pcb.tcp->local_port:msg->conn->pcb.tcp->remote_port);
      break;
#endif /* LWIP_TCP */
    }
  } else {
    msg->conn->err = ERR_CONN;
  }
  TCPIP_APIMSG_ACK(msg);
}

/**
 * Close a TCP pcb contained in a netconn
 * Called from netconn_close
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_close(struct api_msg_msg *msg)
{
#if LWIP_TCP
  if ((msg->conn->pcb.tcp != NULL) && (msg->conn->type == NETCONN_TCP)) {
      msg->conn->state = NETCONN_CLOSE;
      do_close_internal(msg->conn);
      /* for tcp netconns, do_close_internal ACKs the message */
  } else
#endif /* LWIP_TCP */
  {
    msg->conn->err = ERR_VAL;
    TCPIP_APIMSG_ACK(msg);
  }
}

#if LWIP_IGMP
/**
 * Join multicast groups for UDP netconns.
 * Called from netconn_join_leave_group
 *
 * @param msg the api_msg_msg pointing to the connection
 */
void
do_join_leave_group(struct api_msg_msg *msg)
{
  if (!ERR_IS_FATAL(msg->conn->err)) {
    if (msg->conn->pcb.tcp != NULL) {
      if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) {
#if LWIP_UDP
        if (msg->msg.jl.join_or_leave == NETCONN_JOIN) {
          msg->conn->err = igmp_joingroup(msg->msg.jl.interface, msg->msg.jl.multiaddr);
        } else {
          msg->conn->err = igmp_leavegroup(msg->msg.jl.interface, msg->msg.jl.multiaddr);
        }
#endif /* LWIP_UDP */
#if (LWIP_TCP || LWIP_RAW)
      } else {
        msg->conn->err = ERR_VAL;
#endif /* (LWIP_TCP || LWIP_RAW) */
      }
    }
  }
  TCPIP_APIMSG_ACK(msg);
}
#endif /* LWIP_IGMP */

#if LWIP_DNS
/**
 * Callback function that is called when DNS name is resolved
 * (or on timeout). A waiting application thread is waked up by
 * signaling the semaphore.
 */
static void
do_dns_found(const char *name, struct ip_addr *ipaddr, void *arg)
{
  struct dns_api_msg *msg = (struct dns_api_msg*)arg;

  LWIP_ASSERT("DNS response for wrong host name", strcmp(msg->name, name) == 0);

  if (ipaddr == NULL) {
    /* timeout or memory error */
    *msg->err = ERR_VAL;
  } else {
    /* address was resolved */
    *msg->err = ERR_OK;
    *msg->addr = *ipaddr;
  }
  /* wake up the application task waiting in netconn_gethostbyname */
  sys_sem_signal(msg->sem);
}

/**
 * Execute a DNS query
 * Called from netconn_gethostbyname
 *
 * @param arg the dns_api_msg pointing to the query
 */
void
do_gethostbyname(void *arg)
{
  struct dns_api_msg *msg = (struct dns_api_msg*)arg;

  *msg->err = dns_gethostbyname(msg->name, msg->addr, do_dns_found, msg);
  if (*msg->err != ERR_INPROGRESS) {
    /* on error or immediate success, wake up the application
     * task waiting in netconn_gethostbyname */
    sys_sem_signal(msg->sem);
  }
}
#endif /* LWIP_DNS */

#endif /* LWIP_NETCONN */


text:
var parser = require('cheerio');
var Promise = require('bluebird');

// Includes
var http = require('../util/http.js').func;
var jar = require('../util/jar.js').func;
var getRole = require('./getRole.js').func;
var getRoles = require('./getRoles.js').func;
var generalRequest = require('../util/generalRequest.js').func;
var threaded = require('../util/threaded.js').func;

// Args
exports.required = ['group'];
exports.optional = [['rank', 'roleset', 'name'], 'page', 'stream'];

// Define
var maxPageSize = 12;

function getPlayers (group, rankIndex, role, page, body) {
  var $ = parser.load(body);
  var pager = $('.paging_pagenums_container');
  var totalPages = pager.length > 0 ? parseInt(pager.text(), 10) : 1;
  if (group) {
    var found = $('.GroupMember');
    var players = group.players;
    for (var i = 0; i < found.length; i++) {
      var player = found.eq(i);
      var link = player.find('a').first();
      var img = player.find('.OnlineStatus').find('img').first();
      var element = {
        id: parseInt(link.attr('href').substring(29), 10),
        name: link.attr('title'),
        online: img.attr('src') === '../images/online.png',
        parent: {
          role: role,
          page: page,
          rankIndex: rankIndex
        },
        index: ((page - 1) * maxPageSize + i)
      };
      if (group.stream) {
        group.stream.write(element);
      } else {
        players.push(element);
      }
    }
  }
  $ = null;
  body = null;
  return totalPages;
}

exports.func = function (args) {
  var page = args.page;
  var groupId = args.group;
  var option;
  var optionName;
  var getStatus = function () {
    return 0;
  };
  if (args.rank) {
    option = args.rank;
    optionName = 'rank';
  } else if (args.roleset) {
    option = args.roleset;
    optionName = 'id';
  } else if (args.name) {
    option = args.name;
    optionName = 'name';
  }
  var isArray = page instanceof Array;
  var group = {
    players: [],
    stream: args.stream || false,
    totalPages: []
  };
  if (page && !isArray) {
    page = [page];
  } else if (page) {
    page = page.sort(function (a, b) {
      return a - b;
    });
  }
  if (option && !(option instanceof Array)) {
    option = [option];
  }

  function getPages (inputs, rankIndex, role, pages, totalPages) {
    function getPage (i) {
      var page = isArray ? pages[i] : i;
      if (page > totalPages) {
        return Promise.resolve();
      }
      var httpOpt = {
        url: '//www.roblox.com/Groups/Group.aspx?gid=' + groupId,
        options: {
          method: 'POST',
          form: inputs,
          headers: {
            'User-Agent': 'Mozilla'
          },
          jar: jar()
        }
      };
      var form = httpOpt.options.form;
      form.ctl00$cphRoblox$rbxGroupRoleSetMembersPane$dlUsers_Footer$ctl01$PageTextBox = page;
      form.ctl00$cphRoblox$rbxGroupRoleSetMembersPane$dlUsers_Footer$ctl01$HiddenInputButton = '';
      return http(httpOpt)
      .then(function (body) {
        getPlayers(group, rankIndex, role, page, body);
      });
    }
    var start, end;
    var isArray = pages instanceof Array;
    if (isArray) {
      start = 0;
      end = pages.length;
    } else {
      start = 2;
      end = pages + 1;
    }

    return threaded({getPage: getPage, start: start, end: end});
  }

  function getRolesets (group, groupId, roles, pages, all) {
    var jobs = [];
    var statuses = [];
    for (var i = 0; i < roles.length; i++) {
      (function (i) {
        var role = roles[i];
        var id = role.ID;
        var opt = {
          url: '//www.roblox.com/Groups/Group.aspx?gid=' + groupId,
          getBody: true,
          ignoreCache: true,
          events: {
            ctl00$cphRoblox$rbxGroupRoleSetMembersPane$dlRolesetList: id,
            ctl00$cphRoblox$rbxGroupRoleSetMembersPane$currentRoleSetID: id,
            __EVENTTARGET: 'ctl00$cphRoblox$rbxGroupRoleSetMembersPane$dlRolesetList',
            __ASYNCPOST: 'true'
          },
          jar: jar(), // Must be an empty jar or stuff just doesn't work correctly
          http: {
            headers: {
              'User-Agent': 'Mozilla'
            }
          }
        };
        jobs.push(generalRequest(opt)
        .then(function (response) {
          var body = response.res.body;
          var inputs = {
            __EVENTTARGET: '',
            __VIEWSTATE: body.match(/__VIEWSTATE\|(.*?)\|/)[1],
            __EVENTVALIDATION: body.match(/__EVENTVALIDATION\|(.*?)\|/)[1],
            __ASYNCPOST: 'true',
            ctl00$cphRoblox$rbxGroupRoleSetMembersPane$currentRoleSetID: id
          };
          var first = pages ? pages.indexOf(1) : 0;
          var totalPages = getPlayers(first !== -1 ? group : null, i, role, 1, body, all);
          group.totalPages.push({
            role: role,
            total: totalPages
          });
          var page = pages;
          if (pages && first !== -1) {
            page = pages.slice();
            page.splice(first, 1);
          }
          var promise = getPages(inputs, i, role, page || totalPages, totalPages);
          statuses.push({
            completed: promise.getCompleted,
            expected: promise.getExpected
          });
          return promise;
        }));
      })(i);
    }
    getStatus = function () {
      var completed = 0;
      var expected = 0;
      for (var i = 0; i < statuses.length; i++) {
        completed += statuses[i].completed();
        expected += statuses[i].expected();
      }
      return Math.round((completed / expected) * 10000) / 100 || 0;
    };
    return Promise.all(jobs).then(function () {
      if (group.stream) {
        group.stream.end();
      } else {
        group.players = group.players.sort(function (a, b) {
          return a.parent.rankIndex - b.parent.rankIndex || a.index - b.index;
        });
      }
      return group;
    });
  }

  var promise;
  if (optionName === 'id') {
    promise = getRolesets({ID: option});
  } else {
    var rolesets;
    if (option) {
      rolesets = [];
      var opt = {
        group: groupId
      };
      opt[optionName] = option;
      promise = getRole(opt)
      .then(function (roles) {
        return getRolesets(group, groupId, roles, page, false);
      });
    } else {
      promise = getRoles({group: groupId})
      .then(function (roles) {
        return getRolesets(group, groupId, option ? rolesets : roles, page, true);
      });
    }
  }
  promise.getStatus = function () {
    return getStatus();
  };
  return promise;
};

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var SchemaType = require('../schematype');
var util = require('../util');
var cuid = require('cuid');
var ValidationError = require('../error/validation');

/**
 * [CUID](https://github.com/ericelliott/cuid) schema type.
 *
 * @class
 * @param {String} name
 * @param {Object} [options]
 *   @param {Boolean} [options.required=false]
 * @extends {SchemaType}
 */
function SchemaTypeCUID(name, options) {
  SchemaType.call(this, name, options);
}

util.inherits(SchemaTypeCUID, SchemaType);

/**
 * Casts data. Returns a new CUID only if value is null and the field is
 * required.
 *
 * @param {String} value
 * @param {Object} data
 * @return {String}
 */
SchemaTypeCUID.prototype.cast = function(value, data) {
  if (value == null && this.options.required) {
    return cuid();
  }

  return value;
};

/**
 * Validates data. A valid CUID must be started with `c` and 25 in length.
 *
 * @param {*} value
 * @param {Object} data
 * @return {String|Error}
 */
SchemaTypeCUID.prototype.validate = function(value, data) {
  if (value && (value[0] !== 'c' || value.length !== 25)) {
    throw new ValidationError('`' + value + '` is not a valid CUID');
  }

  return value;
};

module.exports = SchemaTypeCUID;


text: ./simple-test.sh `basename $0 .sh` test6 --help


text:
use std::process::Command;
use std::env;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();

    println!("building libcudd.so");
    let st = Command::new("/bin/sh")
        .args(&["build-libcudd.sh"])
        .status().unwrap();
    if !st.success() {
        panic!("couldn't build libcudd, exit code: {}", st)}

    println!("cargo:rustc-link-search={}", out_dir);
    println!("cargo:rustc-link-lib=cudd")}


text:
package com.planet_ink.coffee_mud.Exits.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.Readable;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

/**
 * An interface for all mechanisms or pathways through which a mob may
 * travel when trying to get from one Room to another.
 * @see com.planet_ink.coffee_mud.Locales.interfaces.Room
 */
public interface Exit extends PhysicalAgent, Readable
{
	/**
	 * Returns whether this exit is OPEN and may be travelled through
	 * @return whether this exit is OPEN and may be travelled through
	 */
	public boolean isOpen();

	/**
	 * Returns whether this exit is LOCKED, and must be unlocked before
	 * being used.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasALock()
	 * @return true if locked, false otherwise
	 */
	public boolean isLocked();

	/**
	 * Returns whether this exit has a door, and must be opened before
	 * being used.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isOpen()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isLocked()
	 * @return true if a door is present, false otherwise.
	 */
	public boolean hasADoor();

	/**
	 * Returns whether this exit has a lock on its door, and, if locked,
	 * must be unlocked before being used.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isOpen()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isLocked()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @return whether a lock is present
	 */
	public boolean hasALock();

	/**
	 * For exits with a door and lock, this returns whether the door
	 * defaults in a closed and locked state.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsClosed()
	 * @return true if defaults closed and locked, false otherwise
	 */
	public boolean defaultsLocked();

	/**
	 * For exits with a door, this returns whether the door
	 * defaults in a closed state.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsLocked()
	 * @return true if defaults closed, false otherwise
	 */
	public boolean defaultsClosed();

	/**
	 * Modifies the various door/lock settings for this exit.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isOpen()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#isLocked()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasALock()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsClosed()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsLocked()
	 * @param hasADoor whether this exit has a door
	 * @param isOpen whether this exit is open for travel
	 * @param defaultsClosed whether this exit defaults closed
	 * @param hasALock whether this exit has a door lock
	 * @param isLocked whether this exit is presently locked
	 * @param defaultsLocked whether this exit defaults closed and locked.
	 */
	public void setDoorsNLocks(boolean hasADoor,
							   boolean isOpen,
							   boolean defaultsClosed,
							   boolean hasALock,
							   boolean isLocked,
							   boolean defaultsLocked);

	/**
	 * For Exits with doors and locks, this returns the unique string
	 * representing the key code required to unlock/lock the door.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setKeyName(String)
	 * @return the key code
	 */
	public String keyName();

	/**
	 * For Exits with doors and locks, this sets the unique string
	 * representing the key code required to unlock/lock the door.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#keyName()
	 * @param keyName the new key code
	 */
	public void setKeyName(String keyName);

	/**
	 * Both reads and optionally modifies an internal reference counter for this
	 * exit.  Not currently functional.
	 * @param change 0 to make no change, or a positive or negative number
	 * @return the value of the usage counter after the change is applied
	 */
	public short exitUsage(short change);

	/**
	 * Returns the modified and qualified player-viewed description of this exit.
	 * @param mob the mob doing the viewing
	 * @param myRoom the room from which the mob sees the exit
	 * @return the description of this exit from the given player pov
	 */
	public StringBuilder viewableText(MOB mob, Room myRoom);

	/**
	 * Returns the short name of this door, e.g. gate, door, portal, etc..
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setExitParams(String, String, String, String)
	 * @return the short name of this door.
	 */
	public String doorName();

	/**
	 * Returns the verb used for describing closing this exit, e.g. close,
	 * lower, drop, etc..
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#openWord()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsClosed()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setExitParams(String, String, String, String)
	 * @return the short name of a verb used when closing this door.
	 */
	public String closeWord();

	/**
	 * Returns the verb used for describing opening this exit, e.g. open,
	 * raise, lift, etc..
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#closeWord()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsClosed()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setExitParams(String, String, String, String)
	 * @return the short name of a verb used when opening this door.
	 */
	public String openWord();

	/**
	 * Returns a text description of what this exit looks like when closed.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#hasADoor()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#defaultsClosed()
	 * @return A description of this exit when closed.
	 */
	public String closedText();

	/**
	 * Sets various word descriptions used when doing some dynamic manipulations
	 * of this exit.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#closeWord()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#openWord()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#doorName()
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#closedText()
	 * @param newDoorName short name of this door, e.g. door, gate
	 * @param newCloseWord verb used to close this door, e.g. close, lower
	 * @param newOpenWord verb used to open this door, e.g. open, raise
	 * @param newClosedText description of this exit when in a closed state
	 */
	public void setExitParams(String newDoorName,
							  String newCloseWord,
							  String newOpenWord,
							  String newClosedText);

	/**
	 * Returns the number of ticks that this exit remains open when a mob
	 * or player changes it from a closed to an open state, and the door
	 * defaults in a closed state.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setOpenDelayTicks(int)
	 * @see com.planet_ink.coffee_mud.core.interfaces.Tickable#TICKID_EXIT_REOPEN
	 * @return the number of ticks this exit remains open
	 */
	public int openDelayTicks();

	/**
	 * Sets the number of ticks that this exit will remain open when a mob
	 * or player changes it from a closed to an open state, and the door
	 * defaults in a closed state.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#openDelayTicks()
	 * @see com.planet_ink.coffee_mud.core.interfaces.Tickable#TICKID_EXIT_REOPEN
	 * @param numTicks the number of ticks this exit will remain open
	 */
	public void setOpenDelayTicks(int numTicks);

	/**
	 * If this exit represents a route to a room not yet created, but whose room id
	 * is already known, this will return that designated room id.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#setTemporaryDoorLink(String)
	 * @return the room id of the room that will be linked in later
	 */
	public String temporaryDoorLink();

	/**
	 * If this exit represents a route to a room not yet created, but whose room id
	 * is already known, this will set that designated room id.
	 * @see com.planet_ink.coffee_mud.Exits.interfaces.Exit#temporaryDoorLink()
	 * @param link the room id of the room that will be linked in later
	 */
	public void setTemporaryDoorLink(String link);

	/**
	 * Returns the very last room from or to which this exit was used.
	 * @return the last room that mattered to this exit
	 */
	public Room lastRoomUsedFrom();
}


text:
namespace ash {

namespace multidevice_setup {

// Test AccountStatusChangeDelegateNotifier implementation.
class FakeAccountStatusChangeDelegateNotifier
    : public AccountStatusChangeDelegateNotifier {
 public:
  FakeAccountStatusChangeDelegateNotifier() = default;

  FakeAccountStatusChangeDelegateNotifier(
      const FakeAccountStatusChangeDelegateNotifier&) = delete;
  FakeAccountStatusChangeDelegateNotifier& operator=(
      const FakeAccountStatusChangeDelegateNotifier&) = delete;

  ~FakeAccountStatusChangeDelegateNotifier() override = default;

  using AccountStatusChangeDelegateNotifier::delegate;
};

}  // namespace multidevice_setup

}  // namespace ash

#endif  // ASH_SERVICES_MULTIDEVICE_SETUP_FAKE_ACCOUNT_STATUS_CHANGE_DELEGATE_NOTIFIER_H_


text:
{-# LANGUAGE DeriveGeneric #-}

module SymPath
  ( SymPath (..),
    mangle,
    pathToC,
    consPath,
    fromStrings,
  )
where

import Data.Char (isAscii, ord)
import Data.Hashable
import GHC.Generics (Generic)
import qualified Map
import Util

-- | The path to a binding
data SymPath = SymPath [String] String deriving (Ord, Eq, Generic)

instance Hashable SymPath

instance Show SymPath where
  show (SymPath modulePath symName) =
    if null modulePath
      then symName
      else joinWithPeriod modulePath ++ "." ++ symName

mangle :: String -> String
mangle = ureplace . sreplace . creplace
  where
    creplace =
      replaceChars
        ( Map.fromList
            [ ('+', "_PLUS_"),
              ('-', "_MINUS_"),
              ('*', "_MUL_"),
              ('/', "_DIV_"),
              ('<', "_LT_"),
              ('>', "_GT_"),
              ('?', "_QMARK_"),
              ('!', "_BANG_"),
              ('=', "_EQ_")
            ]
        )
    sreplace =
      replaceStrings
        ( Map.fromList
            [ ("auto", "_AUTO_"),
              ("break", "_BREAK_"),
              ("case", "_CASE_"),
              ("const", "_CONST_"),
              ("char", "_CHAR_"),
              ("continue", "_CONTINUE_"),
              ("default", "_DEFAULT_"),
              ("do", "_DO_"),
              ("double", "_DOUBLE_"),
              ("else", "_ELSE_"),
              ("enum", "_ENUM_"),
              ("extern", "_EXTERN"),
              ("float", "_FLOAT_"),
              ("for", "_FOR"),
              ("goto", "_GOTO_"),
              ("if", "_IF_"),
              ("int", "_INT_"),
              ("long", "_LONG_"),
              ("register", "_REGISTER_"),
              ("return", "_RETURN_"),
              ("short", "_SHORT_"),
              ("signed", "_SIGNED_"),
              ("sizeof", "_SIZEOF_"),
              ("static", "_STATIC_"),
              ("struct", "_STRUCT_"),
              ("switch", "_SWITCH_"),
              ("typedef", "_TYPEDEF_"),
              ("union", "_UNION_"),
              ("unsigned", "_UNSIGNED_"),
              ("volatile", "_VOLATILE_"),
              ("void", "_VOID_"),
              ("while", "_WHILE_")
            ]
        )
    ureplace = concatMap (\c -> if isAscii c then pure c else "_U" ++ show (ord c) ++ "U_")

pathToC :: SymPath -> String
pathToC (SymPath modulePath name) =
  concatMap ((++ "_") . mangle) modulePath ++ mangle name

-- | Add qualifying strings to beginning of a path.
consPath :: [String] -> SymPath -> SymPath
consPath qualifyers (SymPath stringPaths name) =
  SymPath (qualifyers ++ stringPaths) name

-- | Convert a list of strings into a path.
fromStrings :: [String] -> SymPath
fromStrings [] = SymPath [] ""
fromStrings (s : []) = SymPath [] s
fromStrings ss = SymPath (init ss) (last ss)


text:
#include <aws/imagebuilder/model/LaunchPermissionConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace imagebuilder
{
namespace Model
{

LaunchPermissionConfiguration::LaunchPermissionConfiguration() :
    m_userIdsHasBeenSet(false),
    m_userGroupsHasBeenSet(false),
    m_organizationArnsHasBeenSet(false),
    m_organizationalUnitArnsHasBeenSet(false)
{
}

LaunchPermissionConfiguration::LaunchPermissionConfiguration(JsonView jsonValue) :
    m_userIdsHasBeenSet(false),
    m_userGroupsHasBeenSet(false),
    m_organizationArnsHasBeenSet(false),
    m_organizationalUnitArnsHasBeenSet(false)
{
  *this = jsonValue;
}

LaunchPermissionConfiguration& LaunchPermissionConfiguration::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("userIds"))
  {
    Array<JsonView> userIdsJsonList = jsonValue.GetArray("userIds");
    for(unsigned userIdsIndex = 0; userIdsIndex < userIdsJsonList.GetLength(); ++userIdsIndex)
    {
      m_userIds.push_back(userIdsJsonList[userIdsIndex].AsString());
    }
    m_userIdsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("userGroups"))
  {
    Array<JsonView> userGroupsJsonList = jsonValue.GetArray("userGroups");
    for(unsigned userGroupsIndex = 0; userGroupsIndex < userGroupsJsonList.GetLength(); ++userGroupsIndex)
    {
      m_userGroups.push_back(userGroupsJsonList[userGroupsIndex].AsString());
    }
    m_userGroupsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("organizationArns"))
  {
    Array<JsonView> organizationArnsJsonList = jsonValue.GetArray("organizationArns");
    for(unsigned organizationArnsIndex = 0; organizationArnsIndex < organizationArnsJsonList.GetLength(); ++organizationArnsIndex)
    {
      m_organizationArns.push_back(organizationArnsJsonList[organizationArnsIndex].AsString());
    }
    m_organizationArnsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("organizationalUnitArns"))
  {
    Array<JsonView> organizationalUnitArnsJsonList = jsonValue.GetArray("organizationalUnitArns");
    for(unsigned organizationalUnitArnsIndex = 0; organizationalUnitArnsIndex < organizationalUnitArnsJsonList.GetLength(); ++organizationalUnitArnsIndex)
    {
      m_organizationalUnitArns.push_back(organizationalUnitArnsJsonList[organizationalUnitArnsIndex].AsString());
    }
    m_organizationalUnitArnsHasBeenSet = true;
  }

  return *this;
}

JsonValue LaunchPermissionConfiguration::Jsonize() const
{
  JsonValue payload;

  if(m_userIdsHasBeenSet)
  {
   Array<JsonValue> userIdsJsonList(m_userIds.size());
   for(unsigned userIdsIndex = 0; userIdsIndex < userIdsJsonList.GetLength(); ++userIdsIndex)
   {
     userIdsJsonList[userIdsIndex].AsString(m_userIds[userIdsIndex]);
   }
   payload.WithArray("userIds", std::move(userIdsJsonList));

  }

  if(m_userGroupsHasBeenSet)
  {
   Array<JsonValue> userGroupsJsonList(m_userGroups.size());
   for(unsigned userGroupsIndex = 0; userGroupsIndex < userGroupsJsonList.GetLength(); ++userGroupsIndex)
   {
     userGroupsJsonList[userGroupsIndex].AsString(m_userGroups[userGroupsIndex]);
   }
   payload.WithArray("userGroups", std::move(userGroupsJsonList));

  }

  if(m_organizationArnsHasBeenSet)
  {
   Array<JsonValue> organizationArnsJsonList(m_organizationArns.size());
   for(unsigned organizationArnsIndex = 0; organizationArnsIndex < organizationArnsJsonList.GetLength(); ++organizationArnsIndex)
   {
     organizationArnsJsonList[organizationArnsIndex].AsString(m_organizationArns[organizationArnsIndex]);
   }
   payload.WithArray("organizationArns", std::move(organizationArnsJsonList));

  }

  if(m_organizationalUnitArnsHasBeenSet)
  {
   Array<JsonValue> organizationalUnitArnsJsonList(m_organizationalUnitArns.size());
   for(unsigned organizationalUnitArnsIndex = 0; organizationalUnitArnsIndex < organizationalUnitArnsJsonList.GetLength(); ++organizationalUnitArnsIndex)
   {
     organizationalUnitArnsJsonList[organizationalUnitArnsIndex].AsString(m_organizationalUnitArns[organizationalUnitArnsIndex]);
   }
   payload.WithArray("organizationalUnitArns", std::move(organizationalUnitArnsJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace imagebuilder
} // namespace Aws


text:
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.TestFramework
{
    using System;
    using System.Threading.Tasks;

    public class TestObserver<T> :
        IObserver<ConsumeContext<T>>
        where T : class
    {
        readonly TaskCompletionSource<bool> _completed;
        readonly TaskCompletionSource<Exception> _exception;
        readonly TaskCompletionSource<ConsumeContext<T>> _value;

        public TestObserver(TaskCompletionSource<ConsumeContext<T>> value, TaskCompletionSource<Exception> exception, TaskCompletionSource<bool> completed)
        {
            _value = value;
            _exception = exception;
            _completed = completed;
        }

        public Task<ConsumeContext<T>> Value
        {
            get { return _value.Task; }
        }

        public TaskCompletionSource<bool> Completed
        {
            get { return _completed; }
        }

        public TaskCompletionSource<Exception> Exception
        {
            get { return _exception; }
        }

        public void OnNext(ConsumeContext<T> value)
        {
            _value.TrySetResult(value);
        }

        public void OnError(Exception error)
        {
            _exception.TrySetException(error);
        }

        public void OnCompleted()
        {
            _completed.TrySetResult(true);
        }
    }
}


text:
package com.github.spreadsheets.android.api.model;

import com.google.api.client.util.Key;

public class BatchOperation {

  public static final BatchOperation INSERT = BatchOperation.of("insert");
  public static final BatchOperation QUERY = BatchOperation.of("query");
  public static final BatchOperation UPDATE = BatchOperation.of("update");
  public static final BatchOperation DELETE = BatchOperation.of("delete");

  @Key("@type")
  public String type;

  public BatchOperation() {
  }

  public static BatchOperation of(String type) {
    BatchOperation result = new BatchOperation();
    result.type = type;
    return result;
  }
}


text:
.class Landroid/widget/VideoView$4$1;
.super Ljava/lang/Object;
.source "VideoView.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/widget/VideoView$4;->onError(Landroid/media/MediaPlayer;II)Z
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Landroid/widget/VideoView$4;

# direct methods
.method constructor <init>(Landroid/widget/VideoView$4;)V
    .locals 0
    .parameter

    .prologue
    .line 397
    iput-object p1, p0, Landroid/widget/VideoView$4$1;->this$1:Landroid/widget/VideoView$4;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 2
    .parameter "dialog"
    .parameter "whichButton"

    .prologue
    .line 402
    iget-object v0, p0, Landroid/widget/VideoView$4$1;->this$1:Landroid/widget/VideoView$4;

    iget-object v0, v0, Landroid/widget/VideoView$4;->this$0:Landroid/widget/VideoView;

    #getter for: Landroid/widget/VideoView;->mOnCompletionListener:Landroid/media/MediaPlayer$OnCompletionListener;
    invoke-static {v0}, Landroid/widget/VideoView;->access$1400(Landroid/widget/VideoView;)Landroid/media/MediaPlayer$OnCompletionListener;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 403
    iget-object v0, p0, Landroid/widget/VideoView$4$1;->this$1:Landroid/widget/VideoView$4;

    iget-object v0, v0, Landroid/widget/VideoView$4;->this$0:Landroid/widget/VideoView;

    #getter for: Landroid/widget/VideoView;->mOnCompletionListener:Landroid/media/MediaPlayer$OnCompletionListener;
    invoke-static {v0}, Landroid/widget/VideoView;->access$1400(Landroid/widget/VideoView;)Landroid/media/MediaPlayer$OnCompletionListener;

    move-result-object v0

    iget-object v1, p0, Landroid/widget/VideoView$4$1;->this$1:Landroid/widget/VideoView$4;

    iget-object v1, v1, Landroid/widget/VideoView$4;->this$0:Landroid/widget/VideoView;

    #getter for: Landroid/widget/VideoView;->mMediaPlayer:Landroid/media/MediaPlayer;
    invoke-static {v1}, Landroid/widget/VideoView;->access$800(Landroid/widget/VideoView;)Landroid/media/MediaPlayer;

    move-result-object v1

    invoke-interface {v0, v1}, Landroid/media/MediaPlayer$OnCompletionListener;->onCompletion(Landroid/media/MediaPlayer;)V

    .line 405
    :cond_0
    return-void
.end method


text:
cask 'splashtop-business' do
  version '3.2.4.0'
  sha256 '9f6479f313a0db992ba95412c2653e6843dc04356f9102611c61972cc5f7437a'

  # d17kmd0va0f0mp.cloudfront.net/macclient/STB was verified as official when first introduced to the cask
  url "https://d17kmd0va0f0mp.cloudfront.net/macclient/STB/Splashtop_Business_Mac_INSTALLER_v#{version}.dmg"
  appcast 'https://www.splashtop.com/wp-content/themes/responsive/downloadx.php?product=stb&platform=mac-client',
          checkpoint: 'bb47a3c4c584d60148d778a25157104aa80f03357ffbc270d68fac312aafe584'
  name 'Splashtop Business'
  homepage 'https://www.splashtop.com/business'

  pkg 'Splashtop Business.pkg'

  uninstall pkgutil: [
                       'com.splashtop.stb.*',
                       'com.splashtop.splashtopBusiness.*',
                     ]
end


text:
package com.example.yangxiaoyu.coolweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.filterfw.io.TextGraphReader;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.yangxiaoyu.coolweather.gson.Forecast;
import com.example.yangxiaoyu.coolweather.gson.Weather;
import com.example.yangxiaoyu.coolweather.service.AutoUpdateService;
import com.example.yangxiaoyu.coolweather.util.HttpUtil;
import com.example.yangxiaoyu.coolweather.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private static final String TAG ="WeatherActivity";
    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;
    private ImageView bingPicImg;
    public SwipeRefreshLayout swipeRefresh;
    private String mWeatherId;
    public DrawerLayout drawerLayout;
    private Button navButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT>=21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);
        weatherLayout = (ScrollView)findViewById(R.id.weather_layout);
        titleCity = (TextView)findViewById(R.id.title_city);
        titleUpdateTime = (TextView)findViewById(R.id.title_update_time);
        degreeText = (TextView)findViewById(R.id.degree_text);
        weatherInfoText = (TextView)findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout)findViewById(R.id.forecast_layout);
        comfortText = (TextView)findViewById(R.id.comfort_text);
        carWashText = (TextView)findViewById(R.id.car_wash_text);
        aqiText = (TextView)findViewById(R.id.aqi_text);
        pm25Text= (TextView)findViewById(R.id.pm25_text);
        sportText = (TextView)findViewById(R.id.sport_text);
        bingPicImg = (ImageView)findViewById(R.id.bing_pic_img);

        swipeRefresh= (SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);

        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        navButton = (Button)findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = prefs.getString("weather",null);
        String bingPic = prefs.getString("bing_pic",null);
        if(bingPic != null){
            Glide.with(this).load(bingPic).into(bingPicImg);
        }else{
            loadBingPic();
        }
        Log.d(TAG, "onCreate: "+ weatherString);
        if(weatherString != null){
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
        }else{
            mWeatherId = getIntent().getStringExtra("weather_id");
//            String weatherId = getIntent().getStringExtra("weather_id");
            Log.d(TAG, "onCreate: weatherId =" + mWeatherId);
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });
    }

    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });

            }
        });
    }

    public void requestWeather(final String weatherId){
        String weatherUrl = "http://guolin.tech/api/weather?cityid="+ weatherId +"&key=55e3fae1368b42af8fed4102cbb894c2";
        Log.d(TAG, "requestWeather: weatherUrl= "+weatherUrl);
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"获取天气消息失败",Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);
                    }
                });
                loadBingPic();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Log.d("WeatherActivity    ", "onResponse: "+ responseText);
                final Weather weather = Utility.handleWeatherResponse(responseText);
                Log.d(TAG, "onResponse: " + weather);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ( weather != null && "ok".equals(weather.status)) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(WeatherActivity.this, "获取天气消息失败", Toast.LENGTH_SHORT).show();
                        }
                        swipeRefresh.setRefreshing(false);
                    }
                });

            }
        });
    }
    private void showWeatherInfo(Weather weather){
        if(weather != null &&"ok".equals(weather.status)){
            String cityName = weather.basic.cityName;
            String updateTime = weather.basic.update.updateTime.split(" ")[1];
            String degree = weather.now.temperature+"℃";
            String weatherInfo = weather.now.more.info;
            titleCity.setText(cityName);
            titleUpdateTime.setText(updateTime);
            degreeText.setText(degree);
            weatherInfoText.setText(weatherInfo);
            forecastLayout.removeAllViews();
            for(Forecast forecast:weather.forecastList){
                View view = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.forecast_item,forecastLayout,false);
                TextView dateText = (TextView)view.findViewById(R.id.data_text);
                TextView infoText = (TextView)view.findViewById(R.id.info_text);
                TextView maxText = (TextView)view.findViewById(R.id.max_text);
                TextView minText = (TextView)view.findViewById(R.id.min_text);
                Log.d(TAG, "showWeatherInfo: forecastList" + weather.forecastList);
                Log.d(TAG, "showWeatherInfo: forecast = "+forecast.date);
                Log.d(TAG, "showWeatherInfo: forecast.more.info= "+forecast.more.info);
                Log.d(TAG, "showWeatherInfo: forecast.temperature.max="+forecast.temperature.max);
                Log.d(TAG, "showWeatherInfo: forecast.temperature.min="+forecast.temperature.min);
                Log.d(TAG, "showWeatherInfo: View dengyu "+view);
                Log.d(TAG, "showWeatherInfo: "+dateText);
                Log.d(TAG, "showWeatherInfo: "+comfortText);
                dateText.setText(forecast.date);
                infoText.setText(forecast.more.info);
                maxText.setText(forecast.temperature.max);
                minText.setText(forecast.temperature.min);
                forecastLayout.addView(view);
            }
            if(weather.aqi != null){
                aqiText.setText(weather.aqi.city.aqi);
                pm25Text.setText(weather.aqi.city.pm25);
                Log.d(TAG, "showWeatherInfo: "+aqiText);
                Log.d(TAG, "showWeatherInfo: "+pm25Text);
                Log.d(TAG, "showWeatherInfo: aqiText is "+weather.aqi.city.aqi);
                Log.d(TAG, "showWeatherInfo: pm25Text is "+weather.aqi.city.pm25);
            }
            String comfort = "舒适度"+weather.suggestion.comfort.info;
            String carWash= "汽车指数"+weather.suggestion.carWash.info;
            String sport = "运动建议"+weather.suggestion.sport.info;
            Log.d(TAG, "showWeatherInfo: comfort is "+comfort);
            comfortText.setText(comfort);
            carWashText.setText(carWash);
            sportText.setText(sport);
            weatherLayout.setVisibility(View.VISIBLE);
            Intent intent = new Intent(this, AutoUpdateService.class);
            startService(intent);
        }else {
            Toast.makeText(WeatherActivity.this,"获取天气消息失败",Toast.LENGTH_SHORT).show();
        }
        }
}


text:
const webpack = require('webpack')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    app: ['whatwg-fetch', './src'],
    css: 'tachyons',
  },
  output: {
    path: './dist',
    filename: '[name].[hash].js',
    publicPath: '/',
  },
  module: {
    rules: [{
      enforce: 'pre',
      test: /\.ts(x?)$/,
      loader: 'tslint-loader',
      exclude: /node_modules/,
    }, {
      test: /module\.styl/,
      loader: 'style-loader!css-loader?modules!postcss-loader!stylus-loader',
    }, {
      test: /module\.css/,
      loader: 'style-loader!css-loader?modules!postcss-loader',
    }, {
      test: /\.css/,
      exclude: /module\.css/,
      loader: 'style-loader!css-loader!postcss-loader',
    }, {
      test: /\.ts(x?)$/,
      exclude: /node_modules/,
      loader: 'babel-loader!awesome-typescript-loader',
    }, {
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
    }, {
      test: /\.json/,
      loader: 'json-loader',
    }, {
      test: /\.(jpg|png)/,
      loader: 'file-loader',
    }, {
      test: /content\/.*\.svg$/,
      loader: 'file-loader',
    }, {
      test: /icons\/.*\.svg$/,
      loader: 'raw-loader!svgo-loader?{"plugins":[{"removeStyleElement":true}]}',
    }, {
      test: /\.md/,
      loader: 'raw-loader',
    }],
  },
  plugins: [
    new webpack.DefinePlugin({
      __LAST_UPDATE__: '"' + new Date().toLocaleDateString() + '"',
      __GA_TRACKING_CODE__: '"UA-74131346-6"',
      __GITHUB_OAUTH_CLIENT_ID__: JSON.stringify(process.env.GITHUB_OAUTH_CLIENT_ID.toString()),
      __LAMBDA_AUTH__: '"https://learnx.graph.cool/prod/learnapollo"',
      __LAMBDA_DOWNLOAD_EXAMPLE__: '"https://dynamic-resources.graph.cool"',
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      },
    }),
    new HtmlWebpackPlugin({
      favicon: 'static/favicon.png',
      template: 'src/index.html',
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        warnings: false,
      }
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          cssnano({
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll: true,
            },
            safe: true,
          })
        ],
        svgo: {
          plugins: [
            {removeStyleElement: true},
          ],
        },
      }
    }),
  ],
  resolve: {
    extensions: ['.js', '.ts', '.tsx'],
  }
}


text:
module Xero
  module Models
    class BaseModel
      include ActiveAttr::Model
      include ActiveAttr::Attributes
      include Xero::Associations

      class << self
        attr_accessor :path
      end

      attribute :id

      attr_accessor :new_record, :client

      def initialize(attributes = {})
        super(cleanup_hash(attributes))
        @new_record = true
      end

      def attributes=(attrs)
        cleanup_hash(attrs).each do |key, value|
          send("#{key}=", value) unless value.blank?
        end
      end

      def save
        raise StandardError if self.client.blank?
        self.client.save(self)
      end

      def xero_attributes(attrs = nil)
        attrs ||= attributes.clone
        id = attrs.delete('id')
        attrs.delete('updated_date_utc')
        attrs.keys.each do |key|
          value = attrs.delete(key)
          value = xero_attributes(value) if value.is_a?(Hash)
          attrs[build_xero_key(key)] = value.to_s unless value.blank?
        end
        attrs.merge!("#{self.class.to_s.demodulize}ID" => id) unless id.blank?
        attrs
      end

      def build_xero_key(key)
        key.to_s.camelize.gsub(/Id$/, 'ID')
      end

      def cleanup_hash(hash)
        hash.keys.each do |key|
          value = hash.delete(key)
          value = cleanup_hash(value) if value.is_a?(Hash)
          key = key.to_s.underscore
          key = 'id' if key == id_attribute
          hash[key] = value
        end
        hash
      end

      def id_attribute
        @id_attribute ||= "#{self.class.name.demodulize.underscore}_id"
      end

      def persisted?
        id && !@new_record
      end
    end
  end
end


text:
#include <cutils/sockets.h>

#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>

static int toggle_O_NONBLOCK(int s) {
    int flags = fcntl(s, F_GETFL);
    if (flags == -1 || fcntl(s, F_SETFL, flags ^ O_NONBLOCK) == -1) {
        close(s);
        return -1;
    }
    return s;
}

// Connect to the given host and port.
// 'timeout' is in seconds (0 for no timeout).
// Returns a file descriptor or -1 on error.
// On error, check *getaddrinfo_error (for use with gai_strerror) first;
// if that's 0, use errno instead.
int socket_network_client_timeout(const char* host, int port, int type, int timeout,
                                  int* getaddrinfo_error) {
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = type;

    char port_str[16];
    snprintf(port_str, sizeof(port_str), "%d", port);

    struct addrinfo* addrs;
    *getaddrinfo_error = getaddrinfo(host, port_str, &hints, &addrs);
    if (*getaddrinfo_error != 0) {
        return -1;
    }

    int result = -1;
    for (struct addrinfo* addr = addrs; addr != NULL; addr = addr->ai_next) {
        // The Mac doesn't have SOCK_NONBLOCK.
        int s = socket(addr->ai_family, type, addr->ai_protocol);
        if (s == -1 || toggle_O_NONBLOCK(s) == -1) break;

        int rc = connect(s, addr->ai_addr, addr->ai_addrlen);
        if (rc == 0) {
            result = toggle_O_NONBLOCK(s);
            break;
        } else if (rc == -1 && errno != EINPROGRESS) {
            close(s);
            continue;
        }

        fd_set r_set;
        FD_ZERO(&r_set);
        FD_SET(s, &r_set);
        fd_set w_set = r_set;

        struct timeval ts;
        ts.tv_sec = timeout;
        ts.tv_usec = 0;
        if ((rc = select(s + 1, &r_set, &w_set, NULL, (timeout != 0) ? &ts : NULL)) == -1) {
            close(s);
            break;
        }
        if (rc == 0) {  // we had a timeout
            errno = ETIMEDOUT;
            close(s);
            break;
        }

        int error = 0;
        socklen_t len = sizeof(error);
        if (FD_ISSET(s, &r_set) || FD_ISSET(s, &w_set)) {
            if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
                close(s);
                break;
            }
        } else {
            close(s);
            break;
        }

        if (error) {  // check if we had a socket error
            // TODO: Update the timeout.
            errno = error;
            close(s);
            continue;
        }

        result = toggle_O_NONBLOCK(s);
        break;
    }

    freeaddrinfo(addrs);
    return result;
}

int socket_network_client(const char* host, int port, int type) {
    int getaddrinfo_error;
    return socket_network_client_timeout(host, port, type, 0, &getaddrinfo_error);
}


text:
"""Helper to update emoji_metadata.txt"""

from absl import app
from absl import flags
from emojicompat.compat_metadata import emoji_compat_metadata, emoji_metadata_file
import itertools
from nototools import unicode_data
from typing import Tuple

FLAGS = flags.FLAGS

flags.DEFINE_integer("sdk_added", None, "The SDK that will have the new sequences")

_IGNORED = {
    (0x20e3,),  # Keycap is an odd duck
    (0xfe82b,), # Shows up in unicode_data; not an emoji sequence per https://unicode.org/Public/emoji/15.0/emoji-test.txt
}

def _unqualify(seq: Tuple[int, ...]) -> Tuple[int, ...]:
    return tuple(c for c in seq if c != 0xfe0f)

def main(_):
    current_metadata = emoji_compat_metadata()
    max_pua = max(c.identifier for c in current_metadata)
    max_sdk_added = max(c.sdk_added for c in current_metadata)
    max_compat_added = max(c.compat_added for c in current_metadata)
    current_emoji = set(c.codepoints for c in current_metadata)

    if FLAGS.sdk_added <= max_sdk_added:
        raise ValueError(f"New sdk added must exceed previous max, --sdk_added {FLAGS.sdk_added} < {max_sdk_added}")

    new_emoji = set(_unqualify(s) for s in unicode_data.get_emoji_sequences()) - current_emoji - _IGNORED
    print(f"{len(new_emoji)} new sequences, first few")
    for s in sorted(new_emoji)[:64]:
        print(" ".join(f"{c:04x}" for c in s))

    if new_emoji:
        pua_gen = itertools.chain(range(0xE000, 0xF8FF + 1), range(0xF0000, 0xFFFFD + 1), range(0x100000, 0x10FFFD + 1))
        while next(pua_gen) <= max_pua:
            continue

        with open(emoji_metadata_file(), "a") as f:
            for seq in sorted(new_emoji):
                pua = next(pua_gen)
                assert pua > max_pua

                seq = " ".join(f"{c:04X}" for c in seq)
                f.write(f"{pua:04X} {FLAGS.sdk_added} {max_compat_added + 1} {seq}\n")

if __name__ == "__main__":
    flags.mark_flag_as_required("sdk_added")
    app.run(main)


text:
This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.

CNC Microscope is an automated microscope whose stage is built from a
Shapeoko 1 CNC router platform
(http://www.shapeoko.com/wiki/index.php/Assembly_overview_(SO1))
driven by a RepRap RAMPS (http://www.reprap.org/wiki/Ramps) and whose
illuminator is an Adafruit NeoPixel Shield
(http://www.adafruit.com/products/1430).  The microscope is assembled
using the Shapeoko, the illuminator, and an objective/optical
tube/camera assembly, all mounted to an extruded aluminum frame using
3D-printed parts.  Device adapters for the Micro-Manager software
(https://www.micro-manager.org/) make the Shapeoko and illuminator act
as XY/Z microscope stages and shutter, respectively.

Subdirectories:
cad: FreeCAD files for the 3D-printed parts
micromanager: Device adapters for the RAMPS and Adafruit NeoPixel Shield
arduino: Firmware for Arduino UNO to drive the Adafruit NeoPixel Shield

License:
Apache 2(BSD?)

Bill of Materials:

Shapeoko 1.  No longer for sale, but an X-Carve
https://www.inventables.com/technologies/x-carve should be a
reasonable replacement.

Arduino UNO.  Easily obtained from Amazon, or elsewhere.

Adafruit NeoPixel Shield.  http://www.adafruit.com/products/1430

ThorCam camera.  http://www.thorlabs.com/thorproduct.cfm?partnumber=DCC1545M

Edmunds optical tube.  http://www.edmundoptics.com/microscopy/relay-lenses-couplers/single-tube-din-microscopes-for-ocular-c-mount-camera-use/1548/

Misumi extrusion, brackets.  We ordered a pre-cut Misumi AEX BA with dimensions 410mm per side. http://us.misumi-ec.com/vona2/detail/110302285350/?Inch=0

Assembly:

Refer to the CAD diagram of the entire system for an overview.  In
short, assembly follows these steps:

1) Assemble the Shapeoko according to the Shapeoko assembly
instructions.  Omit the step of mounting the spindle holder in the
Z-axis.

2) Assemble the aluminum extrusion frame and mount it to the Shapeoko.

3) 3D print the parts, and mount them to the frame.

4) Assemble the optical tube, camera, and objective and install them
within the 3D-printed microscope to Z axis bracket.

5) Assemble the Arduino UNO, Neopixel Shield, and diffuser and install
them to the aluminum extrusion top bars.

6) Flash the ArduinoNeoPixel firmware to the UNO.

7) Build and install the Micro-Manager device adapters.

8) Run Micro-Manager, configure the device adapters.


text:
package org.codehaus.groovy.grails.compiler.injection;

import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.io.support.GrailsResourceUtils;

import java.io.File;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * Default implementation of domain class injector interface that adds the 'id'
 * and 'version' properties and other previously boilerplate code.
 *
 * @author Graeme Rocher
 * @since 0.2
 */
@AstTransformer
public class DefaultGrailsDomainClassInjector implements GrailsDomainClassInjector {

    private static final String DOMAIN_DIR = "domain";

    private static final String GRAILS_APP_DIR = "grails-app";

    private List<ClassNode> classesWithInjectedToString = new ArrayList<ClassNode>();

    public void performInjection(SourceUnit source, GeneratorContext context, ClassNode classNode) {
        if (isDomainClass(classNode, source) && shouldInjectClass(classNode)) {
            performInjectionOnAnnotatedEntity(classNode);
        }
    }

    public void performInjectionOnAnnotatedEntity(ClassNode classNode) {
        injectIdProperty(classNode);
        injectVersionProperty(classNode);
        injectToStringMethod(classNode);
        injectAssociations(classNode);
    }

    public boolean shouldInject(URL url) {
        return GrailsResourceUtils.isDomainClass(url);
    }

    protected boolean isDomainClass(@SuppressWarnings("unused") ClassNode classNode, SourceUnit sourceNode) {
        String sourcePath = sourceNode.getName();
        File sourceFile = new File(sourcePath);
        File parent = sourceFile.getParentFile();
        while (parent != null) {
            File parentParent = parent.getParentFile();
            if (parent.getName().equals(DOMAIN_DIR) && parentParent != null &&
                    parentParent.getName().equals(GRAILS_APP_DIR)) {
                return true;
            }
            parent = parentParent;
        }

        return false;
    }

    protected boolean shouldInjectClass(ClassNode classNode) {
        String fullName = GrailsASTUtils.getFullName(classNode);
        String mappingFile = getMappingFileName(fullName);

        if (getClass().getResource(mappingFile) != null) {
            return false;
        }

        return !isEnum(classNode);
    }

    /**
     * Returns the ORM framework's mapping file name for the specified class name.
     *
     * @param className The class name of the mapped file
     * @return The mapping file name
     */
    private String getMappingFileName(String className) {
        return className.replaceAll("\\.", "/") + ".hbm.xml";
    }

    private void injectAssociations(ClassNode classNode) {

        List<PropertyNode> propertiesToAdd = new ArrayList<PropertyNode>();
        for (PropertyNode pn : classNode.getProperties()) {
            final String name = pn.getName();
            final boolean isHasManyProperty = name.equals(GrailsDomainClassProperty.RELATES_TO_MANY) ||
                    name.equals(GrailsDomainClassProperty.HAS_MANY);
            if (isHasManyProperty) {
                Expression e = pn.getInitialExpression();
                propertiesToAdd.addAll(createPropertiesForHasManyExpression(e, classNode));
            }
            final boolean isBelongsTo = name.equals(GrailsDomainClassProperty.BELONGS_TO) || name.equals(GrailsDomainClassProperty.HAS_ONE);
            if (isBelongsTo) {
                Expression e = pn.getInitialExpression();
                propertiesToAdd.addAll(createPropertiesForBelongsToExpression(e, classNode));
            }
        }
        injectAssociationProperties(classNode, propertiesToAdd);
    }

    private Collection<PropertyNode> createPropertiesForBelongsToExpression(Expression e, ClassNode classNode) {
        List<PropertyNode> properties = new ArrayList<PropertyNode>();
        if (e instanceof MapExpression) {
            MapExpression me = (MapExpression) e;
            for (MapEntryExpression mme : me.getMapEntryExpressions()) {
                String key = mme.getKeyExpression().getText();
                final Expression expression = mme.getValueExpression();
                ClassNode type;
                if (expression instanceof ClassExpression) {
                    type = expression.getType();
                }
                else {
                    type = ClassHelper.make(expression.getText());
                }

                properties.add(new PropertyNode(key, Modifier.PUBLIC, type, classNode, null, null, null));
            }
        }

        return properties;
    }

    private void injectAssociationProperties(ClassNode classNode, List<PropertyNode> propertiesToAdd) {
        for (PropertyNode pn : propertiesToAdd) {
            if (!GrailsASTUtils.hasProperty(classNode, pn.getName())) {
                classNode.addProperty(pn);
            }
        }
    }

    private List<PropertyNode> createPropertiesForHasManyExpression(Expression e, ClassNode classNode) {
        List<PropertyNode> properties = new ArrayList<PropertyNode>();
        if (e instanceof MapExpression) {
            MapExpression me = (MapExpression) e;
            for (MapEntryExpression mee : me.getMapEntryExpressions()) {
                String key = mee.getKeyExpression().getText();
                addAssociationForKey(key, properties, classNode, findPropertyType(mee.getValueExpression()));
            }
        }
        return properties;
    }

    /**
     * Finds the type of the generated property.  The type will be a {@link Set} that is parameterized
     * by the type of the expression passed in.
     * @param expression the expression used to parameterize the {@link Set}.  Only used if a {@link ClassExpression}.  Otherwise ignored.
     * @return A {@link ClassNode} of type {@link Set} that is possibly parameterized by the expression that is passed in.
     */
    private ClassNode findPropertyType(Expression expression) {
        ClassNode setNode = ClassHelper.make(Set.class).getPlainNodeReference();
        if (expression instanceof ClassExpression) {
            GenericsType[] genericsTypes = new GenericsType[1];
            genericsTypes[0] = new GenericsType(GrailsASTUtils.nonGeneric(expression.getType()));
            setNode.setGenericsTypes(genericsTypes);
        }
        return setNode;
    }

    private void addAssociationForKey(String key, List<PropertyNode> properties, ClassNode declaringType, ClassNode propertyType) {
        properties.add(new PropertyNode(key, Modifier.PUBLIC, propertyType, declaringType, null, null, null));
    }

    private void injectToStringMethod(ClassNode classNode) {
        final boolean hasToString = GrailsASTUtils.implementsOrInheritsZeroArgMethod(
                classNode, "toString", classesWithInjectedToString);

        if (!hasToString && !isEnum(classNode)) {
            GStringExpression ge = new GStringExpression(classNode.getName() + " : ${id}");
            ge.addString(new ConstantExpression(classNode.getName() + " : "));
            ge.addValue(new VariableExpression("id"));
            Statement s = new ReturnStatement(ge);
            MethodNode mn = new MethodNode("toString", Modifier.PUBLIC, new ClassNode(String.class), new Parameter[0], new ClassNode[0], s);
            classNode.addMethod(mn);
            classesWithInjectedToString.add(classNode);
        }
    }

    private boolean isEnum(ClassNode classNode) {
        ClassNode parent = classNode.getSuperClass();
        while (parent != null) {
            if (parent.getName().equals("java.lang.Enum")) return true;
            parent = parent.getSuperClass();
        }
        return false;
    }

    private void injectVersionProperty(ClassNode classNode) {
        final boolean hasVersion = GrailsASTUtils.hasOrInheritsProperty(classNode, GrailsDomainClassProperty.VERSION);

        if (!hasVersion) {
            ClassNode parent = GrailsASTUtils.getFurthestUnresolvedParent(classNode);
            parent.addProperty(GrailsDomainClassProperty.VERSION, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null);
        }
    }

    private void injectIdProperty(ClassNode classNode) {
        final boolean hasId = GrailsASTUtils.hasOrInheritsProperty(classNode, GrailsDomainClassProperty.IDENTITY);

        if (!hasId) {
            // inject into furthest relative
            ClassNode parent = GrailsASTUtils.getFurthestUnresolvedParent(classNode);

            parent.addProperty(GrailsDomainClassProperty.IDENTITY, Modifier.PUBLIC, new ClassNode(Long.class), null, null, null);
        }
    }

    public void performInjection(SourceUnit source, ClassNode classNode) {
        performInjection(source, null, classNode);
    }
}


text:
package com.kodova.carpenter.progression;

import java.util.Calendar;
import java.util.Date;

public class DateMovable implements Moveable<Date> {

	Calendar calendar = Calendar.getInstance();
	int field = Calendar.DATE;
	int step = 1;

	public DateMovable(Calendar calendar, int field, int step) {
		this.calendar = calendar;
		this.field = field;
		this.step = step;

		calendar.add(field, step * -1);
	}

	public DateMovable(int field, int step) {
		this(Calendar.getInstance(), field, step);
	}

	public DateMovable() { }

	@Override
	public  Date next() {
		synchronized (this){
			calendar.add(field, step);
			return calendar.getTime();
		}
	}
}


text:
class CreateOrganisations < ActiveRecord::Migration[4.2]
  def self.up
    create_table :organisations do |t|
      t.string :name
      t.string :website

      t.timestamps
    end
  end

  def self.down
    drop_table :organisations
  end
end


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

namespace ObserverPattern.Base
{
    public interface IObservable
    {
        void SubscribeObserver(IObserver observer);
        void UnsubscribeObserver(IObserver observer);
        void NotifyObservers();

    }
}


text:
using System;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Outlander.Core.Client;
using Outlander.Core;

namespace Outlander.Core.Client.Scripting
{
	public class WaitForReTokenHandler : WeakMatchingTokenHandler
	{
		public WaitForReTokenHandler(IGameState gameState, IGameStream gameStream)
			: base(gameState, gameStream)
		{
		}

		public override Task<CompletionEventArgs> Execute(ScriptContext context, Token token)
		{
			if(context.DebugLevel > 0) {
				context.Get<IScriptLog>().Log(context.Name, "waitforre " + token.Value, context.LineNumber);
			}

			return base.Execute(context, token);
		}

		protected override IWaitForMatcher BuildMatcher(ScriptContext context, Token token)
		{
			return new WaitforRegexMatcher(context, token);
		}
	}
}


text:
package xxxxx.yyyyy.zzzzz.xyz1.lexer.impl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@lombok.extern.slf4j.Slf4j
public final class Util {

    private Util() {
    }

    public static String getResourceAsString(String name) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = classLoader.getResourceAsStream(name); Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name());) {
            return scanner.useDelimiter("\\a").next();
        } catch (IOException cause) {
            throw new RuntimeException(cause);
        }
    }
}