text:
#include "rte_eth_ring.h"
#include <rte_mbuf.h>
#include <rte_ethdev.h>
#include <rte_malloc.h>
#include <rte_memcpy.h>
#include <rte_string_fns.h>
#include <rte_dev.h>
#include <rte_kvargs.h>

#define ETH_RING_NUMA_NODE_ACTION_ARG	"nodeaction"
#define ETH_RING_ACTION_CREATE		"CREATE"
#define ETH_RING_ACTION_ATTACH		"ATTACH"

static const char *valid_arguments[] = {
	ETH_RING_NUMA_NODE_ACTION_ARG,
	NULL
};

struct ring_queue {
	struct rte_ring *rng;
	rte_atomic64_t rx_pkts;
	rte_atomic64_t tx_pkts;
	rte_atomic64_t err_pkts;
};

struct pmd_internals {
	unsigned nb_rx_queues;
	unsigned nb_tx_queues;

	struct ring_queue rx_ring_queues[RTE_PMD_RING_MAX_RX_RINGS];
	struct ring_queue tx_ring_queues[RTE_PMD_RING_MAX_TX_RINGS];
};

static struct ether_addr eth_addr = { .addr_bytes = {0} };
static const char *drivername = "Rings PMD";
static struct rte_eth_link pmd_link = {
		.link_speed = 10000,
		.link_duplex = ETH_LINK_FULL_DUPLEX,
		.link_status = 0
};

static uint16_t
eth_ring_rx(void *q, struct rte_mbuf **bufs, uint16_t nb_bufs)
{
	void **ptrs = (void *)&bufs[0];
	struct ring_queue *r = q;
	const uint16_t nb_rx = (uint16_t)rte_ring_dequeue_burst(r->rng,
			ptrs, nb_bufs);
	if (r->rng->flags & RING_F_SC_DEQ)
		r->rx_pkts.cnt += nb_rx;
	else
		rte_atomic64_add(&(r->rx_pkts), nb_rx);
	return nb_rx;
}

static uint16_t
eth_ring_tx(void *q, struct rte_mbuf **bufs, uint16_t nb_bufs)
{
	void **ptrs = (void *)&bufs[0];
	struct ring_queue *r = q;
	const uint16_t nb_tx = (uint16_t)rte_ring_enqueue_burst(r->rng,
			ptrs, nb_bufs);
	if (r->rng->flags & RING_F_SP_ENQ) {
		r->tx_pkts.cnt += nb_tx;
		r->err_pkts.cnt += nb_bufs - nb_tx;
	} else {
		rte_atomic64_add(&(r->tx_pkts), nb_tx);
		rte_atomic64_add(&(r->err_pkts), nb_bufs - nb_tx);
	}
	return nb_tx;
}

static int
eth_dev_configure(struct rte_eth_dev *dev __rte_unused) { return 0; }

static int
eth_dev_start(struct rte_eth_dev *dev)
{
	dev->data->dev_link.link_status = 1;
	return 0;
}

static void
eth_dev_stop(struct rte_eth_dev *dev)
{
	dev->data->dev_link.link_status = 0;
}

static int
eth_rx_queue_setup(struct rte_eth_dev *dev,uint16_t rx_queue_id,
				    uint16_t nb_rx_desc __rte_unused,
				    unsigned int socket_id __rte_unused,
				    const struct rte_eth_rxconf *rx_conf __rte_unused,
				    struct rte_mempool *mb_pool __rte_unused)
{
	struct pmd_internals *internals = dev->data->dev_private;
	dev->data->rx_queues[rx_queue_id] = &internals->rx_ring_queues[rx_queue_id];
	return 0;
}

static int
eth_tx_queue_setup(struct rte_eth_dev *dev, uint16_t tx_queue_id,
				    uint16_t nb_tx_desc __rte_unused,
				    unsigned int socket_id __rte_unused,
				    const struct rte_eth_txconf *tx_conf __rte_unused)
{
	struct pmd_internals *internals = dev->data->dev_private;
	dev->data->tx_queues[tx_queue_id] = &internals->tx_ring_queues[tx_queue_id];
	return 0;
}

static void
eth_dev_info(struct rte_eth_dev *dev,
		struct rte_eth_dev_info *dev_info)
{
	struct pmd_internals *internals = dev->data->dev_private;
	dev_info->driver_name = drivername;
	dev_info->max_mac_addrs = 1;
	dev_info->max_rx_pktlen = (uint32_t)-1;
	dev_info->max_rx_queues = (uint16_t)internals->nb_rx_queues;
	dev_info->max_tx_queues = (uint16_t)internals->nb_tx_queues;
	dev_info->min_rx_bufsize = 0;
	dev_info->pci_dev = NULL;
}

static void
eth_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *igb_stats)
{
	unsigned i;
	unsigned long rx_total = 0, tx_total = 0, tx_err_total = 0;
	const struct pmd_internals *internal = dev->data->dev_private;

	memset(igb_stats, 0, sizeof(*igb_stats));
	for (i = 0; i < RTE_ETHDEV_QUEUE_STAT_CNTRS &&
			i < internal->nb_rx_queues; i++) {
		igb_stats->q_ipackets[i] = internal->rx_ring_queues[i].rx_pkts.cnt;
		rx_total += igb_stats->q_ipackets[i];
	}

	for (i = 0; i < RTE_ETHDEV_QUEUE_STAT_CNTRS &&
			i < internal->nb_tx_queues; i++) {
		igb_stats->q_opackets[i] = internal->tx_ring_queues[i].tx_pkts.cnt;
		igb_stats->q_errors[i] = internal->tx_ring_queues[i].err_pkts.cnt;
		tx_total += igb_stats->q_opackets[i];
		tx_err_total += igb_stats->q_errors[i];
	}

	igb_stats->ipackets = rx_total;
	igb_stats->opackets = tx_total;
	igb_stats->oerrors = tx_err_total;
}

static void
eth_stats_reset(struct rte_eth_dev *dev)
{
	unsigned i;
	struct pmd_internals *internal = dev->data->dev_private;
	for (i = 0; i < internal->nb_rx_queues; i++)
		internal->rx_ring_queues[i].rx_pkts.cnt = 0;
	for (i = 0; i < internal->nb_tx_queues; i++) {
		internal->tx_ring_queues[i].tx_pkts.cnt = 0;
		internal->tx_ring_queues[i].err_pkts.cnt = 0;
	}
}

static void
eth_queue_release(void *q __rte_unused) { ; }
static int
eth_link_update(struct rte_eth_dev *dev __rte_unused,
		int wait_to_complete __rte_unused) { return 0; }

static struct eth_dev_ops ops = {
		.dev_start = eth_dev_start,
		.dev_stop = eth_dev_stop,
		.dev_configure = eth_dev_configure,
		.dev_infos_get = eth_dev_info,
		.rx_queue_setup = eth_rx_queue_setup,
		.tx_queue_setup = eth_tx_queue_setup,
		.rx_queue_release = eth_queue_release,
		.tx_queue_release = eth_queue_release,
		.link_update = eth_link_update,
		.stats_get = eth_stats_get,
		.stats_reset = eth_stats_reset,
};

int
rte_eth_from_rings(const char *name, struct rte_ring *const rx_queues[],
		const unsigned nb_rx_queues,
		struct rte_ring *const tx_queues[],
		const unsigned nb_tx_queues,
		const unsigned numa_node)
{
	struct rte_eth_dev_data *data = NULL;
	struct rte_pci_device *pci_dev = NULL;
	struct pmd_internals *internals = NULL;
	struct rte_eth_dev *eth_dev = NULL;
	unsigned i;

	/* do some parameter checking */
	if (rx_queues == NULL && nb_rx_queues > 0)
		goto error;
	if (tx_queues == NULL && nb_tx_queues > 0)
		goto error;

	RTE_LOG(INFO, PMD, "Creating rings-backed ethdev on numa socket %u\n",
			numa_node);

	/* now do all data allocation - for eth_dev structure, dummy pci driver
	 * and internal (private) data
	 */
	data = rte_zmalloc_socket(name, sizeof(*data), 0, numa_node);
	if (data == NULL)
		goto error;

	pci_dev = rte_zmalloc_socket(name, sizeof(*pci_dev), 0, numa_node);
	if (pci_dev == NULL)
		goto error;

	internals = rte_zmalloc_socket(name, sizeof(*internals), 0, numa_node);
	if (internals == NULL)
		goto error;

	/* reserve an ethdev entry */
	eth_dev = rte_eth_dev_allocate(name);
	if (eth_dev == NULL)
		goto error;

	/* now put it all together
	 * - store queue data in internals,
	 * - store numa_node info in pci_driver
	 * - point eth_dev_data to internals and pci_driver
	 * - and point eth_dev structure to new eth_dev_data structure
	 */
	/* NOTE: we'll replace the data element, of originally allocated eth_dev
	 * so the rings are local per-process */

	internals->nb_rx_queues = nb_rx_queues;
	internals->nb_tx_queues = nb_tx_queues;
	for (i = 0; i < nb_rx_queues; i++) {
		internals->rx_ring_queues[i].rng = rx_queues[i];
	}
	for (i = 0; i < nb_tx_queues; i++) {
		internals->tx_ring_queues[i].rng = tx_queues[i];
	}

	pci_dev->numa_node = numa_node;

	data->dev_private = internals;
	data->port_id = eth_dev->data->port_id;
	data->nb_rx_queues = (uint16_t)nb_rx_queues;
	data->nb_tx_queues = (uint16_t)nb_tx_queues;
	data->dev_link = pmd_link;
	data->mac_addrs = &eth_addr;

	eth_dev ->data = data;
	eth_dev ->dev_ops = &ops;
	eth_dev ->pci_dev = pci_dev;

	/* finally assign rx and tx ops */
	eth_dev->rx_pkt_burst = eth_ring_rx;
	eth_dev->tx_pkt_burst = eth_ring_tx;

	return 0;

error:
	if (data)
		rte_free(data);
	if (pci_dev)
		rte_free(pci_dev);
	if (internals)
		rte_free(internals);
	return -1;
}

enum dev_action{
	DEV_CREATE,
	DEV_ATTACH
};

static int
eth_dev_ring_create(const char *name, const unsigned numa_node,
		enum dev_action action)
{
	/* rx and tx are so-called from point of view of first port.
	 * They are inverted from the point of view of second port
	 */
	struct rte_ring *rxtx[RTE_PMD_RING_MAX_RX_RINGS];
	unsigned i;
	char rng_name[RTE_RING_NAMESIZE];
	unsigned num_rings = RTE_MIN(RTE_PMD_RING_MAX_RX_RINGS,
			RTE_PMD_RING_MAX_TX_RINGS);

	for (i = 0; i < num_rings; i++) {
		snprintf(rng_name, sizeof(rng_name), "ETH_RXTX%u_%s", i, name);
		rxtx[i] = (action == DEV_CREATE) ?
				rte_ring_create(rng_name, 1024, numa_node,
						RING_F_SP_ENQ|RING_F_SC_DEQ) :
				rte_ring_lookup(rng_name);
		if (rxtx[i] == NULL)
			return -1;
	}

	if (rte_eth_from_rings(name, rxtx, num_rings, rxtx, num_rings, numa_node))
		return -1;

	return 0;
}

static int
eth_dev_ring_pair_create(const char *name, const unsigned numa_node,
		enum dev_action action)
{
	/* rx and tx are so-called from point of view of first port.
	 * They are inverted from the point of view of second port
	 */
	struct rte_ring *rx[RTE_PMD_RING_MAX_RX_RINGS];
	struct rte_ring *tx[RTE_PMD_RING_MAX_TX_RINGS];
	unsigned i;
	char rx_rng_name[RTE_RING_NAMESIZE];
	char tx_rng_name[RTE_RING_NAMESIZE];
	unsigned num_rings = RTE_MIN(RTE_PMD_RING_MAX_RX_RINGS,
			RTE_PMD_RING_MAX_TX_RINGS);

	for (i = 0; i < num_rings; i++) {
		snprintf(rx_rng_name, sizeof(rx_rng_name), "ETH_RX%u_%s", i, name);
		rx[i] = (action == DEV_CREATE) ?
				rte_ring_create(rx_rng_name, 1024, numa_node,
						RING_F_SP_ENQ|RING_F_SC_DEQ) :
				rte_ring_lookup(rx_rng_name);
		if (rx[i] == NULL)
			return -1;
		snprintf(tx_rng_name, sizeof(tx_rng_name), "ETH_TX%u_%s", i, name);
		tx[i] = (action == DEV_CREATE) ?
				rte_ring_create(tx_rng_name, 1024, numa_node,
						RING_F_SP_ENQ|RING_F_SC_DEQ):
				rte_ring_lookup(tx_rng_name);
		if (tx[i] == NULL)
			return -1;
	}

	if (rte_eth_from_rings(rx_rng_name, rx, num_rings, tx, num_rings,
			numa_node) || rte_eth_from_rings(tx_rng_name, tx, num_rings, rx,
					num_rings, numa_node))
		return -1;

	return 0;
}

int
rte_eth_ring_pair_create(const char *name, const unsigned numa_node)
{
	RTE_LOG(WARNING, PMD, "rte_eth_ring_pair_create is deprecated\n");
	return eth_dev_ring_pair_create(name, numa_node, DEV_CREATE);
}

int
rte_eth_ring_pair_attach(const char *name, const unsigned numa_node)
{
	RTE_LOG(WARNING, PMD, "rte_eth_ring_pair_attach is deprecated\n");
	return eth_dev_ring_pair_create(name, numa_node, DEV_ATTACH);
}

struct node_action_pair {
	char name[PATH_MAX];
	unsigned node;
	enum dev_action action;
};

struct node_action_list {
	unsigned total;
	unsigned count;
	struct node_action_pair *list;
};

static int parse_kvlist (const char *key __rte_unused, const char *value, void *data)
{
	struct node_action_list *info = data;
	int ret;
	char *name;
	char *action;
	char *node;
	char *end;

	name = strdup(value);

	ret = -EINVAL;

	if (!name) {
		RTE_LOG(WARNING, PMD, "command line paramter is empty for ring pmd!\n");
		goto out;
	}

	node = strchr(name, ':');
	if (!node) {
		RTE_LOG(WARNING, PMD, "could not parse node value from %s", name);
		goto out;
	}

	*node = '\0';
	node++;

	action = strchr(node, ':');
	if (!action) {
		RTE_LOG(WARNING, PMD, "could not action value from %s", node);
		goto out;
	}

	*action = '\0';
	action++;

	/*
	 * Need to do some sanity checking here
	 */

	if (strcmp(action, ETH_RING_ACTION_ATTACH) == 0)
		info->list[info->count].action = DEV_ATTACH;
	else if (strcmp(action, ETH_RING_ACTION_CREATE) == 0)
		info->list[info->count].action = DEV_CREATE;
	else
		goto out;

	errno = 0;
	info->list[info->count].node = strtol(node, &end, 10);

	if ((errno != 0) || (*end != '\0')) {
		RTE_LOG(WARNING, PMD, "node value %s is unparseable as a number\n", node);
		goto out;
	}

	snprintf(info->list[info->count].name, sizeof(info->list[info->count].name), "%s", name);

	info->count++;

	ret = 0;
out:
	free(name);
	return ret;
}

int
rte_pmd_ring_devinit(const char *name, const char *params)
{
	struct rte_kvargs *kvlist;
	int ret = 0;
	struct node_action_list *info = NULL;

	RTE_LOG(INFO, PMD, "Initializing pmd_ring for %s\n", name);

	if (params == NULL || params[0] == '\0')
		eth_dev_ring_create(name, rte_socket_id(), DEV_CREATE);
	else {
		kvlist = rte_kvargs_parse(params, valid_arguments);

		if (!kvlist) {
			RTE_LOG(INFO, PMD, "Ignoring unsupported parameters when creating"
					" rings-backed ethernet device\n");
			eth_dev_ring_create(name, rte_socket_id(), DEV_CREATE);
			return 0;
		} else {
			ret = rte_kvargs_count(kvlist, ETH_RING_NUMA_NODE_ACTION_ARG);
			info = rte_zmalloc("struct node_action_list", sizeof(struct node_action_list) +
					   (sizeof(struct node_action_pair) * ret), 0);
			if (!info)
				goto out;

			info->total = ret;
			info->list = (struct node_action_pair*)(info + 1);

			ret = rte_kvargs_process(kvlist, ETH_RING_NUMA_NODE_ACTION_ARG,
						 parse_kvlist, info);

			if (ret < 0)
				goto out_free;

			for (info->count = 0; info->count < info->total; info->count++) {
				eth_dev_ring_create(name, info->list[info->count].node,
						    info->list[info->count].action);
			}
		}
	}

out_free:
	rte_free(info);
out:
	return ret;
}

static struct rte_driver pmd_ring_drv = {
	.name = "eth_ring",
	.type = PMD_VDEV,
	.init = rte_pmd_ring_devinit,
};

PMD_REGISTER_DRIVER(pmd_ring_drv);


text:
/**
 * @author  e.e d3si9n
 */

import scalaxb._
import anycontent._

object AnyUsage {
  def main(args: Array[String]): Unit = {
    allTests
  }

  def allTests = {
    testAny
    testAny2
    testAny3
    true
  }

  def testAny {
    val subject = <foo xmlns="http://www.example.com/any"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <int xsi:type="xs:int">1</int>
          <byte xsi:type="xs:byte">1</byte>
          <short xsi:type="xs:short">1</short>
          <long xsi:type="xs:long">1</long>
          <float xsi:type="xs:float">1.0</float>
          <double xsi:type="xs:double">1.0</double>
          <integer xsi:type="xs:integer">1</integer>
          <nonPositiveInteger xsi:type="xs:nonPositiveInteger">-1</nonPositiveInteger>
          <negativeInteger xsi:type="xs:negativeInteger">-1</negativeInteger>
          <nonNegativeInteger xsi:type="xs:nonNegativeInteger">1</nonNegativeInteger>
          <positiveInteger xsi:type="xs:positiveInteger">1</positiveInteger>
          <unsignedLong xsi:type="xs:unsignedLong">1</unsignedLong>
          <unsignedInt xsi:type="xs:unsignedInt">1</unsignedInt>
          <unsignedShort xsi:type="xs:unsignedShort">1</unsignedShort>
          <unsignedByte xsi:type="xs:unsignedByte">1</unsignedByte>
          <decimal xsi:type="xs:decimal">1</decimal>
        </foo>
    val obj = fromXML[Element1](subject)
    obj match {
      case Element1(
          DataRecord(Some("http://www.example.com/any"), Some("int"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("byte"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("short"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("long"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("float"), 1.0F),
          DataRecord(Some("http://www.example.com/any"), Some("double"), 1.0),
          DataRecord(Some("http://www.example.com/any"), Some("integer"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("nonPositiveInteger"), -1),
          DataRecord(Some("http://www.example.com/any"), Some("negativeInteger"), -1),
          DataRecord(Some("http://www.example.com/any"), Some("nonNegativeInteger"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("positiveInteger"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("unsignedLong"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("unsignedInt"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("unsignedShort"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("unsignedByte"), 1),
          DataRecord(Some("http://www.example.com/any"), Some("decimal"), 1)
        ) =>
      case _ => sys.error("match failed: " + obj.toString)
    }
    val document = toXML[Element1](obj, "foo", defaultScope)
    println(document)
  }

  def testAny2 {
    val subject = <foo xmlns="http://www.example.com/any"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <boolean xsi:type="xs:boolean">false</boolean>
          <string xsi:type="xs:string">foo</string>
          <normalizedString xsi:type="xs:normalizedString">foo</normalizedString>
          <token xsi:type="xs:token">foo</token>
          <language xsi:type="xs:language">en-US</language>
          <Name xsi:type="xs:Name">foo</Name>
          <NCName xsi:type="xs:NCName">foo</NCName>
          <NMTOKEN xsi:type="xs:NMTOKEN">foo</NMTOKEN>
          <NMTOKENS xsi:type="xs:NMTOKENS">foo</NMTOKENS>
          <ID xsi:type="xs:ID">foo</ID>
          <IDREF xsi:type="xs:IDREF">foo</IDREF>
          <IDREFS xsi:type="xs:IDREFS">foo</IDREFS>
          <ENTITY xsi:type="xs:ENTITY">foo</ENTITY>
          <ENTITIES xsi:type="xs:ENTITIES">foo</ENTITIES>
        </foo>
    val obj = fromXML[Element1](subject)
    obj match {
      case Element1(
          DataRecord(Some("http://www.example.com/any"), Some("boolean"), false),
          DataRecord(Some("http://www.example.com/any"), Some("string"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("normalizedString"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("token"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("language"), "en-US"),
          DataRecord(Some("http://www.example.com/any"), Some("Name"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("NCName"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("NMTOKEN"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("NMTOKENS"), Seq("foo")),
          DataRecord(Some("http://www.example.com/any"), Some("ID"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("IDREF"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("IDREFS"), Seq("foo")),
          DataRecord(Some("http://www.example.com/any"), Some("ENTITY"), "foo"),
          DataRecord(Some("http://www.example.com/any"), Some("ENTITIES"), Seq("foo"))
        ) =>
      case _ => sys.error("match failed: " + obj.toString)
    }
    val document = toXML[Element1](obj, "foo", defaultScope)
    println(document)
  }

  def testAny3 {
    val ExampleCom = new java.net.URI("http://www.example.com/")
    val ExampleQName = javax.xml.namespace.QName.valueOf("{http://www.example.com/any}foo")
    lazy val typeFactory = javax.xml.datatype.DatatypeFactory.newInstance()
    val ExampleDuration = typeFactory.newDuration("P1D")

    val subject = <foo xmlns="http://www.example.com/any"
        xmlns:any="http://www.example.com/any"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <hexBinary xsi:type="xs:hexBinary">0F</hexBinary>
          <base64Binary xsi:type="xs:base64Binary">bQ==</base64Binary>
          <anyURI xsi:type="xs:anyURI">http://www.example.com/</anyURI>
          <QName xsi:type="xs:QName">any:foo</QName>
          <NOTATION xsi:type="xs:NOTATION">{{http://www.example.com/any}}foo</NOTATION>
          <duration xsi:type="xs:duration">P1D</duration>
          <dateTime xsi:type="xs:dateTime">2002-10-10T12:00:00Z</dateTime>
          <time xsi:type="xs:time">12:00:00Z</time>
          <gYearMonth xsi:type="xs:gYearMonth">2002-10</gYearMonth>
          <gYear xsi:type="xs:gYear">2002</gYear>
          <gMonthDay xsi:type="xs:gMonthDay">--10-10</gMonthDay>
          <gDay xsi:type="xs:gDay">---10</gDay>
          <gMonth xsi:type="xs:gMonth">--10</gMonth>
        </foo>

    val obj = fromXML[Element1](subject)
    obj match {
      case Element1(
          DataRecord(Some("http://www.example.com/any"), Some("hexBinary"), HexBinary(15)),
          DataRecord(Some("http://www.example.com/any"), Some("base64Binary"), Base64Binary('m')),
          DataRecord(Some("http://www.example.com/any"), Some("anyURI"), ExampleCom),
          DataRecord(Some("http://www.example.com/any"), Some("QName"), ExampleQName),
          DataRecord(Some("http://www.example.com/any"), Some("NOTATION"), ExampleQName),
          DataRecord(Some("http://www.example.com/any"), Some("duration"), ExampleDuration),
          DataRecord(Some("http://www.example.com/any"), Some("dateTime"), XMLCalendar("2002-10-10T12:00:00Z")),
          DataRecord(Some("http://www.example.com/any"), Some("time"), XMLCalendar("12:00:00Z")),
          DataRecord(Some("http://www.example.com/any"), Some("gYearMonth"), XMLCalendar("2002-10")),
          DataRecord(Some("http://www.example.com/any"), Some("gYear"), XMLCalendar("2002")),
          DataRecord(Some("http://www.example.com/any"), Some("gMonthDay"), XMLCalendar("--10-10")),
          DataRecord(Some("http://www.example.com/any"), Some("gDay"), XMLCalendar("---10")),
          DataRecord(Some("http://www.example.com/any"), Some("gMonth"), XMLCalendar("--10"))
        ) =>
      case _ => sys.error("match failed: " + obj.toString)
    }
    val document = toXML[Element1](obj, "foo", defaultScope)
    println(document)
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @namespace
 */
namespace RestPHP\Request\Header;

/**
 * DateTest - Tests the Date header behaves as documented in RFC 2616
 * Section 14
 *
 * @category   RestPHP
 * @package    RestPHP
 * @subpackage Test
 * @author     Joshua Johnston <johnston.joshua@gmail.com>
 * @copyright  2011 RestPHP Framework
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @link       http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html RFC 2616 Sec 14
 */
class DateTest extends \PHPUnit_Framework_TestCase
{
    /**
     *
     * @var \RestPHP\Request\Header\Date
     */
    protected $header;

    public function setUp()
    {
        $this->header = new \RestPHP\Request\Header\Date();
    }

    public function testParse()
    {
        $this->markTestIncomplete('No tests implemented');
    }
}


text:
var http = require('http');
var connect = require('connect');
var Yajsml = require('yajsml');
var urlutil = require('url');

var resourceHandler = function (req, res, next) {
  var resources = resourceHandler.resources || {};
  var url = urlutil.parse(req.url);
  var resource = resources[url.path];

  req.writeHead(resource.status, resource.header);
  setTimeout(function () {
    req.end(resource.content);
  }, 0);
};

var resourceServer = http.createServer(resourceHandler);
resourceServer.listen(9999); // Unlisten somewhere...
resourceServerURL = 'http://localhost:9999/';

describe('yajsml', function(){
  var app = connect();
  var yajsml = new (Yajsml.Server)({
    rootPath: 'src'
  , rootURL: resourceServerURL + 'src'
  , libraryPath: 'lib'
  , libraryURL: resourceServerURL + 'lib'
  });
  app.use(yajsml);

  describe('simple request', function(){
    resourceHandler.resources = {
      {
        status: 200
      , headers: {'content-type': 'text/plain'}
      , content: 'asdf'
      }
    }

    it('should ', function(){
      app.request()
      .get('/src')
      .end(function (res) {
        res.getHeader('content-type').should.equal('application/javascript');
      });
    })
  });
});


text:
class AddIndexForCommittedAtAndId < ActiveRecord::Migration[4.2]
  def change
    add_index :ci_commits, [:project_id, :committed_at, :id]
  end
end


text:
def super_fizzbuzz(array)
  new_array = []
 array.each do |number|
    new_array << fizzbuzz(number)
  end
  new_array
end

def fizzbuzz(number)
  if number % 15 == 0
    "FizzBuzz"
  elsif number % 5 == 0
    "Buzz"
  elsif number % 3 == 0
    "Fizz"
  else
    number
  end
end

# Reflection

# Introduction to Inheritance

# I worked on this challenge [by myself, with: ].

# Pseudocode GlobalCohort
# Method: initialize
# Input: Name, start date
# Output: a cohort is created
# steps:
# sets date of immersive_start_date to start_date + 7*9
# set graduation_date to start_date + 7*18

# Method: add_student
# input: student
# output:
#Steps: Add student to list students

# Method: remove_student
# input: student
# output:
# Steps: Find Student on list students
# delete from list students

# Method: currently_in_phase
# input: nothing
# output: phase number.
# if

# # Initial Solution

# class GlobalCohort
#     attr_accessor :name
#     attr_accessor :students
#     attr_accessor :p0_start_date
#     attr_accessor :immersive_start_date
#     attr_accessor :graduation_date

# end

# class LocalCohort < GlobalCohort
#   attr_accessor :city

# end

# class Student
#   attr_accessor :name
#   attr_accessor :email
# end

# # Refactored Solution

# # Reflection


text:
import daDK from '../../date-picker/locale/da_DK';

export default daDK;


text:
update setting set content='1.0.6' where name = 'ionize_version';

INSERT IGNORE INTO resource (id_resource, id_parent, resource, actions, title, description) VALUES (220,NULL,'admin/item','create,edit,delete,add','Static Items','Static Items');
INSERT IGNORE INTO resource (id_resource, id_parent, resource, actions, title, description) VALUES (221,220,'admin/item/definition','edit','Definition','Static Items > Definition');

INSERT IGNORE INTO rule (id_role, resource, actions, permission) VALUES (2,'admin/item','create,edit,delete,add',1);
INSERT IGNORE INTO rule (id_role, resource, actions, permission) VALUES (3,'admin/item','create,edit,delete,add',1);

INSERT IGNORE INTO resource (id_resource, id_parent, resource, actions, title, description) VALUES (222,220,'admin/item/media','link,unlink,edit','Media','Static Items > Media');
INSERT IGNORE INTO rule (id_role, resource, actions, permission) VALUES (2,'admin/item/media','link,unlink,edit',1);
INSERT IGNORE INTO rule (id_role, resource, actions, permission) VALUES (3,'admin/item/media','link,unlink,edit',1);

ALTER TABLE extend_fields add parent varchar(50) NOT NULL default '';
ALTER TABLE extend_field add id_parent int(11) unsigned NULL;
UPDATE extend_field set parent='element', id_parent=id_element_definition where id_element_definition != 0;
ALTER TABLE extend_field add main smallint(1) unsigned NOT NULL DEFAULT 0;

delete from rule where resource='admin/page/media' and actions='';
delete from rule where resource='admin/article/media' and actions='';
ALTER TABLE rule DROP PRIMARY KEY;
ALTER TABLE rule add id_user int(1) unsigned NOT NULL DEFAULT 0;
ALTER TABLE rule ADD PRIMARY KEY(id_role,id_user,resource);

update resource set actions='link,unlink,edit' where resource='admin/page/media';
update resource set actions='link,unlink,edit' where resource='admin/article/media';
update rule set actions='link,unlink,edit' where resource='admin/page/media';
update rule set actions='link,unlink,edit' where resource='admin/article/media';

delete from resource where resource ='admin/page/media/file';
delete from resource where resource ='admin/page/media/music';
delete from resource where resource ='admin/page/media/video';
delete from resource where resource ='admin/page/media/picture';
delete from resource where resource ='admin/article/media/file';
delete from resource where resource ='admin/article/media/music';
delete from resource where resource ='admin/article/media/video';
delete from resource where resource ='admin/article/media/picture';

delete from rule where resource ='admin/page/media/file';
delete from rule where resource ='admin/page/media/music';
delete from rule where resource ='admin/page/media/video';
delete from rule where resource ='admin/page/media/picture';
delete from rule where resource ='admin/article/media/file';
delete from rule where resource ='admin/article/media/music';
delete from rule where resource ='admin/article/media/video';
delete from rule where resource ='admin/article/media/picture';

update extend_field set id_parent = id_element_definition where parent='element';
update extend_fields set id_parent = id_element where id_element != 0;
update extend_fields set parent = 'element' where id_element != 0;
alter table extend_fields drop id_element;
alter table extend_field drop id_element_definition;
alter table extend_field drop parents;
alter table extend_field drop block;
alter table extend_field change type type int(3);
alter table extend_field add copy_in varchar(50) NULL;
alter table extend_field add copy_in_pk varchar(50) NULL;

alter table article_lang change lang lang varchar(8);
alter table article_media change lang_display lang_display varchar(8);
alter table captcha change lang lang varchar(8);
alter table element_definition_lang change lang lang varchar(8);
alter table extend_field_lang change lang lang varchar(8);
alter table extend_fields change lang lang varchar(8);
alter table item_definition_lang change lang lang varchar(8);
alter table item_lang change lang lang varchar(8);
alter table lang change lang lang varchar(8);
alter table media_lang change lang lang varchar(8);
alter table module_setting change lang lang varchar(8);
alter table page_lang change lang lang varchar(8);
alter table page_media change lang_display lang_display varchar(8);
alter table setting change lang lang varchar(8);
alter table url change lang lang varchar(8);


text:
var AudioContext;
var console;
var define;
var global;
var module;
var exports;
var JSON;


text:
package ru.vyarus;

import org.gradle.api.Plugin;
import org.gradle.api.Project;

public class TestPlugin implements Plugin<Project> {

    @Override
    public void apply(Project target) {

    }
}


text:
import React, { FC, useEffect, useMemo, useState } from "react";
import { useSigma } from "react-sigma-v2";
import { sortBy, values, keyBy, mapValues } from "lodash";
import { MdGroupWork } from "react-icons/md";
import { AiOutlineCheckCircle, AiOutlineCloseCircle } from "react-icons/ai";

import { Cluster, FiltersState } from "../types";
import Panel from "./Panel";

const ClustersPanel: FC<{
  clusters: Cluster[];
  filters: FiltersState;
  toggleCluster: (cluster: string) => void;
  setClusters: (clusters: Record<string, boolean>) => void;
}> = ({ clusters, filters, toggleCluster, setClusters }) => {
  const sigma = useSigma();
  const graph = sigma.getGraph();

  const nodesPerCluster = useMemo(() => {
    const index: Record<string, number> = {};
    graph.forEachNode((_, { cluster }) => (index[cluster] = (index[cluster] || 0) + 1));
    return index;
  }, []);

  const maxNodesPerCluster = useMemo(() => Math.max(...values(nodesPerCluster)), [nodesPerCluster]);
  const visibleClustersCount = useMemo(() => Object.keys(filters.clusters).length, [filters]);

  const [visibleNodesPerCluster, setVisibleNodesPerCluster] = useState<Record<string, number>>(nodesPerCluster);
  useEffect(() => {
    // To ensure the graphology instance has up to data "hidden" values for
    // nodes, we wait for next frame before reindexing. This won't matter in the
    // UX, because of the visible nodes bar width transition.
    requestAnimationFrame(() => {
      const index: Record<string, number> = {};
      graph.forEachNode((_, { cluster, hidden }) => !hidden && (index[cluster] = (index[cluster] || 0) + 1));
      setVisibleNodesPerCluster(index);
    });
  }, [filters]);

  const sortedClusters = useMemo(
    () => sortBy(clusters, (cluster) => -nodesPerCluster[cluster.key]),
    [clusters, nodesPerCluster],
  );

  return (
    <Panel
      title={
        <>
          <MdGroupWork className="text-muted" /> Clusters
          {visibleClustersCount < clusters.length ? (

              {" "}
              ({visibleClustersCount} / {clusters.length})

          ) : (
            ""
          )}
        </>
      }
    >

        Click a cluster to show/hide related pages from the network.

        <button className="btn" onClick={() => setClusters(mapValues(keyBy(clusters, "key"), () => true))}>
          <AiOutlineCheckCircle /> Check all
        </button>{" "}
        <button className="btn" onClick={() => setClusters({})}>
          <AiOutlineCloseCircle /> Uncheck all
        </button>

        {sortedClusters.map((cluster) => {
          const nodesCount = nodesPerCluster[cluster.key];
          const visibleNodesCount = visibleNodesPerCluster[cluster.key] || 0;
          return (

 1 ? "s" : ""}${
                visibleNodesCount !== nodesCount ? ` (only ${visibleNodesCount} visible)` : ""
              }`}
            >
              <input
                type="checkbox"
                checked={filters.clusters[cluster.key] || false}
                onChange={() => toggleCluster(cluster.key)}
                id={`cluster-${cluster.key}`}
              />
              <label htmlFor={`cluster-${cluster.key}`}>
                {" "}

                  {cluster.clusterLabel}

          );
        })}

    </Panel>
  );
};

export default ClustersPanel;


text:
import React from 'react';
import { Meteor } from 'meteor/meteor';

const logout = () => {
  let content;
  if (Meteor.user()) {
    content = (

            Log out

    );
  }
  return content;
};

const Header = ({ title }) => (

        <button
          type="button"
          className="navbar-toggle"
          data-toggle="collapse"
          data-target="#navigation-example-2"
        >
          Toggle navigation

        </button>
        {title}

      {logout()}

);

Header.propTypes = {
  title: React.PropTypes.string.isRequired,
};

export default Header;


text:
namespace AWSV4 {
    const std::string ENDL{"\n"};
    const std::string POST{"POST"};
    const std::string STRING_TO_SIGN_ALGO{"AWS4-HMAC-SHA256"};
    const std::string AWS4{"AWS4"};
    const std::string AWS4_REQUEST{"aws4_request"};

    void sha256(const std::string str, unsigned char outputBuffer[SHA256_DIGEST_LENGTH]) noexcept;

    const std::string sha256_base16(const std::string) noexcept;

    const std::string canonicalize_uri(const Poco::URI& uri) noexcept;

    const std::string canonicalize_query(const Poco::URI& uri) noexcept;

    const std::map<std::string,std::string> canonicalize_headers(const std::vector<std::string>& headers) noexcept;

    const std::string map_headers_string(const std::map<std::string,std::string>& header_key2val) noexcept;

    const std::string map_signed_headers(const std::map<std::string,std::string>& header_key2val) noexcept;

    const std::string canonicalize_request(const std::string& http_request_method,
                                           const std::string& canonical_uri,
                                           const std::string& canonical_query_string,
                                           const std::string& canonical_headers,
                                           const std::string& signed_headers,
                                           const std::string& payload) noexcept;

    const std::string string_to_sign(const std::string& algorithm,
                                     const std::time_t& request_date,
                                     const std::string& credential_scope,
                                     const std::string& hashed_canonical_request) noexcept;

    const std::string ISO8601_date(const std::time_t& t) noexcept;

    const std::string utc_yyyymmdd(const std::time_t& t) noexcept;

    const std::string credential_scope(const std::time_t& t,
                                       const std::string region,
                                       const std::string service) noexcept;

    const std::string calculate_signature(const std::time_t& request_date,
                                          const std::string secret,
                                          const std::string region,
                                          const std::string service,
                                          const std::string string_to_sign) noexcept;

}

#endif


text:
package org.elasticsearch.action.bulk;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.TransportBulkActionTookTests.Resolver;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.AutoCreateIndex;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.transport.CapturingTransport;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import org.junit.After;
import org.junit.Before;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;

public class TransportBulkActionTests extends ESTestCase {

    /** Services needed by bulk action */
    private TransportService transportService;
    private ClusterService clusterService;
    private ThreadPool threadPool;

    private TestTransportBulkAction bulkAction;

    class TestTransportBulkAction extends TransportBulkAction {

        boolean indexCreated = false; // set when the "real" index is created

        TestTransportBulkAction() {
            super(Settings.EMPTY, TransportBulkActionTests.this.threadPool, transportService, clusterService, null, null,
                    null, new ActionFilters(Collections.emptySet()), new Resolver(Settings.EMPTY),
                    new AutoCreateIndex(Settings.EMPTY, clusterService.getClusterSettings(), new Resolver(Settings.EMPTY)));
        }

        @Override
        protected boolean needToCheck() {
            return true;
        }

        @Override
        void createIndex(String index, TimeValue timeout, ActionListener<CreateIndexResponse> listener) {
            indexCreated = true;
            listener.onResponse(null);
        }
    }

    @Before
    public void setUp() throws Exception {
        super.setUp();
        threadPool = new TestThreadPool("TransportBulkActionTookTests");
        clusterService = createClusterService(threadPool);
        CapturingTransport capturingTransport = new CapturingTransport();
        transportService = capturingTransport.createCapturingTransportService(clusterService.getSettings(), threadPool,
            TransportService.NOOP_TRANSPORT_INTERCEPTOR,
            boundAddress -> clusterService.localNode(), null, Collections.emptySet());
        transportService.start();
        transportService.acceptIncomingRequests();
        bulkAction = new TestTransportBulkAction();
    }

    @After
    public void tearDown() throws Exception {
        ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
        threadPool = null;
        clusterService.close();
        super.tearDown();
    }

    public void testDeleteNonExistingDocDoesNotCreateIndex() throws Exception {
        BulkRequest bulkRequest = new BulkRequest().add(new DeleteRequest("index", "type", "id"));

        bulkAction.execute(null, bulkRequest, ActionListener.wrap(response -> {
            assertFalse(bulkAction.indexCreated);
            BulkItemResponse[] bulkResponses = ((BulkResponse) response).getItems();
            assertEquals(bulkResponses.length, 1);
            assertTrue(bulkResponses[0].isFailed());
            assertTrue(bulkResponses[0].getFailure().getCause() instanceof IndexNotFoundException);
            assertEquals("index", bulkResponses[0].getFailure().getIndex());
        }, exception -> {
            throw new AssertionError(exception);
        }));
    }

    public void testDeleteNonExistingDocExternalVersionCreatesIndex() throws Exception {
        BulkRequest bulkRequest = new BulkRequest()
                .add(new DeleteRequest("index", "type", "id").versionType(VersionType.EXTERNAL).version(0));

        bulkAction.execute(null, bulkRequest, ActionListener.wrap(response -> {
            assertTrue(bulkAction.indexCreated);
        }, exception -> {
            throw new AssertionError(exception);
        }));
    }

    public void testDeleteNonExistingDocExternalGteVersionCreatesIndex() throws Exception {
        BulkRequest bulkRequest = new BulkRequest()
                .add(new DeleteRequest("index2", "type", "id").versionType(VersionType.EXTERNAL_GTE).version(0));

        bulkAction.execute(null, bulkRequest, ActionListener.wrap(response -> {
            assertTrue(bulkAction.indexCreated);
        }, exception -> {
            throw new AssertionError(exception);
        }));
    }
}


text:
using System.Collections.Generic;
using MicroNetCore.AspNetCore.Paging;
using MicroNetCore.Rest.Abstractions;

namespace MicroNetCore.Rest.MediaTypes.Hypermedia.Services
{
    public interface IHypermediaTitleGenerator
    {
        string Get(IResponseViewModel model);
        string Get(IEnumerable<IResponseViewModel> models);
        string Get(IEnumerablePage<IResponseViewModel> page);
    }
}


text:
describe SampleModel do
  it "includes Active Record Base" do
    SampleModel.should be < ActiveRecord::Base
  end

  context "select only the main document when find" do
    before do
      SampleModel.create indexed_field: "test"
    end
    it "should do the regular find with the restricted fields" do
      pending
      expect( SampleModel ).to receive( :regular_find ).with(:all, { select: [ :object, :created_at, :updated_at ] } )

      SampleModel.find(:all)
    end
    it "should do the regular find with the restricted fields" do
      query = SampleModel.where( indexed_field: "test" ).to_sql
      expect( query ).to include("object")
      expect( query ).to include("created_at")
      expect( query ).to include("updated_at")
    end
  end

  context "with an arbitrary set of attributes" do
    let(:arbitrary_attributes){ { arbitrary_attribute: 'test' } }
    let(:sample){ SampleModel.new arbitrary_attributes }

    it "should allow access the previously set attributes thru direct methods" do
      expect( sample.arbitrary_attribute ).to eq 'test'
    end

    it "should allow assignments thru direct methods" do
      sample.arbitrary_attribute = 'reassign'
      expect( sample.arbitrary_attribute ).to eq 'reassign'
    end

    it "can be saved" do
      sample.save
    end
  end

  context "with an arbitrary hash" do
    let(:hash){ { "level1" => {"level2" => 'level3'} } }
    let(:sample){ SampleModel.new hash }

    it "returns the previously stored hash when requested" do
      expect( sample.level1 ).to eq :level2 => 'level3'
    end
    it "can be saved" do
      sample.save
    end
  end

  context "with a hash with multiple items" do
    let(:hash){{ one: {two: :three}, single: :test }}
    let(:sample) { SampleModel.new hash }

    it "finds all the hash keys" do
      expect( sample.deep_keys ).to match_array ["one_two", "single"]
    end
  end

  context "with an arbitrary inner attribute" do
    let(:hash) { { "inner" => { "attribute" => "value" }}}
    let(:sample){ SampleModel.new hash }

    it "recognizes inner_attribute as an indexed field" do
      expect( sample.is_indexed?(:inner_attribute) ).to eq true
    end

    it "should write the value to an attribute" do
      expect( sample.attributes["inner_attribute"] ).to eq "value"
    end

    it "would have the inner attribute accessible" do
      expect( sample.inner_attribute ).to eq "value"
    end

    it "changes the inner attribute indexed field when changing the attribute" do
      sample.inner["attribute"] = "testing"
      expect( sample.inner_attribute.should ).to eq "testing"
    end

    it "changes an inner attribute when changing the property" do
      sample.inner.attribute = "new"
      expect( sample.inner["attribute"] ).to eq "new"
    end

  end

  it "can save the indexed fields on their respective field" do
    s1 = SampleModel.create level1: { level2: 'level3' }, indexed_field: 'test'
    expect( s1.indexed_field ).to eq 'test'
  end

  it "updates the document when updating an index field" do
    s1 = SampleModel.create level1: { level2: 'level3' }, indexed_field: 'test'
    s1.indexed_field = 'update'
    s1.as_json["indexed_field"].should == "update"
  end

  it "can be found by indexed_field" do
    s1 = SampleModel.create level1: { level2: 'level3' }, indexed_field: 'test'
    s2 = SampleModel.find_by_indexed_field 'test'
    expect( s2 ).to eq( s1 )
  end

  it "return any key even if it was passed as string" do
    s1 = SampleModel.create "level1" => "level2"
    s1.level1.should == "level2"
  end

  it "save integers as integers" do
    s1 = SampleModel.create "number" => 1
    s1.number.should be_an Integer
  end

  it "honors indexed field type integer" do
    s1 = SampleModel.create "indexed_integer" => "1"
    s1.indexed_integer.should be_an Integer
  end

  it "honors indexed field type time" do
    s1 = SampleModel.create "indexed_date" => DateTime.new
    s1.indexed_date.should be_an DateTime
  end

  it "forces indexed values to their types" do
    s1 = SampleModel.create "indexed_date" => "2009-04-12T20:44:55"
    s1.attributes["indexed_date"].should be_a_kind_of ActiveSupport::TimeWithZone
  end

  it "recognizes the specified timezones" do
    date = "2009-04-12T20:44:55+0400"
    s1 = SampleModel.create "indexed_date" => date
    s1.reload
    expect( DateTime.parse( s1.indexed_date ) ).to eq(DateTime.parse(date))
  end

  it "reports that indexed fields have been changed" do
    s1 = SampleModel.create "indexed_field" => "test"
    s1.indexed_field = "change"
    expect( s1.indexed_field_changed? ).to be true
  end

  it "includes attributes in the json" do
    s1 = SampleModel.create "test" => "test"
    s1.as_json.should have_key "created_at"
  end

  it "respond to column function" do
    s1 = SampleModel.create "created_at" => 3.days.ago

    expect( s1 ).to respond_to( :created_at )
  end

  it "the schema field should come from the indexed info" do
    s1 = SampleModel.create "created_at" => 3.days.ago
    s1.update_column( "created_at", 1.day.ago )

    expect( s1.created_at ).to eq( s1.read_attribute( :created_at ) )
  end

  it "the schema field should come from the indexed info and reflect in the json" do
    s1 = SampleModel.create "created_at" => 3.days.ago
    s1.update_column( "created_at", 1.day.ago )

    expect( s1.as_json["created_at"] ).to eq( s1.read_attribute( :created_at ) )
  end

  it "doesn't include the document field" do
    s1 = SampleModel.create "test" => "test"
    s1.as_json.should_not have_key "object"
  end

  it "includes methods if passed thru options" do
    s1 = SampleModel.create "test" => "test"
    s1.as_json( methods: [ :json_method ] ).should have_key :json_method
  end

end

describe ActiveRecord::Base do
  it { ActiveRecord::Base.should respond_to :document_field }

  # describe '#document_field' do
  #   it "should show an error if the field doesn't exist" do
  #     expect {
  #       SampleModel.class_eval { document_field :object }
  #     }.to_not raise_error
  #   end
  # end
end


text:
require 'factory_girl'

FactoryGirl.define do
  factory :user do
    name "Chuck Norris"
    points  { (rand * 100).to_i }
  end
end


text:
<?php

function verify_oauth_1a($origin = 'https://api.twitter.com')
{
    $oauth_params = array_map('urldecode', parse_ini_string(str_replace(', ', "\n", substr(
        filter_input(INPUT_SERVER, 'HTTP_AUTHORIZATION'),
        strlen('OAuth ')
    ))));

    if (!isset($oauth_params['oauth_signature'])) {
        header('Content-Type: application/json', true, 400);
        exit('{"errors":[{"message":"Bad Authentication data","code":215}]}');
    }

    $actual_signature = $oauth_params['oauth_signature'];
    unset($oauth_params['oauth_signature']);

    if (strpos(filter_input(INPUT_SERVER, 'CONTENT_TYPE'), 'multipart/form-data') !== 0) {
        $additional_params = $_POST + $_GET;
    } else {
        $additional_params = [];
    }

    $base = $oauth_params + $additional_params;
    $key = ['cs', isset($oauth_params['oauth_token']) ? 'ts' : ''];

    uksort($base, 'strnatcmp');
    $expected_signature = base64_encode(hash_hmac(
        'sha1',
        implode('&', array_map('rawurlencode', [
            filter_input(INPUT_SERVER, 'REQUEST_METHOD'),
            $origin . substr(parse_url(filter_input(INPUT_SERVER, 'REQUEST_URI'), PHP_URL_PATH), 0, -strlen('.php')),
            http_build_query($base, '', '&', PHP_QUERY_RFC3986)
        ])),
        implode('&', array_map('rawurlencode', $key)),
        true
    ));

    if ($expected_signature !== $actual_signature) {
        header('Content-Type: application/json', true, 400);
        exit('{"errors":[{"message":"Bad Authentication data","code":215}]}');
    }
}

function verify_oauth_2_bearer()
{
    $token = substr(
        filter_input(INPUT_SERVER, 'HTTP_AUTHORIZATION'),
        strlen('Bearer ')
    );

    if ($token !== 't') {
        header('Content-Type: application/json', true, 400);
        exit('{"errors":[{"message":"Bad Authentication data","code":215}]}');
    }
}

function verify_oauth_2_basic()
{
    $pair = array_map('rawurldecode', explode(':', base64_decode(substr(
        filter_input(INPUT_SERVER, 'HTTP_AUTHORIZATION'),
        strlen('Basic ')
    ))));

    if ($pair[0] !== 'ck' || $pair[1] !== 'cs') {
        header('Content-Type: application/json', true, 400);
        exit('{"errors":[{"message":"Bad Authentication data","code":215}]}');
    }
}


text:
FROM easypi/alpine-arm
MAINTAINER EasyPi Software Foundation

RUN apk add --no-cache bash ca-certificates curl openssh-client rsync
RUN curl -sSL https://github.com/Drillster/drone-rsync/raw/master/upload.sh > /usr/local/bin/upload.sh
RUN chmod +x /usr/local/bin/upload.sh

ENTRYPOINT ["upload.sh"]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;

namespace PensioenSysteem.Application.Werkgever
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}


text:
<?php

namespace tourze\Base\Helper;

use PHPUnit_Framework_TestCase;

/**
 * 测试MIME助手类
 *
 * @package tourze\Base\Helper
 */
class MimeTest extends PHPUnit_Framework_TestCase
{

    /**
     * @return array
     */
    public function dateGetExtensionsFromMime()
    {
        return [
            ['video/3gpp', false, '3gp'],
            ['image/svg+xml', false, 'svg'],
            ['FAKE_MIME', false, ''],
        ];
    }

    /**
     * 检测[Mime::getExtensionsFromMime]
     *
     * @dataProvider dateGetExtensionsFromMime
     * @param string $mime
     * @param bool   $all
     * @param string $expected
     */
    public function testGetExtensionsFromMime($mime, $all, $expected)
    {
        $this->assertEquals($expected, Mime::getExtensionsFromMime($mime, $all));
    }

    /**
     * @return array
     */
    public function dataGetMimeFromExtension()
    {
        return [
            ['vsf', 'application/vnd.vsf'],
            ['zip', 'application/zip'],
            ['ttl', 'text/turtle'],
        ];
    }

    /**
     * 检测[Mime::getMimeFromExtension]
     *
     * @dataProvider dataGetMimeFromExtension
     * @param string $ext
     * @param string $expected
     */
    public function testGetMimeFromExtension($ext, $expected)
    {
        $this->assertEquals($expected, Mime::getMimeFromExtension($ext));
    }
}


text:
using System;
using System.Diagnostics;
using JetBrains.Annotations;

namespace Shouldly
{
    [DebuggerStepThrough]
    [ShouldlyMethods]
    public static partial class ShouldBeStringTestExtensions
    {
        /// <summary>
        /// Perform a case sensitive string comparison
        /// </summary>
        public static void ShouldBe(this string actual, string expected)
        {
            ShouldBe(actual, expected, Case.Sensitive, () => null);
        }

        /// <summary>
        /// Perform a string comparison, specifying the desired case sensitivity
        /// </summary>
        public static void ShouldBe(this string actual, string expected, Case caseSensitivity)
        {
            ShouldBe(actual, expected, caseSensitivity, () => null);
        }

        public static void ShouldBe(this string actual, string expected, Case caseSensitivity, string customMessage)
        {
            ShouldBe(actual, expected, caseSensitivity, () => customMessage);
        }

        public static void ShouldBe(this string actual, string expected, Case caseSensitivity, [InstantHandle] Func<string> customMessage)
        {
            actual.AssertAwesomelyWithCaseSensitivity(
                v => Is.StringEqualWithCaseSensitivity(v, expected, caseSensitivity),
                actual, expected, caseSensitivity, customMessage);
        }
    }
}


text:
{% extends 'new/base.html' %}
{% load staticfiles %}
{% block title %}Alumnos{% endblock %}
{% block breadcumb %}

    Inicio

    Gestión de Alumnos

    Alumnos

{% endblock %}
{% block content %}

      {% if perms.student.change_alumno %}

            <button class="btn btn-lg dropdown-toggle" data-toggle="dropdown">
             Opciones

            </button>

Cambiar división

Insertar arancel

      {% endif %}

        {% if perms.students.add_alumno %}
          <button onclick="window.location.href='{% url 'alumno-jardin-nuevo' %}'" class="btn btn-lg">
              Agregar Nuevo
          </button>
        {% endif %}

		    <form action="{% url 'alumnos-jardin' %}" method="GET">
		        <input type="text" name="terms" class="form-control" placeholder="Buscar"/>

		    </form>

            <input id="select_all" type="checkbox" name="all" value="">

                  Nombre
                  Apellido
                  Teléfono
                  Domicilio
                  Sexo
                  Acciones

              	{% for alumno in object_list %}

                    <input class="alumno_check" id="{{alumno.id}}" type="checkbox" name="alumno" value="">

	                  {{alumno.nombre1}}
	                  {{alumno.apellido}}
	                  {{alumno.telefono}}
	                  {{alumno.domicilio}}
                    {{alumno.get_sexo_display}}

                      {% if perms.student.change_alumno %}

                      {% endif %}
                      {% if perms.student.change_alumno %}

                      {% endif %}

                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Eliminar Alumno

¿Esta seguro que desea eliminar alumno {{alumno}}?

                                    <button data-dismiss="modal" class="btn btn-default" type="button">Cancelar</button>
                                    <button id="{{alumno.id}}" href="/jardin/alumnos/{{alumno.id}}/eliminar/" class="btn btn-danger eliminar" type="submit"> Eliminar</button>

	            {% endfor %}

            {% if is_paginated %}

                        {% if page_obj.has_previous %}
                            Anterior
                        {% endif %}

                            Página {{ page_obj.number }} de {{ page_obj.paginator.num_pages }}.

                        {% if page_obj.has_next %}
                             Siguiente
                        {% endif %}

            {% endif %}

                  <button type="button" class="close" data-dismiss="modal">×Close</button>

Ingresar Monto

                        <input id="monto" type="number" step="0.01" class="form-control" placeholder="Monto">

                        <input id="concepto" type="text" class="form-control" placeholder="Concepto">

                  <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                  <button id="ingresar_arancel" type="button" class="btn btn-primary">Ingresar</button>

                  <button type="button" class="close" data-dismiss="modal">×Close</button>

Seleccione división

                        <select class="form-control" id="select_sala_1">
                          <option>Elija una sala</option>
                          {% for sala in salas %}
                            <option id="{{sala.id}}">{{sala}}</option>
                          {% endfor %}
                        </select>

                        <select class="form-control" id="select_sala_2">
                          <option>Elija una sala</option>
                          {% for sala in salas %}
                            <option id="{{sala.id}}">{{sala}}</option>
                          {% endfor %}
                        </select>

                  <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                  <button id="seleccionar_sala" type="button" class="btn btn-primary">Seleccionar</button>

{% endblock %}
{% block extra_scripts %}

{% endblock %}


text:
<!DOCTYPE html>

		<title>workshop chess</title>

		<link rel="stylesheet" type="text/css" href="./css/chessboard.css">

Waiting for other player...