text:
package net.mikesu.fastdfs.client;

import static org.junit.Assert.*;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;

import net.mikesu.fastdfs.data.GroupInfo;
import net.mikesu.fastdfs.data.Result;
import net.mikesu.fastdfs.data.UploadStorage;

import org.junit.Test;

public class TrackerClientTest {

	@Test
	public void testGetUploadStorageAddr() throws NumberFormatException, UnknownHostException, IOException {
		TrackerClient trackerClient = new TrackerClientImpl("10.125.176.138:22122");
		Result<UploadStorage> result = trackerClient.getUploadStorage();
		assertEquals(0, result.getCode());
		assertEquals("10.125.176.138:23000",result.getData().getAddress());
		trackerClient.close();
	}

	@Test
	public void testGetDownloadStorageAddr() throws IOException {
		TrackerClient trackerClient = new TrackerClientImpl("10.125.176.138:22122");
		Result<String> result = trackerClient.getDownloadStorageAddr("group1","M00/00/00/Cn2wilM00puAa0xSAANVQ4eIxAM143.jpg");
		assertEquals(0, result.getCode());
		assertEquals("10.125.176.138:23000",result.getData());
		trackerClient.close();
	}

	@Test
	public void testGetUpdateStorageAddr() throws IOException {
		TrackerClient trackerClient = new TrackerClientImpl("10.125.176.138:22122");
		Result<String> result = trackerClient.getUpdateStorageAddr("group1","M00/00/00/Cn2wilM00puAa0xSAANVQ4eIxAM143.jpg");
		assertEquals(0, result.getCode());
		assertEquals("10.125.176.138:23000",result.getData());
		trackerClient.close();
	}

	@Test
	public void testGetGroupInfos() throws NumberFormatException, UnknownHostException, IOException{
		TrackerClient trackerClient = new TrackerClientImpl("10.125.176.138:22122");
		Result<List<GroupInfo>> groupInfos = trackerClient.getGroupInfos();
		assertNotNull(groupInfos);
		trackerClient.close();
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

'use strict';

var Message = require('azure-iot-common').Message;

/**
 * @class module:azure-iot-common.Http
 * @classdesc Basic HTTP request/response functionality used by higher-level IoT Hub libraries.
 */
function Http() {
  this._https = require('https');
}

/*Codes_SRS_NODE_HTTP_05_001: [buildRequest shall accept the following arguments:
method - an HTTP verb, e.g., 'GET', 'POST', 'DELETE'
path - the path to the resource, not including the hostname
httpHeaders - an object whose properties represent the names and values of HTTP headers to include in the request
host - the fully-qualified DNS hostname of the IoT hub
done - a callback that will be invoked when a completed response is returned from the server]*/
Http.prototype.buildRequest = function (method, path, httpHeaders, host, done) {
  var options = {
    host: host,
    path: path,
    method: method,
    headers: httpHeaders
  };

  var request = this._https.request(options, function onResponse(response) {
    var responseBody = '';
    response.on('data', function onResponseData(chunk) {
      responseBody += chunk;
    });
    response.on('end', function onResponseEnd() {
      /*Codes_SRS_NODE_HTTP_05_005: [When an HTTP response is received, the callback function indicated by the done argument shall be invoked with the following arguments:
      err - the standard JavaScript Error object if status code >= 300, otherwise null
      body - the body of the HTTP response as a string
      response - the Node.js http.ServerResponse object returned by the transport]*/
      var err = (response.statusCode >= 300) ?
        new Error(response.statusMessage) :
        null;
      done(err, responseBody, response);
    });
  });

  /*Codes_SRS_NODE_HTTP_05_003: [If buildRequest encounters an error before it can send the request, it shall invoke the done callback function and pass the standard JavaScript Error object with a text description of the error (err.message).]*/
  request.on('error', done);
  /*Codes_SRS_NODE_HTTP_05_002: [buildRequest shall return a Node.js https.ClientRequest object, upon which the caller must invoke the end method in order to actually send the request.]*/
  return request;
};

Http.prototype.toMessage = function toMessage(response, body) {
  var msg;
  /*Codes_SRS_NODE_HTTP_05_006: [If the status code of the HTTP response < 300, toMessage shall create a new azure-iot-common.Message object with data equal to the body of the HTTP response.]*/
  if (response.statusCode < 300) {
    msg = new Message(body);
    for (var item in response.headers) {
      if (item.search("iothub-") !== -1) {
        /*Codes_SRS_NODE_HTTP_05_007: [If the HTTP response has an 'iothub-messageid' header, it shall be saved as the messageId property on the created Message.]*/
        if (item.toLowerCase() === "iothub-messageid") {
          msg.messageId = response.headers[item];
        }
        /*Codes_SRS_NODE_HTTP_05_008: [If the HTTP response has an 'iothub-to' header, it shall be saved as the to property on the created Message.]*/
        else if (item.toLowerCase() === "iothub-to") {
          msg.to = response.headers[item];
        }
        /*Codes_SRS_NODE_HTTP_05_009: [If the HTTP response has an 'iothub-expiry' header, it shall be saved as the expiryTimeUtc property on the created Message.]*/
        else if (item.toLowerCase() === "iothub-expiry") {
          msg.expiryTimeUtc = response.headers[item];
        }
        /*Codes_SRS_NODE_HTTP_05_010: [If the HTTP response has an 'iothub-correlationid' header, it shall be saved as the correlationId property on the created Message.]*/
        else if (item.toLowerCase() === "iothub-correlationid") {
          msg.correlationId = response.headers[item];
        }
      }
      /*Codes_SRS_NODE_HTTP_05_011: [If the HTTP response has an 'etag' header, it shall be saved as the lockToken property on the created Message, minus any surrounding quotes.]*/
      else if (item.toLowerCase() === "etag") {
        // Need to strip the quotes from the string
        var len = response.headers[item].length;
        msg.lockToken = response.headers[item].substring(1, len-1);
      }
    }
  }

  return msg;
};

module.exports = Http;


text:
//Dependencies
#include <stdlib.h>
#include <string.h>
#include "iodefine.h"
#include "rspi.h"
#include "adc.h"
#include "lcd_pmod.h"
#include "os_port.h"
#include "core/net.h"
#include "drivers/rza1_eth.h"
#include "drivers/upd60611.h"
#include "dhcp/dhcp_client.h"
#include "ipv6/slaac.h"
#include "smtp/smtp_client.h"
#include "http/http_server.h"
#include "http/mime.h"
#include "yarrow.h"
#include "str.h"
#include "path.h"
#include "date_time.h"
#include "resource_manager.h"
#include "bma250.h"
#include "debug.h"

//Application configuration
#define APP_MAC_ADDR "00-AB-CD-EF-00-A1"

#define APP_USE_DHCP ENABLED
#define APP_IPV4_HOST_ADDR "192.168.0.20"
#define APP_IPV4_SUBNET_MASK "255.255.255.0"
#define APP_IPV4_DEFAULT_GATEWAY "192.168.0.254"
#define APP_IPV4_PRIMARY_DNS "8.8.8.8"
#define APP_IPV4_SECONDARY_DNS "8.8.4.4"

#define APP_USE_SLAAC ENABLED
#define APP_IPV6_LINK_LOCAL_ADDR "fe80::a1"
#define APP_IPV6_PREFIX "2001:db8::"
#define APP_IPV6_PREFIX_LENGTH 64
#define APP_IPV6_GLOBAL_ADDR "2001:db8::a1"
#define APP_IPV6_ROUTER "fe80::1"
#define APP_IPV6_PRIMARY_DNS "2001:4860:4860::8888"
#define APP_IPV6_SECONDARY_DNS "2001:4860:4860::8844"

#define APP_HTTP_MAX_CONNECTIONS 8

//Forward declaration of functions
HttpAccessStatus httpServerAuthCallback(HttpConnection *connection,
   const char_t *user, const char_t *uri);

error_t httpServerCgiCallback(HttpConnection *connection,
   const char_t *param);

error_t httpServerUriNotFoundCallback(HttpConnection *connection,
   const char_t *uri);

//Global variables
uint_t lcdLine = 0;
uint_t lcdColumn = 0;
uint_t adcValue = 0;
uint_t joystickState = 0;
int8_t ax = 0;
int8_t ay = 0;
int8_t az = 0;

DhcpClientSettings dhcpClientSettings;
DhcpClientCtx dhcpClientContext;
SlaacSettings slaacSettings;
SlaacContext slaacContext;
HttpServerSettings httpServerSettings;
HttpServerContext httpServerContext;
HttpConnection httpConnections[APP_HTTP_MAX_CONNECTIONS];
YarrowContext yarrowContext;
uint8_t seed[32];

/**
 * @brief Set cursor location
 * @param[in] line Line number
 * @param[in] column Column number
 **/

void lcdSetCursor(uint_t line, uint_t column)
{
   lcdLine = MIN(line, 16);
   lcdColumn = MIN(column, 21);
}

/**
 * @brief Write a character to the LCD display
 * @param[in] c Character to be written
 **/

void lcdPutChar(char_t c)
{
   uint8_t buffer[2];

   if(c == '\r')
   {
      lcdColumn = 0;
   }
   else if(c == '\n')
   {
      lcdColumn = 0;
      lcdLine++;
   }
   else if(lcdLine < 16 && lcdColumn < 21)
   {
      buffer[0] = c;
      buffer[1] = '\0';

      //Display current character
      display_set_cursor(lcdColumn, lcdLine);
      display_str(buffer);

      //Advance the cursor position
      if(++lcdColumn >= 21)
      {
         lcdColumn = 0;
         lcdLine++;
      }
   }
}

/**
 * @brief I/O initialization
 **/

void ioInit(void)
{
   //Configure LED (P7_8)
   PORT7.PMCn.BIT.PMCn8 = 0;
   PORT7.PIPCn.BIT.PIPCn8 = 0;
   PORT7.PMn.BIT.PMn8 = 0;
   //Clear LED
   PORT7.Pn.BIT.Pn8 = 0;

   //Configure SW1 (P1_11) as an input
   PORT1.PMCn.BIT.PMCn11 = 0;
   PORT1.PIBCn.BIT.PIBCn11 = 1;
   PORT1.PMn.BIT.PMn11 = 1;

   //Configure PMOD_RST (P3_15) as an output
   PORT3.PMCn.BIT.PMCn15 = 0;
   PORT3.PIPCn.BIT.PIPCn15 = 0;
   PORT3.PMn.BIT.PMn15 = 0;
   //Set PMOD_RST to default state
   PORT3.Pn.BIT.Pn15 = 1;

   //Configure PMOD_CS (P6_13) as an output
   PORT6.PMCn.BIT.PMCn13 = 0;
   PORT6.PIPCn.BIT.PIPCn13 = 0;
   PORT6.PMn.BIT.PMn13 = 0;
   //Set CS to default state
   PORT6.Pn.BIT.Pn13 = 1;

   //Configure PMOD_GPIO (P9_5) as an output
   PORT9.PMCn.BIT.PMCn5 = 0;
   PORT9.PIPCn.BIT.PIPCn5 = 0;
   PORT9.PMn.BIT.PMn5 = 0;
   //Set PMOD_GPIO to default state
   PORT9.Pn.BIT.Pn5 = 1;

   //Configure PHY_RST (P2_7)
   PORT2.PMCn.BIT.PMCn7 = 0;
   PORT2.PIPCn.BIT.PIPCn7 = 0;
   PORT2.PMn.BIT.PMn7 = 0;

   //Reset PHY transceiver
   PORT2.Pn.BIT.Pn7 = 0;
}

/**
 * @brief User task
 **/

void userTask(void *param)
{
   char_t buffer[40];

   //Point to the network interface
   NetInterface *interface = &netInterface[0];

   //Initialize LCD display
   lcdSetCursor(2, 0);
   printf("IPv4 Addr\r\n");
   lcdSetCursor(5, 0);
   printf("IPv6 Link-Local Addr\r\n");
   lcdSetCursor(8, 0);
   printf("IPv6 Global Addr\r\n");

   //Endless loop
   while(1)
   {
#if (IPV4_SUPPORT == ENABLED)
      //Display IPv4 host address
      lcdSetCursor(3, 0);
      printf("%-16s\r\n", ipv4AddrToString(interface->ipv4Config.addr, buffer));
#endif

#if (IPV6_SUPPORT == ENABLED)
      //Display IPv6 link-local address
      lcdSetCursor(6, 0);
      printf("%-40s\r\n", ipv6AddrToString(&interface->ipv6Config.linkLocalAddr, buffer));

      //Display IPv6 global address
      lcdSetCursor(9, 0);
      printf("%-40s\r\n", ipv6AddrToString(&interface->ipv6Config.globalAddr, buffer));
#endif

      //Start A/D conversion
      R_ADC_Read();
      //Get conversion result
      adcValue = g_adc_result * 4;

      //Retrieve acceleration along the 3 axis
      bma250GetAcc(&ax, &ay, &az);

      //Loop delay
      osDelayTask(100);
   }
}

/**
 * @brief LED blinking task
 **/

void blinkTask(void *parameters)
{
   //Endless loop
   while(1)
   {
      PORT7.Pn.BIT.Pn8 = 1;
      osDelayTask(100);
      PORT7.Pn.BIT.Pn8 = 0;
      osDelayTask(900);
   }
}

/**
 * @brief Main entry point
 * @return Unused value
 **/

int_t main(void)
{
   error_t error;
   NetInterface *interface;
   OsTask *task;
   MacAddr macAddr;
#if (APP_USE_DHCP == DISABLED)
   Ipv4Addr ipv4Addr;
#endif
#if (APP_USE_SLAAC == DISABLED)
   Ipv6Addr ipv6Addr;
#endif

   //Initialize kernel
   osInitKernel();
   //Configure debug UART
   debugInit(115200);

   //Start-up message
   TRACE_INFO("\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("*** CycloneTCP Web Server Demo ***\r\n");
   TRACE_INFO("**********************************\r\n");
   TRACE_INFO("Copyright: 2010-2015 Oryx Embedded SARL\r\n");
   TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
   TRACE_INFO("Target: RZ/A1L\r\n");
   TRACE_INFO("\r\n");

   //Configure I/Os
   ioInit();
   //Initialize BMA250 accelerometer
   bma250Init();

   //SPI initialization
   R_SPI_Init();
   //Initialize LCD display
   R_LCD_Init();
   //Turn on LCD display
   display_on();

   //Welcome message
   lcdSetCursor(0, 0);
   printf("Web Server Demo\r\n");

   //ADC initialization
   R_ADC_Open();

   //Generate a random seed

   //PRNG initialization
   error = yarrowInit(&yarrowContext);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize PRNG!\r\n");
   }

   //Properly seed the PRNG
   error = yarrowSeed(&yarrowContext, seed, sizeof(seed));
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to seed PRNG!\r\n");
   }

   //TCP/IP stack initialization
   error = netInit();
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n");
   }

   //Configure the first Ethernet interface
   interface = &netInterface[0];

   //Set interface name
   netSetInterfaceName(interface, "eth0");
   //Set host name
   netSetHostname(interface, "WebServerDemo");
   //Select the relevant network adapter
   netSetDriver(interface, &rza1EthDriver);
   netSetPhyDriver(interface, &upd60611PhyDriver);
   //Set host MAC address
   macStringToAddr(APP_MAC_ADDR, &macAddr);
   netSetMacAddr(interface, &macAddr);

   //Initialize network interface
   error = netConfigInterface(interface);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name);
   }

#if (IPV4_SUPPORT == ENABLED)
#if (APP_USE_DHCP == ENABLED)
   //Get default settings
   dhcpClientGetDefaultSettings(&dhcpClientSettings);
   //Set the network interface to be configured by DHCP
   dhcpClientSettings.interface = interface;
   //Disable rapid commit option
   dhcpClientSettings.rapidCommit = FALSE;

   //DHCP client initialization
   error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings);
   //Failed to initialize DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize DHCP client!\r\n");
   }

   //Start DHCP client
   error = dhcpClientStart(&dhcpClientContext);
   //Failed to start DHCP client?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start DHCP client!\r\n");
   }
#else
   //Set IPv4 host address
   ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr);
   ipv4SetHostAddr(interface, ipv4Addr);

   //Set subnet mask
   ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr);
   ipv4SetSubnetMask(interface, ipv4Addr);

   //Set default gateway
   ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr);
   ipv4SetDefaultGateway(interface, ipv4Addr);

   //Set primary and secondary DNS servers
   ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 0, ipv4Addr);
   ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr);
   ipv4SetDnsServer(interface, 1, ipv4Addr);
#endif
#endif

#if (IPV6_SUPPORT == ENABLED)
#if (APP_USE_SLAAC == ENABLED)
   //Get default settings
   slaacGetDefaultSettings(&slaacSettings);
   //Set the network interface to be configured
   slaacSettings.interface = interface;

   //SLAAC initialization
   error = slaacInit(&slaacContext, &slaacSettings);
   //Failed to initialize SLAAC?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize SLAAC!\r\n");
   }

   //Start IPv6 address autoconfiguration process
   error = slaacStart(&slaacContext);
   //Failed to start SLAAC process?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start SLAAC!\r\n");
   }
#else
   //Set link-local address
   ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr);
   ipv6SetLinkLocalAddr(interface, &ipv6Addr);

   //Set IPv6 prefix
   ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr);
   ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH);

   //Set global address
   ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr);
   ipv6SetGlobalAddr(interface, &ipv6Addr);

   //Set router
   ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr);
   ipv6SetRouter(interface, &ipv6Addr);

   //Set primary and secondary DNS servers
   ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 0, &ipv6Addr);
   ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr);
   ipv6SetDnsServer(interface, 1, &ipv6Addr);
#endif
#endif

   //Get default settings
   httpServerGetDefaultSettings(&httpServerSettings);
   //Bind HTTP server to the desired interface
   httpServerSettings.interface = &netInterface[0];
   //Listen to port 80
   httpServerSettings.port = HTTP_PORT;
   //Client connections
   httpServerSettings.maxConnections = APP_HTTP_MAX_CONNECTIONS;
   httpServerSettings.connections = httpConnections;
   //Specify the server's root directory
   strcpy(httpServerSettings.rootDirectory, "/www/");
   //Set default home page
   strcpy(httpServerSettings.defaultDocument, "index.shtm");
   //Callback functions
   httpServerSettings.authCallback = httpServerAuthCallback;
   httpServerSettings.cgiCallback = httpServerCgiCallback;
   httpServerSettings.uriNotFoundCallback = httpServerUriNotFoundCallback;

   //HTTP server initialization
   error = httpServerInit(&httpServerContext, &httpServerSettings);
   //Failed to initialize HTTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to initialize HTTP server!\r\n");
   }

   //Start HTTP server
   error = httpServerStart(&httpServerContext);
   //Failed to start HTTP server?
   if(error)
   {
      //Debug message
      TRACE_ERROR("Failed to start HTTP server!\r\n");
   }

   //Create user task
   task = osCreateTask("User Task", userTask, NULL, 800, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Create a task to blink the LED
   task = osCreateTask("Blink", blinkTask, NULL, 500, 1);
   //Failed to create the task?
   if(task == OS_INVALID_HANDLE)
   {
      //Debug message
      TRACE_ERROR("Failed to create task!\r\n");
   }

   //Start the execution of tasks
   osStartKernel();

   //This function should never return
   return 0;
}

/**
 * @brief HTTP authentication callback
 * @param[in] connection Handle referencing a client connection
 * @param[in] user NULL-terminated string specifying the user name
 * @param[in] uri NULL-terminated string containing the path to the requested resource
 * @return Access status (HTTP_ACCESS_ALLOWED, HTTP_ACCESS_DENIED,
 *   HTTP_BASIC_AUTH_REQUIRED or HTTP_DIGEST_AUTH_REQUIRED)
 **/

HttpAccessStatus httpServerAuthCallback(HttpConnection *connection,
   const char_t *user, const char_t *uri)
{
   HttpAccessStatus status;

   //Manage access rights
   if(pathMatch(uri, "/passwords.txt"))
   {
      //This file is not visible
      status = HTTP_ACCESS_DENIED;
   }
   else if(pathMatch(uri, "/config/*"))
   {
      //This directory is not visible
      status = HTTP_ACCESS_DENIED;
   }
   else if(pathMatch(uri, "/admin/*"))
   {
      //Only the administrator can access this directory
      if(!strcmp(user, "administrator"))
      {
         //Check the administrator password
         if(httpCheckPassword(connection, "password", HTTP_AUTH_MODE_BASIC))
            status = HTTP_ACCESS_ALLOWED;
         else
            status = HTTP_ACCESS_BASIC_AUTH_REQUIRED;
      }
      else
      {
         //Users other than administrator cannot access this directory
         status = HTTP_ACCESS_BASIC_AUTH_REQUIRED;
      }
   }
   else
   {
      //No restriction for other directories
      status = HTTP_ACCESS_ALLOWED;
   }

   //Return access status
   return status;
}

/**
 * @brief CGI callback function
 * @param[in] connection Handle referencing a client connection
 * @param[in] param NULL-terminated string that contains the CGI parameter
 * @return Error code
 **/

error_t httpServerCgiCallback(HttpConnection *connection,
   const char_t *param)
{
   static uint_t pageCounter = 0;
   uint_t length;

   //Underlying network interface
   NetInterface *interface = connection->socket->interface;

   //Check parameter name
   if(!strcasecmp(param, "PAGE_COUNTER"))
   {
      pageCounter++;
      sprintf(connection->buffer, "%u time%s", pageCounter, (pageCounter >= 2) ? "s" : "");
   }
   else if(!strcasecmp(param, "BOARD_NAME"))
   {
      strcpy(connection->buffer, "Stream it! RZ");
   }
   else if(!strcasecmp(param, "SYSTEM_TIME"))
   {
      systime_t time = osGetSystemTime();
      formatSystemTime(time, connection->buffer);
   }
   else if(!strcasecmp(param, "MAC_ADDR"))
   {
      macAddrToString(&interface->macAddr, connection->buffer);
   }
   else if(!strcasecmp(param, "IPV4_ADDR"))
   {
      ipv4AddrToString(interface->ipv4Config.addr, connection->buffer);
   }
   else if(!strcasecmp(param, "SUBNET_MASK"))
   {
      ipv4AddrToString(interface->ipv4Config.subnetMask, connection->buffer);
   }
   else if(!strcasecmp(param, "DEFAULT_GATEWAY"))
   {
      ipv4AddrToString(interface->ipv4Config.defaultGateway, connection->buffer);
   }
   else if(!strcasecmp(param, "IPV4_PRIMARY_DNS"))
   {
      ipv4AddrToString(interface->ipv4Config.dnsServer[0], connection->buffer);
   }
   else if(!strcasecmp(param, "IPV4_SECONDARY_DNS"))
   {
      ipv4AddrToString(interface->ipv4Config.dnsServer[1], connection->buffer);
   }
#if (IPV6_SUPPORT == ENABLED)
   else if(!strcasecmp(param, "LINK_LOCAL_ADDR"))
   {
      ipv6AddrToString(&interface->ipv6Config.linkLocalAddr, connection->buffer);
   }
   else if(!strcasecmp(param, "GLOBAL_ADDR"))
   {
      ipv6AddrToString(&interface->ipv6Config.globalAddr, connection->buffer);
   }
   else if(!strcasecmp(param, "IPV6_PREFIX"))
   {
      ipv6AddrToString(&interface->ipv6Config.prefix, connection->buffer);
      length = strlen(connection->buffer);
      sprintf(connection->buffer + length, "/%u", interface->ipv6Config.prefixLength);
   }
   else if(!strcasecmp(param, "ROUTER"))
   {
      ipv6AddrToString(&interface->ipv6Config.router, connection->buffer);
   }
   else if(!strcasecmp(param, "IPV6_PRIMARY_DNS"))
   {
      ipv6AddrToString(&interface->ipv6Config.dnsServer[0], connection->buffer);
   }
   else if(!strcasecmp(param, "IPV6_SECONDARY_DNS"))
   {
      ipv6AddrToString(&interface->ipv6Config.dnsServer[1], connection->buffer);
   }
#endif
   else
   {
      return ERROR_INVALID_TAG;
   }

   //Get the length of the resulting string
   length = strlen(connection->buffer);

   //Send the contents of the specified environment variable
   return httpWriteStream(connection, connection->buffer, length);
}

/**
 * @brief URI not found callback
 * @param[in] connection Handle referencing a client connection
 * @param[in] uri NULL-terminated string containing the path to the requested resource
 * @return Error code
 **/

error_t httpServerUriNotFoundCallback(HttpConnection *connection,
   const char_t *uri)
{
   error_t error;
   size_t n;
   char_t *buffer;

   //Process data.xml file?
   if(!strcasecmp(uri, "/data.xml"))
   {
      //Point to the scratch buffer
      buffer = connection->buffer + 384;

      //Format XML data
      n = sprintf(buffer, "<data>\r\n");
      n += sprintf(buffer + n, "  <ax>%d</ax>\r\n", -ax);
      n += sprintf(buffer + n, "  <ay>%d</ay>\r\n", ay);
      n += sprintf(buffer + n, "  <az>%d</az>\r\n", -az);
      n += sprintf(buffer + n, "  <adc>%u</adc>\r\n", adcValue);
      n += sprintf(buffer + n, "  <joystick>%u</joystick>\r\n", joystickState);

      //End of XML data
      n += sprintf(buffer + n, "</data>\r\n");

      //Format HTTP response header
      connection->response.version = connection->request.version;
      connection->response.statusCode = 200;
      connection->response.keepAlive = connection->request.keepAlive;
      connection->response.noCache = TRUE;
      connection->response.contentType = mimeGetType(".xml");
      connection->response.chunkedEncoding = FALSE;
      connection->response.contentLength = n;

      //Send the header to the client
      error = httpWriteHeader(connection);
      //Any error to report?
      if(error) return error;

      //Send response body
      error = httpWriteStream(connection, buffer, n);
      //Any error to report?
      if(error) return error;

      //Properly close output stream
      error = httpCloseStream(connection);
      //Return status code
      return error;
   }
   //Process send_mail.xml file?
   else if(!strcasecmp(uri, "/send_mail.xml"))
   {
      char_t *separator;
      char_t *property;
      char_t *value;
      char_t *p;
      SmtpAuthInfo authInfo;
      SmtpMail mail;
      SmtpMailAddr recipients[4];

      //Initialize structures to zero
      memset(&authInfo, 0, sizeof(authInfo));
      memset(&mail, 0, sizeof(mail));
      memset(recipients, 0, sizeof(recipients));

      //Set the relevant PRNG algorithm to be used
      authInfo.prngAlgo = YARROW_PRNG_ALGO;
      authInfo.prngContext = &yarrowContext;

      //Set email recipients
      mail.recipients = recipients;
      //Point to the scratch buffer
      buffer = connection->buffer;

      //Start of exception handling block
      do
      {
         //Process HTTP request body
         while(1)
         {
            //Read the HTTP request body until an ampersand is encountered
            error = httpReadStream(connection, buffer,
               HTTP_SERVER_BUFFER_SIZE - 1, &n, HTTP_FLAG_BREAK('&'));
            //End of stream detected?
            if(error) break;

            //Properly terminate the string with a NULL character
            buffer[n] = '\0';

            //Remove the trailing ampersand
            if(n > 0 && buffer[n - 1] == '&')
               buffer[--n] = '\0';

            //Decode the percent-encoded string
            httpDecodePercentEncodedString(buffer, buffer, HTTP_SERVER_BUFFER_SIZE);
            //Check whether a separator is present
            separator = strchr(buffer, '=');

            //Separator found?
            if(separator)
            {
               //Split the line
               *separator = '\0';
               //Get property name and value
               property = strTrimWhitespace(buffer);
               value = strTrimWhitespace(separator + 1);

               //Check property name
               if(!strcasecmp(property, "server"))
               {
                  //Save server name
                  authInfo.serverName = strDuplicate(value);
               }
               else if(!strcasecmp(property, "port"))
               {
                  //Save the server port to be used
                  authInfo.serverPort = atoi(value);
               }
               else if(!strcasecmp(property, "userName"))
               {
                  //Save user name
                  authInfo.userName = strDuplicate(value);
               }
               else if(!strcasecmp(property, "password"))
               {
                  //Save password
                  authInfo.password = strDuplicate(value);
               }
               else if(!strcasecmp(property, "useTls"))
               {
                  //Open a secure SSL/TLS session?
                  authInfo.useTls = TRUE;
               }
               else if(!strcasecmp(property, "recipient"))
               {
                  //Split the recipient address list
                  value = strtok_r(value, ", ", &p);

                  //Loop through the list
                  while(value != NULL)
                  {
                     //Save recipient address
                     recipients[mail.recipientCount].name = NULL;
                     recipients[mail.recipientCount].addr = strDuplicate(value);
                     recipients[mail.recipientCount].type = SMTP_RCPT_TYPE_TO;
                     //Get the next item in the list
                     value = strtok_r(NULL, ", ", &p);

                     //Increment the number of recipients
                     if(++mail.recipientCount >= arraysize(recipients))
                        break;
                  }
               }
               else if(!strcasecmp(property, "from"))
               {
                  //Save sender address
                  mail.from.name = NULL;
                  mail.from.addr = strDuplicate(value);
               }
               else if(!strcasecmp(property, "date"))
               {
                  //Save current time
                  mail.dateTime = strDuplicate(value);
               }
               else if(!strcasecmp(property, "subject"))
               {
                  //Save mail subject
                  mail.subject = strDuplicate(value);
               }
               else if(!strcasecmp(property, "body"))
               {
                  //Save mail body
                  mail.body = strDuplicate(value);
               }
            }
         }

         //Propagate exception if necessary
         if(error != ERROR_END_OF_STREAM)
            break;

         //Send mail
         error = smtpSendMail(&authInfo, &mail);

         //Point to the scratch buffer
         buffer = connection->buffer + 384;
         //Format XML data
         n = sprintf(buffer, "<data>\r\n  <status>");

         if(error == NO_ERROR)
            n += sprintf(buffer + n, "Mail successfully sent!\r\n");
         else if(error == ERROR_NAME_RESOLUTION_FAILED)
            n += sprintf(buffer + n, "Cannot resolve SMTP server name!\r\n");
         else if(error == ERROR_AUTHENTICATION_FAILED)
            n += sprintf(buffer + n, "Authentication failed!\r\n");
         else if(error == ERROR_UNEXPECTED_RESPONSE)
            n += sprintf(buffer + n, "Unexpected response from SMTP server!\r\n");
         else
            n += sprintf(buffer + n, "Failed to send mail (error %d)!\r\n", error);

         n += sprintf(buffer + n, "</status>\r\n</data>\r\n");

         //Format HTTP response header
         connection->response.version = connection->request.version;
         connection->response.statusCode = 200;
         connection->response.keepAlive = connection->request.keepAlive;
         connection->response.noCache = TRUE;
         connection->response.contentType = mimeGetType(".xml");
         connection->response.chunkedEncoding = FALSE;
         connection->response.contentLength = n;

         //Send the header to the client
         error = httpWriteHeader(connection);
         //Any error to report?
         if(error) break;

         //Send response body
         error = httpWriteStream(connection, buffer, n);
         //Any error to report?
         if(error) break;

         //Properly close output stream
         error = httpCloseStream(connection);
         //Any error to report?
         if(error) break;

         //End of exception handling block
      } while(0);

      //Free previously allocated memory
      osFreeMem((void *) authInfo.serverName);
      osFreeMem((void *) authInfo.userName);
      osFreeMem((void *) authInfo.password);
      osFreeMem((void *) recipients[0].addr);
      osFreeMem((void *) mail.from.addr);
      osFreeMem((void *) mail.dateTime);
      osFreeMem((void *) mail.subject);
      osFreeMem((void *) mail.body);

      //Return status code
      return error;
   }
   else
   {
      return ERROR_NOT_FOUND;
   }
}


text: MIT Haystack Summer REU 2015


text:
<?php
/////////////////////////////////////////////////////////////////////////////////////
// xbtit - Bittorrent tracker/frontend
//
// Copyright (C) 2004 - 2011  Btiteam
//
//    This file is part of xbtit.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////////

global $CURUSER, $FORUMLINK, $db_prefix, $XBTT_USE, $btit_settings;
?>

<?php

print("".$language["MNU_INDEX"]."	\n");
if ($CURUSER["uid"]==1 || !$CURUSER)
{
    print("".$language["LOGIN"]."\n");
    print("".$language["ACCOUNT_CREATE"]."\n");
    print("".$language["RECOVER_PWD"]."\n");
}
if($CURUSER["view_torrents"]=="yes")
{
print("	".$language["MNU_TORRENT"]."	");
// print("".$language["VR"]."	");
print("".$language["MNU_STATS"]."	");
}
if ($CURUSER["view_forum"]=="yes")
      {
        if ($GLOBALS["FORUMLINK"]=="" || $GLOBALS["FORUMLINK"]=="internal" || $GLOBALS["FORUMLINK"]=="smf")
           print("".$language["MNU_FORUM"]."	\n");
        elseif ($GLOBALS["FORUMLINK"]=="smf")
           print("".$language["MNU_FORUM"]."	\n");
        else
            print("".$language["MNU_FORUM"]."	\n");
      }
if ($CURUSER["can_upload"]=="yes")
{
print("".$language["MNU_UPLOAD"]."	\n");
}
if ($CURUSER["view_news"]=="yes")
    {
        print("".$language['MNU_NEWS']."	\n");
    }
		if ($CURUSER["view_users"]=="yes")
		{
    print("".$language["MNU_MEMBERS"]."	\n");
    print("".$language["STAFF"]."	\n");
    }
if ($CURUSER["uid"] > 1)
{
       print("".$language["LOGOUT"]."	\n");
}
?>


text:
class TestLab
  class Container

    module ClassMethods

      # Container domain list
      #
      # Returns an array of strings containing all the unique domains defined
      # across all containers
      #
      # @return [Array<String>] A unique array of all defined domain names.
      def domains
        self.all.select{ |container| (!container.template rescue true) }.map do |container|
          container.domain ||= container.node.domain
          container.domain
        end.compact.uniq
      end

    end

  end
end


text:
START_ATF_NAMESPACE
    template<>
    struct _CIP<IBinding,&IID_IBinding>
    {
        IBinding *_pInterface;
    };
END_ATF_NAMESPACE
#include <IUnknown.hpp>

START_ATF_NAMESPACE
    template<>
    struct _CIP<IUnknown,&IID_IUnknown>
    {
        IUnknown *_pInterface;
    };
END_ATF_NAMESPACE
#include <IMoniker.hpp>

START_ATF_NAMESPACE
    template<>
    struct _CIP<IMoniker,&IID_IMoniker>
    {
        IMoniker *_pInterface;
    };
END_ATF_NAMESPACE


text:
namespace NVelocity.Runtime.Parser.Node
{
    using System.Reflection;

    using Log;
    using Util.Introspection;

    ///  Abstract class that is used to Execute an arbitrary
    /// method that is in introspected. This is the superclass
    /// for the PutExecutor and SetPropertyExecutor.
    ///
    /// There really should be a superclass for this and AbstractExecutor (which should
    /// be refactored to GetExecutor) because they differ only in the Execute() method.
    ///
    ///
    /// <author>  Jason van Zyl
    /// </author>
    /// <author>  Geir Magnusson Jr.
    /// </author>
    /// <author>  Henning P. Schmiedehausen
    /// </author>
    /// <version>  $Id: SetExecutor.java 685685 2008-08-13 21:43:27Z nbubna $
    /// </version>
    /// <since> 1.5
    /// </since>
    public abstract class SetExecutor
    {
        ///  Tell whether the executor is alive by looking
        /// at the value of the method.
        ///
        /// <returns> True if the executor is alive.
        /// </returns>
        virtual public bool Alive
        {
            get
            {
                return (method != null);
            }

        }
        /// Class logger
        protected internal Log log = null;

        ///  Method to be executed.
        private MethodEntry method;

        ///  Execute method against context.
        /// <param name="instance">
        /// </param>
        /// <param name="value">
        /// </param>
        /// <returns> The result of the invocation.
        /// </returns>
        /// <throws>  IllegalAccessException </throws>
        /// <throws>  InvocationTargetException </throws>
        public abstract object Execute(object o, object value);

        /// <returns> The method to invoke.
        /// </returns>
        ///  /// <param name="method">
        /// </param>
        public virtual MethodEntry Method
        {
            get
            {
                return method;
            }
            protected set
            {
                method = value;
            }
        }
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="fill"
    android:padding="6dp" >

    <ImageView
        android:id="@+id/contactIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginRight="5dp"
        android:adjustViewBounds="true"
        android:contentDescription="@string/iconContactContentDescription"
        android:maxHeight="48dp"
        android:maxWidth="48dp"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/contactDisplayName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/contactIcon"
        android:singleLine="true"
        android:text="@string/progressRecognizing"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/contactStarred"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/contactDisplayName"
        android:text="@string/star"
        android:textColor="@color/yellow1"
        android:textSize="20sp"
        android:typeface="monospace" />

    <TextView
        android:id="@+id/contactLastTimeContacted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/contactDisplayName"
        android:layout_toRightOf="@+id/contactIcon"
        android:singleLine="true"
        android:text="@string/formatDate"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/contactTimesContacted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="@color/semi_transparent"
        android:padding="2dp"
        android:text="@integer/versionAcousticModel"
        android:textSize="14sp" />

</RelativeLayout>


text:
#include <click/config.h>
#include "aggregateip.hh"
#include <click/error.hh>
#include <click/straccum.hh>
#include <click/args.hh>
#include <clicknet/ip.h>
#include <clicknet/tcp.h>
#include <clicknet/udp.h>
#include <click/packet_anno.hh>
CLICK_DECLS

AggregateIP::AggregateIP()
{
}

AggregateIP::~AggregateIP()
{
}

int
AggregateIP::configure(Vector<String> &conf, ErrorHandler *errh)
{
    String arg;
    _incremental = _unshift_ip_addr = false;
    if (Args(conf, this, errh)
	.read_mp("FIELD", AnyArg(), arg)
	.read("INCREMENTAL", _incremental)
	.read("UNSHIFT_IP_ADDR", _unshift_ip_addr)
	.complete() < 0)
	return -1;
    const char *end = IPField::parse(arg.begin(), arg.end(), -1, &_f, errh, this);
    if (end == arg.begin())
	return -1;
    else if (end != arg.end())
	return errh->error("garbage after field specification");
    int32_t right = _f.bit_offset() + _f.bit_length() - 1;
    if ((_f.bit_offset() / 32) != (right / 32))
	return errh->error("field specification does not fit within a single word");
    if (_f.bit_length() > 32)
	return errh->error("field length too large, max 32");
    else if (_f.bit_length() == 32 && _incremental)
	return errh->error("'INCREMENTAL' is incompatible with field length 32");
    if (_f.bit_length() == 32)
	_mask = 0xFFFFFFFFU;
    else
	_mask = (1 << _f.bit_length()) - 1;
    _offset = (_f.bit_offset() / 32) * 4;
    if (!_unshift_ip_addr || _f.proto() != 0 || _f.bit_offset() < 12*8 || _f.bit_offset() >= 20*8)
	_shift = 31 - right % 32;
    else {
	_mask <<= 31 - right % 32;
	_shift = 0;
    }
    return 0;
}

Packet *
AggregateIP::bad_packet(Packet *p)
{
    if (noutputs() == 2)
	output(1).push(p);
    else
	p->kill();
    return 0;
}

Packet *
AggregateIP::handle_packet(Packet *p)
{
    if (!p->has_network_header())
	return bad_packet(p);

    const click_ip *iph = p->ip_header();
    int offset = p->length();
    switch (_f.proto()) {
      case 0:
	offset = p->network_header_offset();
	break;
      case IP_PROTO_TCP_OR_UDP:
	if (IP_FIRSTFRAG(iph) && (iph->ip_p == IP_PROTO_TCP || iph->ip_p == IP_PROTO_UDP))
	    offset = p->transport_header_offset();
	break;
      case IP_PROTO_TRANSP:
	if (IP_FIRSTFRAG(iph))
	    offset = p->transport_header_offset();
	break;
      case IP_PROTO_PAYLOAD:
	if (!IP_FIRSTFRAG(iph))
	    /* bad; will be thrown away below */;
	else if (iph->ip_p == IPPROTO_TCP && p->transport_header_offset() + sizeof(click_tcp) <= p->length()) {
	    const click_tcp *tcph = (const click_tcp *)p->transport_header();
	    offset = p->transport_header_offset() + (tcph->th_off << 2);
	} else if (iph->ip_p == IPPROTO_UDP)
	    offset = p->transport_header_offset() + sizeof(click_udp);
	break;
      default:
	if (IP_FIRSTFRAG(iph) && iph->ip_p == _f.proto())
	    offset = p->transport_header_offset();
	break;
    }
    offset += _offset;

    if (offset + 4 > (int)p->length())
	return bad_packet(p);

    uint32_t udata = *((const uint32_t *)(p->data() + offset));
    uint32_t agg = (ntohl(udata) >> _shift) & _mask;

    if (_incremental)
	SET_AGGREGATE_ANNO(p, (AGGREGATE_ANNO(p) << _f.bit_length()) + agg);
    else
	SET_AGGREGATE_ANNO(p, agg);

    return p;
}

void
AggregateIP::push(int, Packet *p)
{
    if (Packet *q = handle_packet(p))
	output(0).push(q);
}

Packet *
AggregateIP::pull(int)
{
    Packet *p = input(0).pull();
    if (p)
	p = handle_packet(p);
    return p;
}

String
AggregateIP::read_handler(Element *e, void *thunk)
{
    AggregateIP *aip = static_cast<AggregateIP *>(e);
    switch ((intptr_t)thunk) {
      case 0:
	return NameInfo::revquery_int(NameInfo::T_IP_PROTO, e, aip->_f.proto());
      case 1:
	return String(aip->_f.bit_offset());
      case 2:
	return String(aip->_f.bit_length());
      case 3:
	return aip->_f.unparse(e, false);
      default:
	return "<error>";
    }
}

void
AggregateIP::add_handlers()
{
    add_read_handler("header", read_handler, 0);
    add_read_handler("bit_offset", read_handler, 1);
    add_read_handler("bit_length", read_handler, 2);
    add_read_handler("field", read_handler, 3);
}

CLICK_ENDDECLS
ELEMENT_REQUIRES(userlevel IPFieldInfo)
EXPORT_ELEMENT(AggregateIP)


text:
#include "result_response.hpp"

#include "external.hpp"
#include "logger.hpp"
#include "protocol.hpp"
#include "result_metadata.hpp"
#include "serialization.hpp"

extern "C" {

void cass_result_free(const CassResult* result) {
  result->dec_ref();
}

size_t cass_result_row_count(const CassResult* result) {
  if (result->kind() == CASS_RESULT_KIND_ROWS) {
    return result->row_count();
  }
  return 0;
}

size_t cass_result_column_count(const CassResult* result) {
  if (result->kind() == CASS_RESULT_KIND_ROWS) {
    return result->column_count();
  }
  return 0;
}

CassError cass_result_column_name(const CassResult* result,
                                  size_t index,
                                  const char** name,
                                  size_t* name_length) {
  const cass::SharedRefPtr<cass::ResultMetadata>& metadata(result->metadata());
  if (index >= metadata->column_count()) {
    return CASS_ERROR_LIB_INDEX_OUT_OF_BOUNDS;
  }
  if (result->kind() != CASS_RESULT_KIND_ROWS) {
    return CASS_ERROR_LIB_BAD_PARAMS;
  }
  const cass::ColumnDefinition def = metadata->get_column_definition(index);
  *name = def.name.data();
  *name_length = def.name.size();
  return CASS_OK;
}

CassValueType cass_result_column_type(const CassResult* result, size_t index) {
  const cass::SharedRefPtr<cass::ResultMetadata>& metadata(result->metadata());
  if (result->kind() == CASS_RESULT_KIND_ROWS &&
      index < metadata->column_count()) {
    return metadata->get_column_definition(index).data_type->value_type();
  }
  return CASS_VALUE_TYPE_UNKNOWN;
}

const CassDataType* cass_result_column_data_type(const CassResult* result, size_t index) {
  const cass::SharedRefPtr<cass::ResultMetadata>& metadata(result->metadata());
  if (result->kind() == CASS_RESULT_KIND_ROWS &&
      index < metadata->column_count()) {
    return CassDataType::to(metadata->get_column_definition(index).data_type.get());
  }
  return NULL;
}

const CassRow* cass_result_first_row(const CassResult* result) {
  if (result->kind() == CASS_RESULT_KIND_ROWS && result->row_count() > 0) {
    return CassRow::to(&result->first_row());
  }
  return NULL;
}

cass_bool_t cass_result_has_more_pages(const CassResult* result) {
  return static_cast<cass_bool_t>(result->has_more_pages());
}

CassError cass_result_paging_state_token(const CassResult* result,
                                   const char** paging_state,
                                   size_t* paging_state_size) {
  if (!result->has_more_pages()) {
    return CASS_ERROR_LIB_NO_PAGING_STATE;
  }
  *paging_state = result->paging_state().data();
  *paging_state_size = result->paging_state().size();
  return CASS_OK;
}

} // extern "C"

namespace cass {

class DataTypeDecoder {
public:
  DataTypeDecoder(char* input, SimpleDataTypeCache& cache)
    : buffer_(input)
    , cache_(cache) { }

  char* buffer() const { return buffer_; }

  DataType::ConstPtr decode() {
    uint16_t value_type;
    buffer_ = decode_uint16(buffer_, value_type);

    switch (value_type) {
      case CASS_VALUE_TYPE_CUSTOM:
        return decode_custom();

      case CASS_VALUE_TYPE_LIST:
      case CASS_VALUE_TYPE_SET:
      case CASS_VALUE_TYPE_MAP:
        return decode_collection(static_cast<CassValueType>(value_type));

      case CASS_VALUE_TYPE_UDT:
        return decode_user_type();

      case CASS_VALUE_TYPE_TUPLE:
        return decode_tuple();

      default:
        return cache_.by_value_type(value_type);
    }

    return DataType::NIL;
  }

private:
  DataType::ConstPtr decode_custom() {
    StringRef class_name;
    buffer_ = decode_string(buffer_, &class_name);

    DataType::ConstPtr type = cache_.by_class(class_name);
    if (type) return type;

    // If no mapping exists, return an actual custom type.
    return DataType::ConstPtr(new CustomType(class_name.to_string()));
  }

  DataType::ConstPtr decode_collection(CassValueType collection_type) {
    DataType::Vec types;
    types.push_back(decode());
    if (collection_type == CASS_VALUE_TYPE_MAP) {
      types.push_back(decode());
    }
    return DataType::ConstPtr(new CollectionType(collection_type, types, false));
  }

  DataType::ConstPtr decode_user_type() {
    StringRef keyspace;
    buffer_ = decode_string(buffer_, &keyspace);

    StringRef type_name;
    buffer_ = decode_string(buffer_, &type_name);

    uint16_t n;
    buffer_ = decode_uint16(buffer_, n);

    UserType::FieldVec fields;
    for (uint16_t i = 0; i < n; ++i) {
      StringRef field_name;
      buffer_ = decode_string(buffer_, &field_name);
      fields.push_back(UserType::Field(field_name.to_string(), decode()));
    }
    return DataType::ConstPtr(new UserType(keyspace.to_string(),
                                           type_name.to_string(),
                                           fields,
                                           false));
  }

  DataType::ConstPtr decode_tuple() {
    uint16_t n;
    buffer_ = decode_uint16(buffer_, n);

    DataType::Vec types;
    for (uint16_t i = 0; i < n; ++i) {
      types.push_back(decode());
    }
    return DataType::ConstPtr(new TupleType(types, false));
  }

private:
  char* buffer_;
  SimpleDataTypeCache& cache_;
};

bool ResultResponse::decode(int version, char* input, size_t size) {
  protocol_version_ = version;

  char* buffer = decode_int32(input, kind_);

  switch (kind_) {
    case CASS_RESULT_KIND_VOID:
      return true;
      break;

    case CASS_RESULT_KIND_ROWS:
      return decode_rows(version, buffer);
      break;

    case CASS_RESULT_KIND_SET_KEYSPACE:
      return decode_set_keyspace(buffer);
      break;

    case CASS_RESULT_KIND_PREPARED:
      return decode_prepared(version, buffer);
      break;

    case CASS_RESULT_KIND_SCHEMA_CHANGE:
      return decode_schema_change(buffer);
      break;

    default:
      assert(false);
  }
  return false;
}

char* ResultResponse::decode_metadata(int version,
                                      char* input, ResultMetadata::Ptr* metadata,
                                      bool has_pk_indices) {
  int32_t flags = 0;
  char* buffer = decode_int32(input, flags);

  int32_t column_count = 0;
  buffer = decode_int32(buffer, column_count);

  if (supports_result_metadata_id(version)) {
    if (flags & CASS_RESULT_FLAG_METADATA_CHANGED) {
      buffer = decode_string(buffer, &new_metadata_id_);
    }
  }

  if (has_pk_indices) {
    int32_t pk_count = 0;
    buffer = decode_int32(buffer, pk_count);
    for (int i = 0; i < pk_count; ++i) {
      uint16_t pk_index = 0;
      buffer = decode_uint16(buffer, pk_index);
      pk_indices_.push_back(pk_index);
    }
  }

  if (flags & CASS_RESULT_FLAG_HAS_MORE_PAGES) {
    has_more_pages_ = true;
    buffer = decode_bytes(buffer, &paging_state_);
  } else {
    has_more_pages_ = false;
  }

  if (!(flags & CASS_RESULT_FLAG_NO_METADATA)) {
    bool global_table_spec = flags & CASS_RESULT_FLAG_GLOBAL_TABLESPEC;

    if (global_table_spec) {
      buffer = decode_string(buffer, &keyspace_);
      buffer = decode_string(buffer, &table_);
    }

    metadata->reset(new ResultMetadata(column_count));

    SimpleDataTypeCache cache;

    for (int i = 0; i < column_count; ++i) {
      ColumnDefinition def;

      def.index = i;

      if (!global_table_spec) {
        buffer = decode_string(buffer, &def.keyspace);
        buffer = decode_string(buffer, &def.table);
      }

      buffer = decode_string(buffer, &def.name);

      DataTypeDecoder type_decoder(buffer, cache);
      def.data_type = DataType::ConstPtr(type_decoder.decode());
      buffer = type_decoder.buffer();

      (*metadata)->add(def);
    }
  }
  return buffer;
}

void ResultResponse::decode_first_row() {
  if (row_count_ > 0 &&
      metadata_ && // Valid metadata required for column count
      first_row_.values.empty()) { // Only decode the first row once
    first_row_.values.reserve(column_count());
    rows_ = decode_row(rows_, this, first_row_.values);
  }
}

bool ResultResponse::decode_rows(int version, char* input) {
  char* buffer = decode_metadata(version, input, &metadata_);
  rows_ = decode_int32(buffer, row_count_);
  decode_first_row();
  return true;
}

bool ResultResponse::decode_set_keyspace(char* input) {
  decode_string(input, &keyspace_);
  return true;
}

bool ResultResponse::decode_prepared(int version, char* input) {
  char* buffer = decode_string(input, &prepared_id_);
  if (supports_result_metadata_id(version)) {
    buffer = decode_string(buffer, &result_metadata_id_);
  }
  buffer = decode_metadata(version, buffer, &metadata_, version >= 4);
  if (version > 1) {
    decode_metadata(version, buffer, &result_metadata_);
  }
  return true;
}

bool ResultResponse::decode_schema_change(char* input) {
  char* buffer = decode_string(input, &change_);
  buffer = decode_string(buffer, &keyspace_);
  buffer = decode_string(buffer, &table_);
  return true;
}

} // namespace cass


text: Object.defineProperty(Symbol, 'iterator', {value: Symbol('iterator')});


text:
using System;
//### Problem 5. Workdays
//*	Write a method that calculates the number of workdays between today and given date, passed as parameter.
//*	Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter date (year/month/day): ");
        DateTime endDate = DateTime.Parse(Console.ReadLine());
        // holidays in array are from non leap year
        DateTime[] holidays = new DateTime[]
        {
            // later we use only the DayofYear property, year here must be non-leap year
            new DateTime(2001,12,24),
            new DateTime(2001,3,3),
        };

        int count = WorkDaysToDate(endDate, holidays);
        Console.WriteLine(count);
    }

    private static int WorkDaysToDate(DateTime endDate, DateTime[] holidays)
    {
        DateTime today = DateTime.Today;
        if (endDate <= today) return 0;
        int counter = 0;
        while (today < endDate)
        {
            bool isHoliday = false;
            int leapIndex = 0;  // this is a correction index for leap years
            if (DateTime.IsLeapYear(today.Year))
            {
                leapIndex = 1;
            }

            if (today <= new DateTime(2015 / 2 / 28))  // we don`t need correction index for these days of leap year
            {
                leapIndex = 0;
            }

            for (int i = 0; i < holidays.Length; i++)
            {

                if (today.DayOfYear - leapIndex == holidays[i].DayOfYear)
                {
                    isHoliday = true;
                    break;
                }
            }

            if (today.DayOfWeek == DayOfWeek.Saturday || today.DayOfWeek == DayOfWeek.Sunday) isHoliday = true;

            if (isHoliday)
            {
                today = today.AddDays(1);
            }
            else
            {
                counter++;
                today = today.AddDays(1);
            }
        }
        counter--; // don`t count first day
        return counter;
    }
}


text:
@interface ZRMorePush1Controller : ZRShareTableViewController

@end


text:
package com.blazebit.security.spi;

import com.blazebit.security.model.Action;

/**
 * A factory for creating action objects by name.
 *
 */
public interface ActionFactory {

	/**
	 * Creates an action object for the given action parameter.
	 *
	 * @param action The name of the action to create
	 * @return The action object for the given action
	 * @see Action
	 */
	public Action createAction(String action);

}


text:
class a_text_area_base
{
protected:
    static terminalpp::element const fill;

    munin::text_area   text_area_;
    terminalpp::canvas canvas_{{0, 0}};

    void fill_canvas(terminalpp::extent canvas_size);
    void verify_oob_is_untouched();
};

class a_text_area : public a_text_area_base, public testing::Test
{
};


text:
require File.dirname(__FILE__) + '/../../../../spec_helper'
require 'net/http'

describe "Net::HTTPResponse#response" do
  it "returns self" do
    res = Net::HTTPUnknownResponse.new("1.0", "???", "test response")
    res.response.should equal(res)
  end
end


text:
package connectors

import com.cjwwdev.http.verbs.Http
import com.cjwwdev.implicits.ImplicitDataSecurity._
import helpers.connectors.ConnectorSpec

import scala.concurrent.ExecutionContext.Implicits.global

class DeversityMicroserviceConnectorSpec extends ConnectorSpec {

  val testConnector = new DeversityConnector {
    override val deversity: String = "/test/deversity"
    override val http: Http        = mockHttp
  }

  "getDeversityEnrolment" should {
    "return some DeversityEnrolment" when {
      "the response has an Ok status" in {
        mockHttpGet(response = fakeHttpResponse(OK, testTeacherEnrolment.encrypt))

        awaitAndAssert(testConnector.getDeversityEnrolment) {
          _ mustBe Some(testTeacherEnrolment)
        }
      }
    }

    "return None" when {
      "the response has a NoContent status" in {
        mockHttpGet(response = fakeHttpResponse(NO_CONTENT))

        awaitAndAssert(testConnector.getDeversityEnrolment) {
          _ mustBe None
        }
      }

      "the response has NotFound status" in {
        mockHttpGet(response = fakeHttpResponse(NOT_FOUND))

        awaitAndAssert(testConnector.getDeversityEnrolment) {
          _ mustBe None
        }
      }
    }
  }

  "getTeacherInfo" should {
    "return some TeacherInfo" in {
      mockHttpGet(response = fakeHttpResponse(OK, testTeacherDetails.encrypt))

      awaitAndAssert(testConnector.getTeacherInfo("testTeacher", "testSchool")) {
        _ mustBe Some(testTeacherDetails)
      }
    }

    "return None" in {
      mockHttpGet(response = fakeHttpResponse(NOT_FOUND))

      awaitAndAssert(testConnector.getTeacherInfo("testTeacher", "testSchool")) {
        _ mustBe None
      }
    }
  }

  "getSchoolInfo" should {
    "return some OrgDetails" in {
      mockHttpGet(response = fakeHttpResponse(OK, testOrgDetails.encrypt))

      awaitAndAssert(testConnector.getSchoolInfo("testSchool")) {
        _ mustBe Some(testOrgDetails)
      }
    }

    "return None" in {
      mockHttpGet(response = fakeHttpResponse(NOT_FOUND))

      awaitAndAssert(testConnector.getSchoolInfo("testSchool")) {
        _ mustBe None
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ContextOptimised.Models
{
    // Models returned by MeController actions.
    public class GetViewModel
    {
        public string Hometown { get; set; }
    }
}


text:
import sys
import json
import threading

if sys.version_info < (3, 0):
    reload(sys)
    sys.setdefaultencoding('utf-8')

class SpiderManager(object):
    def __init__(self):
        self.spider_list = dict()

    def set_spider(self, spider):
        self.spider_list[spider._spider_id] = spider

    def del_spider(self, spider_id):
        if spider_id in self.spider_list.keys():
            self.spider_list[spider_id].stop()
            del self.spider_list[spider_id]

    def init_system(self):
        pass

    def get_all_spider(self):
        return json.dumps(self.spider_list.keys())

    def find_spider(self, spider_id):
        pass

    def start_spider(self, spider_id):
        if self.spider_list[spider_id]._spider_status == "stopped":
            thread = threading.Thread(target=self.spider_list[spider_id].start)
            thread.setDaemon(True)
            thread.start()

    def restart_spider(self, spider_id):
        thread = threading.Thread(target=self.spider_list[spider_id].restart)
        thread.setDaemon(True)
        thread.start()

    def stop_spider(self, spider_id):
        self.spider_list[spider_id].stop()

    def get_spider_detail(self, spider_id):
        return str(self.spider_list[spider_id]._process_count)


text:
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using NUnit.Framework;
using ReCommendedExtension.ContextActions;

namespace ReCommendedExtension.Tests.ContextActions
{
    [TestFixture]
    public sealed class RemoveAssertNotNullAvailabilityTests : CSharpContextActionAvailabilityTestBase<RemoveAssertNotNull>
    {
        protected override string ExtraPath => "";

        protected override string RelativeTestDataPath => @"ContextActions\RemoveAssertNotNull";

        [Test]
        public void TestAvailability() => DoNamedTest2();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.catalina.mbeans (Apache Tomcat 9.0.0.M11 API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.catalina.mbeans

Classes

ClassNameMBean

ConnectorMBean

ContainerMBean

ContextEnvironmentMBean

ContextMBean

ContextResourceLinkMBean

ContextResourceMBean

GlobalResourcesLifecycleListener

GroupMBean

JmxRemoteLifecycleListener

JmxRemoteLifecycleListener.RmiClientLocalhostSocketFactory

JmxRemoteLifecycleListener.RmiServerBindSocketFactory

JmxRemoteLifecycleListener.SslRmiServerBindSocketFactory

MBeanDumper

MBeanFactory

MBeanUtils

MemoryUserDatabaseMBean

NamingResourcesMBean

RoleMBean

ServiceMBean

UserMBean


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "log".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $action
 * @property integer $time
 */
class LogModel extends Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'time', 'related_id', 'station_id'], 'integer'],
            [['action'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'Người dùng',
            'action' => 'Hoạt động',
            'time' => 'Thời gian',
            'related_id' => 'Thiết bị',
            'station_id' => 'Trạm',
        ];
    }

    public static function _prepareDataSelect($collections, $key, $value, $addFirst = true) {
        $data = [];
        if ($addFirst) $data[0] = 'Chọn hoạt động';
        return parent::_prepareDataSelect($collections, $key, $value, $data);
    }
}


text:
事件

  <ng-container matColumnDef="select">

      <mat-checkbox
        (change)="$event ? masterToggle() : null"
        [checked]="selection.hasValue() && isAllSelected()"
        [indeterminate]="selection.hasValue() && !isAllSelected()"
      >
      </mat-checkbox>

      <mat-checkbox
        (click)="$event.stopPropagation()"
        (change)="$event ? selection.toggle(row) : null"
        [checked]="selection.isSelected(row)"
      >
      </mat-checkbox>

  </ng-container>

  <ng-container matColumnDef="name">
    姓名
    {{ element.name }}
  </ng-container>

  <ng-container matColumnDef="age">
    年龄
    {{ element.age }}
  </ng-container>

  <ng-container matColumnDef="address">
    省份
    {{ element.address }}
  </ng-container>

  <ng-container matColumnDef="province">
    市区
    {{ element.province }}
  </ng-container>

  <ng-container matColumnDef="city">
    地址
    {{ element.city }}
  </ng-container>

  <ng-container matColumnDef="zip">
    邮编
    {{ element.zip }}
  </ng-container>


text:
namespace CoreAppSkeleton.Data.Common.Models
{
    public interface IOrderable
    {
        int OrderBy { get; set; }
    }
}


text:
#ifndef CBUFFER_H
#define CBUFFER_H

class CBuffer
{
private:
    uint8_t* _data;
    size_t _size;
    size_t _allocatedSize;
    boost::scoped_array<uint8_t> _spAllocation;

    // disallow copy and assignment.
    CBuffer(const CBuffer&);
    void operator=(const CBuffer& other);

public:
    CBuffer(); // deliberately makes the buffer null
    void Reset(); // releases current pointer

    CBuffer(size_t nSize);
    HRESULT InitWithAllocation(size_t size);

    CBuffer(uint8_t* pByteArray, size_t nByteArraySize, bool fCopy);

    HRESULT InitWithAllocAndCopy(uint8_t* pByteArray, size_t nByteArraySize);
    HRESULT InitNoAlloc(uint8_t* pByteArray, size_t nByteArraySize);

    inline size_t GetSize() {return _size;}
    inline size_t GetAllocatedSize() {return _allocatedSize;}

    HRESULT SetSize(size_t size);

    inline uint8_t* GetData() {return _data;}

    bool IsValid();
};

typedef boost::shared_ptr<CBuffer> CRefCountedBuffer;

#endif


text:
#include "test/core/end2end/end2end_tests.h"

#include <stdio.h>
#include <string.h>

#include <grpc/byte_buffer.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/string.h"
#include "test/core/end2end/cq_verifier.h"

static void* tag(intptr_t t) { return (void*)t; }

static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,
                                            const char* test_name,
                                            grpc_channel_args* client_args,
                                            grpc_channel_args* server_args) {
  grpc_end2end_test_fixture f;
  gpr_log(GPR_INFO, "Running test: %s/%s", test_name, config.name);
  f = config.create_fixture(client_args, server_args);
  config.init_server(&f, server_args);
  config.init_client(&f, client_args);
  return f;
}

static gpr_timespec n_seconds_from_now(int n) {
  return grpc_timeout_seconds_to_deadline(n);
}

static gpr_timespec five_seconds_from_now(void) {
  return n_seconds_from_now(5);
}

static void drain_cq(grpc_completion_queue* cq) {
  grpc_event ev;
  do {
    ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);
  } while (ev.type != GRPC_QUEUE_SHUTDOWN);
}

static void shutdown_server(grpc_end2end_test_fixture* f) {
  if (!f->server) return;
  grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));
  GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),
                                         grpc_timeout_seconds_to_deadline(5),
                                         nullptr)
                 .type == GRPC_OP_COMPLETE);
  grpc_server_destroy(f->server);
  f->server = nullptr;
}

static void shutdown_client(grpc_end2end_test_fixture* f) {
  if (!f->client) return;
  grpc_channel_destroy(f->client);
  f->client = nullptr;
}

static void end_test(grpc_end2end_test_fixture* f) {
  shutdown_server(f);
  shutdown_client(f);

  grpc_completion_queue_shutdown(f->cq);
  drain_cq(f->cq);
  grpc_completion_queue_destroy(f->cq);
  grpc_completion_queue_destroy(f->shutdown_cq);
}

static void empty_batch_body(grpc_end2end_test_config /*config*/,
                             grpc_end2end_test_fixture f) {
  grpc_call* c;
  cq_verifier* cqv = cq_verifier_create(f.cq);
  grpc_call_error error;
  grpc_op* op = nullptr;

  gpr_timespec deadline = five_seconds_from_now();
  c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,
                               grpc_slice_from_static_string("/foo"), nullptr,
                               deadline, nullptr);
  GPR_ASSERT(c);

  error = grpc_call_start_batch(c, op, 0, tag(1), nullptr);
  GPR_ASSERT(GRPC_CALL_OK == error);
  CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
  cq_verify(cqv);

  grpc_call_unref(c);

  cq_verifier_destroy(cqv);
}

static void test_invoke_empty_body(grpc_end2end_test_config config) {
  grpc_end2end_test_fixture f;

  f = begin_test(config, "test_invoke_empty_body", nullptr, nullptr);
  empty_batch_body(config, f);
  end_test(&f);
  config.tear_down_data(&f);
}

void empty_batch(grpc_end2end_test_config config) {
  test_invoke_empty_body(config);
}

void empty_batch_pre_init(void) {}


text:
.. currentmodule:: zbx.io

===========================
Dump and load configuration
===========================

.. automodule:: zbx.io
   :members:


text:
clone

```
$ git clone git@github.com:ivansoft/memobook.git
```

and find out what you want by using

```
$ grep -rnH "match" ./memobook
```

or just

```
$ grep -rl "match" ./memobook
```


text:
/*
 * @test
 * @bug 5031171
 * @summary Test parameter annotations.
 * @library ../../lib
 * @compile  ../../lib/Tester.java Main.java
 * @run main Main
 */

import java.io.IOException;
import sbql4j8.com.sun.javadoc.*;

public class Main extends Tester.Doclet {

    private static final Tester tester = new Tester("Main", "pkg1");

    public static void main(String[] args) throws IOException {
        tester.run();
        tester.verify();
    }

    public static boolean start(RootDoc root) {
        try {
            for (PackageDoc pkg : root.specifiedPackages()) {
                for (ClassDoc cd : pkg.ordinaryClasses()) {
                    for (ConstructorDoc c : cd.constructors()) {
                        tester.println(c);
                        tester.println();
                        for (Parameter p : c.parameters()) {
                            tester.printParameter(p);
                        }
                        tester.println();
                    }
                    for (MethodDoc m : cd.methods()) {
                        tester.println(m);
                        tester.println();
                        for (Parameter p : m.parameters()) {
                            tester.printParameter(p);
                        }
                        tester.println();
                    }
                }
            }

            return true;
        } catch (IOException e) {
            return false;
        }
    }
}


text:
Bootstraps your form component with low-level validation feat.

## Importat Note

**Project dropped**.

This **was** a work-in-progress. However, I am stopping this project because starting `v0.13`, [**React** seems to be going away from mixins](https://facebook.github.io/react/blog/2015/03/10/react-v0.13.html); and I couldn't think a good API for this project that wouldn't be boilerplatey or annoying.

## Acknowledgement

**react-vixin** © 2015+, Kier Borromeo (srph). **react-vixin** is released under the [BSD-3](http://opensource.org/licenses/BSD-3-Clause) license.

> [srph.github.io](http://srph.github.io)  ·
> GitHub [@srph](https://github.com/srph)  ·
> Twitter [@_srph](https://twitter.com/_srph)


text:
<?php

namespace Kirby\Parsley;

use DOMComment;
use DOMNode;
use DOMNodeList;
use DOMText;
use Kirby\Toolkit\Html;

class Inline
{
	protected string $html = '';
	protected array $marks = [];

	public function __construct(DOMNode $node, array $marks = [])
	{
		$this->createMarkRules($marks);
		$this->html = trim(static::parseNode($node, $this->marks) ?? '');
	}

	/**
	 * Loads all mark rules
	 */
	protected function createMarkRules(array $marks): array
	{
		foreach ($marks as $mark) {
			$this->marks[$mark['tag']] = $mark;
		}

		return $this->marks;
	}

	/**
	 * Get all allowed attributes for a DOMNode
	 * as clean array
	 */
	public static function parseAttrs(DOMNode $node, array $marks = []): array
	{
		$attrs    = [];
		$mark     = $marks[$node->tagName];
		$defaults = $mark['defaults'] ?? [];

		foreach ($mark['attrs'] ?? [] as $attr) {
			if ($node->hasAttribute($attr)) {
				$attrs[$attr] = $node->getAttribute($attr);
			} else {
				$attrs[$attr] = $defaults[$attr] ?? null;
			}
		}

		return $attrs;
	}

	/**
	 * Parses all children and creates clean HTML
	 * for each of them.
	 */
	public static function parseChildren(DOMNodeList $children, array $marks): string
	{
		$html = '';
		foreach ($children as $child) {
			$html .= static::parseNode($child, $marks);
		}
		return $html;
	}

	/**
	 * Go through all child elements and create
	 * clean inner HTML for them
	 */
	public static function parseInnerHtml(DOMNode $node, array $marks = []): string|null
	{
		$html = static::parseChildren($node->childNodes, $marks);

		// trim the inner HTML for paragraphs
		if ($node->tagName === 'p') {
			$html = trim($html);
		}

		// return null for empty inner HTML
		if ($html === '') {
			return null;
		}

		return $html;
	}

	/**
	 * Converts the given node to clean HTML
	 */
	public static function parseNode(DOMNode $node, array $marks = []): string|null
	{
		if ($node instanceof DOMText) {
			return Html::encode($node->textContent);
		}

		// ignore comments
		if ($node instanceof DOMComment) {
			return null;
		}

		// unknown marks
		if (array_key_exists($node->tagName, $marks) === false) {
			return static::parseChildren($node->childNodes, $marks);
		}

		// collect all allowed attributes
		$attrs = static::parseAttrs($node, $marks);

		// close self-closing elements
		if (Html::isVoid($node->tagName) === true) {
			return '<' . $node->tagName . Html::attr($attrs, null, ' ') . ' />';
		}

		$innerHtml = static::parseInnerHtml($node, $marks);

		// skip empty paragraphs
		if ($innerHtml === null && $node->tagName === 'p') {
			return null;
		}

		// create the outer html for the element
		return '<' . $node->tagName . Html::attr($attrs, null, ' ') . '>' . $innerHtml . '</' . $node->tagName . '>';
	}

	/**
	 * Returns the HTML contents of the element
	 */
	public function innerHtml(): string
	{
		return $this->html;
	}
}


text:
package org.hibernate.validator.test.constraints.impl;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.constraints.DecimalMin;

import org.testng.annotations.Test;

import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.cfg.defs.DecimalMaxDef;
import org.hibernate.validator.cfg.defs.DecimalMinDef;
import org.hibernate.validator.testutil.TestForIssue;
import org.hibernate.validator.testutil.ValidatorUtil;

import static java.lang.annotation.ElementType.FIELD;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertCorrectConstraintTypes;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertNumberOfViolations;

/**
 * @author Hardy Ferentschik
 */
public class DecimalMinMaxValidatorBoundaryTest {
	private Double d;

	@Test
	public void testDecimalMinValue() {
		ConstraintMapping mapping = new ConstraintMapping();
		mapping.type( DecimalMinMaxValidatorBoundaryTest.class )
				.property( "d", FIELD )
				.constraint( new DecimalMinDef().value( "0.100000000000000005" ) );
		Validator validator = ValidatorUtil.getValidatorForProgrammaticMapping( mapping );

		this.d = 0.1;

		Set<ConstraintViolation<DecimalMinMaxValidatorBoundaryTest>> constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 1 );
		assertCorrectConstraintTypes( constraintViolations, DecimalMin.class );
	}

	@Test
	public void testDecimalMaxValue() {
		ConstraintMapping mapping = new ConstraintMapping();
		mapping.type( DecimalMinMaxValidatorBoundaryTest.class )
				.property( "d", FIELD )
				.constraint( new DecimalMaxDef().value( "0.1" ) );

		Validator validator = ValidatorUtil.getValidatorForProgrammaticMapping( mapping );

		this.d = 0.1;

		Set<ConstraintViolation<DecimalMinMaxValidatorBoundaryTest>> constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 0 );
	}

	@Test
	@TestForIssue(jiraKey = "HV-508")
	public void testDoubleTrouble() {
		ConstraintMapping mapping = new ConstraintMapping();
		mapping.type( DecimalMinMaxValidatorBoundaryTest.class )
				.property( "d", FIELD )
				.constraint( new DecimalMaxDef().value( "1.2" ) );

		Validator validator = ValidatorUtil.getValidatorForProgrammaticMapping( mapping );

		this.d = 1.0;
		Set<ConstraintViolation<DecimalMinMaxValidatorBoundaryTest>> constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 0 );

		this.d = 1.1;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 0 );

		this.d = 1.19;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 0 );

		this.d = 1.20;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 0 );

		this.d = 1.3;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 1 );

		this.d = 1.51;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 1 );

		this.d = 1.9;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 1 );

		this.d = 2.000000001;
		constraintViolations = validator.validate( this );
		assertNumberOfViolations( constraintViolations, 1 );
	}
}


text:
package nl.codecentric.jenkins.appd.rest.types;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * POJO object for unmarshalling JSON data from the AppDynamics REST interface.
 * Maps to the following structure (part of {@link MetricData}:
 *
 *     "current": 19,
 *     "max": 54104,
 *     "min": 0,
 *     "startTimeInMillis": 1356877200000,
 *     "value": 6
 *
 *     ==> The 'value' field contains the actual value requested.
 */
public class MetricValues {
  private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.mediumDateTime();

  private Integer current;
  private Integer max;
  private Integer min;
  private Long startTimeInMillis;
  private Integer value;
  private Integer sum;
  private Integer count;
  private Double standardDeviation;
  private Integer occurrences;
  private Boolean useRange;

  public Integer getCurrent() {
    return current;
  }

  public void setCurrent(Integer current) {
    this.current = current;
  }

  public Integer getMax() {
    return max;
  }

  public void setMax(Integer max) {
    this.max = max;
  }

  public Integer getMin() {
    return min;
  }

  public void setMin(Integer min) {
    this.min = min;
  }

  public Long getStartTimeInMillis() {
    return startTimeInMillis;
  }

  public void setStartTimeInMillis(Long startTimeInMillis) {
    this.startTimeInMillis = startTimeInMillis;
  }

  public String getFormattedTime() {
    return DATE_TIME_FORMATTER.print(this.startTimeInMillis);
  }

  public Integer getValue() {
    return value;
  }

  public void setValue(Integer value) {
    this.value = value;
  }

  public Integer getSum() {
    return sum;
  }

  public void setSum(final Integer sum) {
    this.sum = sum;
  }

  public Integer getCount() {
    return count;
  }

  public void setCount(final Integer count) {
    this.count = count;
  }

  public Double getStandardDeviation() {
    return standardDeviation;
  }

  public void setStandardDeviation(final Double standardDeviation) {
    this.standardDeviation = standardDeviation;
  }

  public Integer getOccurrences() {
    return occurrences;
  }

  public void setOccurrences(final Integer occurrences) {
    this.occurrences = occurrences;
  }

  public Boolean getUseRange() {
    return useRange;
  }

  public void setUseRange(final Boolean useRange) {
    this.useRange = useRange;
  }
}


text:
#include "jvmrunner.h"

/**
 * Loads the configuration file, looking for the properties:
 *  * JVM_Location - 1      - Path to the Java virtual machine library.
 *  * Extra_Lib    - 0 .. * - List of extra JAR libraries to load to add to
 *                            classpath.
 *  * Max_Memory   -        - The maximum heap memory to set on the Java
 *                            machine (-Xmx JVM option) in megabytes.
 *
 * @return true if successful, false otherwise
 */
int loadConfig(void)
{
	char buf[1024], prop[1024], *line, *val;
	FILE *config, *jvmPath;

	memset(buf, 0, 1024);

	if ((config = fopen(CONFIG_FILE, "r")) == NULL)
	{
		logMessage("ERROR: Unable to open configuration file %s.\n", CONFIG_FILE);
		perror("Failed to open configuration file because");
		return 0;
	}
	logMessage("NORMAL: Opened log file '%s' successfully.\n", CONFIG_FILE);

	while (fgets(buf, 1023, config) != NULL)
	{
		line = buf;
		memset(prop, 0, 1024);

		line = trim(line);
		if (strlen(line) == 0) continue; /* Empty line.    */
		if (line[0] == '#') continue;    /* Comment line. */

		val = line;
		/* The ini format prop to value delimiter is an equal sign. */
		while (*val != '=' && *val != '\0') val++;
		if (*val == '\0')
		{
			logMessage("NORMAL: No value for prop %s.\n", line);
			continue;
		}

		strncpy(prop, line, val - line);
		trim(prop);
		trim(val);
		val = val + 1;                               /* Equals sign. */
		while (*val != '\0' && isspace(*val)) val++; /* Remaining left whitespace. */

		if (strcmp("JVM_Location", prop) == 0)
		{
			jvmSo = (char *)malloc(sizeof(char) * (strlen(val) + 1));
			memset(jvmSo, 0, strlen(val) + 1);
			strcpy(jvmSo, val);
			logMessage("JVM location is '%s'.\n", jvmSo);
		}
		else if (strcmp("Extra_Lib", prop) == 0)
		{
			if (classPathExt == NULL)
			{
				classPathExt = (char *)malloc(strlen(val) + 1);
				memset(classPathExt, 0, strlen(val) + 1);
				strcat(classPathExt, val);
			}
			else
			{
				char *tmp = (char *)malloc(sizeof(char) * (strlen(val) + 1 + strlen(classPathExt)));
				memset(tmp, 0, strlen(val) + 1 + strlen(classPathExt));
				strcpy(tmp, classPathExt);
				strcat(tmp, CLASS_PATH_DELIM);
				strcat(tmp, val);
				free(classPathExt);
				classPathExt = tmp;
			}
		}
		else if (strcmp("Max_Memory", prop) == 0)
		{
		    int len = 7 + strlen(val);
			maxHeap = (char *)malloc(sizeof(char) * len);
			memset(maxHeap, 0, len);
			strcat(maxHeap, "-Xmx");
			strcat(maxHeap, val);
			*(maxHeap + 4 + strlen(val)) = 'm';
		}
		else
		{
			logMessage("WARNING: Unknown property %s.\n", prop);
		}
	}

#ifdef WIN32
	/* If on Windows attempt to use the registry to determine if Java is installed,
	 * what version and where the runtime DLL is installed. The keys used are:
	 *    - [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion]
	 *    - [HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6\RuntimeLib] */
	if (jvmSo == NULL)
	{
		HKEY regKey;
		char regData[FILENAME_MAX], *clstart;
		DWORD regDataSize = FILENAME_MAX, err;
		float version;

		if ((err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\JavaSoft\\Java Runtime Environment", 0, KEY_READ, &regKey)) == ERROR_SUCCESS &&
			(err = RegQueryValueEx(regKey, "CurrentVersion", NULL, NULL, regData, &regDataSize)) == ERROR_SUCCESS)
		{
			RegCloseKey(regKey);

			version = atof(regData);
			if (atof(regData) >= 1.6)
			{
				/* Version is installed and OK, so now need to find the RuntimeDLL location. */
				regDataSize = FILENAME_MAX;
				if ((err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.6", 0, KEY_READ, &regKey)) == ERROR_SUCCESS &&
					(err = RegQueryValueEx(regKey, "RuntimeLib", NULL, NULL, regData, &regDataSize)) == ERROR_SUCCESS &&
					regDataSize > 0)
				{
					regData[regDataSize + 1] = '\0';
					jvmSo = (char *)malloc(strlen(regData));
					strcpy(jvmSo, regData);
					logMessage("NORMAL: The detected Java runtime library location is '%s'.\n", jvmSo);
					RegCloseKey(regKey);

#ifdef _WIN64
					/* The Sun Java 6 (v26) sets the RuntimeLib registry key to
					 * the 'client' VM, but no client VM is actually installed.
					 * So, we are putting a hack to make change it to the server
					 * VM. */
					if (clstart = strstr(jvmSo, "client"))
					{
						memcpy(clstart, "server", 6);
						logMessage("QUIRK: Changed to using server JVM as there is no client JVM installed on 64bit Windows.");
						logMessage("New Java runtime library location is '%s'.\n", jvmSo);
					}
#endif
				}
			}
			else
			{
				logMessage("ERROR: The version of Java you have installed (%.2f) is too old. It must be at least version 1.6.", atof(regData));
			}
		}
		else
		{
			logMessage("ERROR: Failed to read registry key (HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment"
				"\\CurrentVersion). Error code %i.\n", err);
		}
	}
#endif
	/* If the JVM location still isn't found, use an environment variable to
	 * attempt to locate the JVM library. */
	if (jvmSo == NULL && (jvmSo = getenv(JVM_SO_ENV)) == NULL)
	{
		logMessage("ERROR: The JVM location was not found.\n");
		return 0;
	}
	else if ((jvmPath = fopen(jvmSo, "r")) == NULL)
	{
		logMessage("ERROR: Unable to use configured JVM location '%s' as the file does not exist.\n", jvmSo);
		perror("Failed opening JVM library");
		free(jvmSo);
		jvmSo = NULL;
		return 0;
	}

	logMessage("NORMAL: Using '%s' as the JVM to load.\n", jvmSo);
	fclose(jvmPath);
	return 1;
}

/**
 * Generates the classpath argument to provide to the java virtual machine.
 * The classpath contains:
 *
 * 1) The rig client jar which is in the current working directory.
 * 2) The configured JAR libraries.
 * 3) The JARs in the 'lib/' folder.
 *
 * @return true if successful
 */
int generateClassPath(void)
{
	char currentDir[FILENAME_MAX];

	memset(currentDir, 0, FILENAME_MAX);
	if (getCWDir(currentDir, sizeof(currentDir)) == NULL)
	{
		logMessage("ERROR: Unable to detect current working directory, failing...\n");
		return 0;
	}

	classPath = (char *)malloc(strlen(CLASS_PATH) + strlen(currentDir) + 2 + strlen(JAR_FILE));
	strcpy(classPath, CLASS_PATH);

	/* Rig Client library. */
	strcat(classPath, currentDir);
	strcat(classPath, "/");
	strcat(classPath, JAR_FILE);

	/* Configured extension libraries. */
	if (classPathExt != NULL)
	{
		classPath = (char *)realloc(classPath, strlen(classPath) + 1 + strlen(classPathExt));
		strcat(classPath, CLASS_PATH_DELIM);
		strcat(classPath, classPathExt);
	}

	logMessage("NORMAL: Class path argument for Java virtual machine is '%s'.\n", classPath);
	return 1;
}

/**
 * Starts the Java virual machine.
 *
 * @return true if successful, false otherwise
 */
int startJVM()
{
	JavaVMInitArgs vm_args;
	JavaVMOption *options;
	jint res;
	JNIEnv *env;
	jclass clazz;
	jmethodID method;

#ifdef WIN32
	HINSTANCE hVM;
#else
	void *libVM;
#endif

	if (maxHeap == NULL)
	{
	    options = (JavaVMOption *) malloc(sizeof(JavaVMOption) * 2);
	}
	else
	{
		options = (JavaVMOption *) malloc(sizeof(JavaVMOption) * 3);
	}

	/* Set up Java options. */
	options[0].optionString = classPath; /* Sets the Java classpath. */
	options[1].optionString = "-Xrs";    /* Set Java to not use a signal handler, (we use our own). */
	if (maxHeap != NULL)
	{
		options[2].optionString = maxHeap;
	}

	vm_args.options = options;
	vm_args.nOptions = maxHeap == NULL ? 2 : 3;
	vm_args.ignoreUnrecognized = JNI_FALSE;
	vm_args.version = JNI_VERSION_1_4;

	/* Load the JVM library and find the JNI_CreateJavaVM function. */
#ifdef WIN32
	SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
	hVM = LoadLibrary(jvmSo);
	if (hVM == NULL)
	{
		char *pch = jvmSo, *bch = NULL, *javaBin;

		/* Add the Java installation bin directory to the DLL search path so msvcr71.dll
		 * can be loaded when java.dll is loaded. See Java bug #6509291. */
		while ((pch = strstr(pch, "bin")) != NULL) bch = pch++;
		if (bch == NULL)
		{
			logMessage("ERROR: Unable to find 'bin/' directory in the Java installaion directory. This is "
				       "most likely a bug caused by a change in the Java installation layout. Please "
					   "report this with the Java version in use.");
			return 0;
		}

		javaBin = (char *) malloc(bch - jvmSo + 5);
		memset(javaBin, 0, bch - jvmSo + 5);
		strncpy(javaBin, jvmSo, bch - jvmSo);
		strcat(javaBin, "bin");

		logMessage("NORMAL: Adding '%s' to the DLL search path.\n");
		SetDllDirectory(javaBin);
		hVM = LoadLibraryEx(jvmSo, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
		if (hVM == NULL)
		{
			logMessage("ERROR: Unable to load library %s, error code %i.\n", jvmSo, GetLastError());
			return 0;
		}
	}
	createJVM = (CreateJavaVM)GetProcAddress(hVM, "JNI_CreateJavaVM");
#else
	libVM = dlopen(jvmSo, RTLD_LAZY);
	if (libVM == NULL)
	{
		logMessage("ERROR: Unable to load library %s.\n", jvmSo);
		perror("Error loading JVM library");
		return 0;
	}
	createJVM = (CreateJavaVM)dlsym(libVM, "JNI_CreateJavaVM");
#endif

	/* Create the JVM. */
	res = createJVM(&vm, (void **)&env, &vm_args);
	if (res < 0)
	{
		logMessage("ERROR: Failed to create JVM, response code is %i.\n", res);
		return 0;
	}
	logMessage("NORMAL: Successfully created Java virtual machine.\n");

	/* Find the start up class. */
	if ((clazz = (*env)->FindClass(env, CLASS_NAME)) == NULL)
	{
		logMessage("ERROR: Unable to find class %s.\n", CLASS_NAME);
		return 0;
	}

	/* Find start up method and invoke it. */
	if ((method = (*env)->GetStaticMethodID(env, clazz, STARTUP_METHOD, "()V")) == NULL)
	{
		logMessage("BUG: Unable to find method %s in class %s.\n", STARTUP_METHOD, CLASS_NAME);
		return 0;
	}
	(*env)->CallStaticVoidMethod(env, clazz, method, NULL);

	if ((*env)->ExceptionCheck(env))
	{
		logMessage("BUG: Exception thrown starting up rig client (called method %s on %s).\n", STARTUP_METHOD, CLASS_NAME);
		return 0;
	}

	return 1;
}

/**
 * Shuts down the Java virtual machine.
 *
 * @return true if successful, false otherwise
 */
int shutDownJVM()
{
	JNIEnv *env;
	jclass clazz;
	jmethodID method;

	(*vm)->AttachCurrentThread(vm, (void **)&env, NULL);

	clazz = (*env)->FindClass(env, CLASS_NAME);
	if ((method = (*env)->GetStaticMethodID(env, clazz, SHUTDOWN_METHOD, "()V")) == NULL)
	{
		logMessage("BUG: Unable to find shutdown method %s in class %s.\n", SHUTDOWN_METHOD, CLASS_NAME);
		return 0;
	}

	logMessage("NORMAL: Calling shutdown...\n");
	(*env)->CallStaticVoidMethod(env, clazz, method, NULL);
	if ((*env)->ExceptionCheck(env))
	{
		logMessage("BUG: Exception thrown shutting down rig client.\n");
		return 0;
	}

	return 1;
}
/**
 * Logs messages to a file. This function has the same format as
 * 'printf'.
 *
 * @param *fmt format string
 * @param ... format arguments
 */
void logMessage(char *fmt, ...)
{
	static FILE* logFile;
	static int prevErr = 0;
	va_list argp;

	if (logFile == NULL)
	{
		logFile = fopen(LOG_FILE, "a");
		if (logFile == NULL && !prevErr)
		{
			printf("Unable to open log file %s.\n", LOG_FILE);
			perror("Log file error");
			prevErr = 1;
			return;
		}
	}

	if (logFile != NULL)
	{
		va_start(argp, fmt);
		vfprintf(logFile, fmt, argp);
		va_end(argp);
	}
	else
	{
		va_start(argp, fmt);
		vprintf(fmt, argp);
		va_end(argp);
	}

	fflush(logFile);
}

/**
 * Trims leading and trailing whitespace from a string.
 *
 * @param *tmp string to trim
 */
char *trim(char *tmp)
{
	char *end;

	/* Trim leading whitespace. */
	while (*tmp != '\0' && isspace(*tmp)) tmp++;

	/* Trim trailing whitespace. */
	end = tmp + strlen(tmp) - 1;
	while (end > tmp && isspace(*end)) end--;
	*(end + 1) = '\0';

	return tmp;
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.storm.generated;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum LogLevelAction implements org.apache.thrift.TEnum {
  UNCHANGED(1),
  UPDATE(2),
  REMOVE(3);

  private final int value;

  private LogLevelAction(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static LogLevelAction findByValue(int value) {
    switch (value) {
      case 1:
        return UNCHANGED;
      case 2:
        return UPDATE;
      case 3:
        return REMOVE;
      default:
        return null;
    }
  }
}


text:
/*
 * 	Author: David B. Golub, Carnegie Mellon University
 *	Date:	7/90
 */

/*
 * Commands to run process.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/kdb.h>
#include <sys/proc.h>

#include <machine/kdb.h>
#include <machine/pcb.h>

#include <vm/vm.h>

#include <ddb/ddb.h>
#include <ddb/db_break.h>
#include <ddb/db_access.h>

static int	db_run_mode;
#define	STEP_NONE	0
#define	STEP_ONCE	1
#define	STEP_RETURN	2
#define	STEP_CALLT	3
#define	STEP_CONTINUE	4
#define	STEP_INVISIBLE	5
#define	STEP_COUNT	6

static boolean_t	db_sstep_print;
static int		db_loop_count;
static int		db_call_depth;

int		db_inst_count;
int		db_load_count;
int		db_store_count;

#ifndef db_set_single_step
void db_set_single_step(void);
#endif
#ifndef db_clear_single_step
void db_clear_single_step(void);
#endif

#ifdef SOFTWARE_SSTEP
db_breakpoint_t	db_not_taken_bkpt = 0;
db_breakpoint_t	db_taken_bkpt = 0;
#endif

boolean_t
db_stop_at_pc(boolean_t *is_breakpoint)
{
	register db_addr_t	pc;
	register db_breakpoint_t bkpt;

	pc = PC_REGS();
#ifdef SOFTWARE_SSTEP
	if ((db_not_taken_bkpt != 0 && pc == db_not_taken_bkpt->address)
	    || (db_taken_bkpt != 0 && pc == db_taken_bkpt->address))
		*is_breakpoint = FALSE;
#endif

	db_clear_single_step();
	db_clear_breakpoints();
	db_clear_watchpoints();

#ifdef	FIXUP_PC_AFTER_BREAK
	if (*is_breakpoint) {
	    /*
	     * Breakpoint trap.  Fix up the PC if the
	     * machine requires it.
	     */
	    FIXUP_PC_AFTER_BREAK
	    pc = PC_REGS();
	}
#endif

	/*
	 * Now check for a breakpoint at this address.
	 */
	bkpt = db_find_breakpoint_here(pc);
	if (bkpt) {
	    if (--bkpt->count == 0) {
		bkpt->count = bkpt->init_count;
		*is_breakpoint = TRUE;
		return (TRUE);	/* stop here */
	    }
	} else if (*is_breakpoint) {
#ifdef BKPT_SKIP
		BKPT_SKIP;
#endif
	}

	*is_breakpoint = FALSE;

	if (db_run_mode == STEP_INVISIBLE) {
	    db_run_mode = STEP_CONTINUE;
	    return (FALSE);	/* continue */
	}
	if (db_run_mode == STEP_COUNT) {
	    return (FALSE); /* continue */
	}
	if (db_run_mode == STEP_ONCE) {
	    if (--db_loop_count > 0) {
		if (db_sstep_print) {
		    db_printf("\t\t");
		    db_print_loc_and_inst(pc);
		    db_printf("\n");
		}
		return (FALSE);	/* continue */
	    }
	}
	if (db_run_mode == STEP_RETURN) {
	    /* continue until matching return */
	    db_expr_t ins;

	    ins = db_get_value(pc, sizeof(int), FALSE);
	    if (!inst_trap_return(ins) &&
		(!inst_return(ins) || --db_call_depth != 0)) {
		if (db_sstep_print) {
		    if (inst_call(ins) || inst_return(ins)) {
			register int i;

			db_printf("[after %6d]     ", db_inst_count);
			for (i = db_call_depth; --i > 0; )
			    db_printf("  ");
			db_print_loc_and_inst(pc);
			db_printf("\n");
		    }
		}
		if (inst_call(ins))
		    db_call_depth++;
		return (FALSE);	/* continue */
	    }
	}
	if (db_run_mode == STEP_CALLT) {
	    /* continue until call or return */
	    db_expr_t ins;

	    ins = db_get_value(pc, sizeof(int), FALSE);
	    if (!inst_call(ins) &&
		!inst_return(ins) &&
		!inst_trap_return(ins)) {
		return (FALSE);	/* continue */
	    }
	}
	db_run_mode = STEP_NONE;
	return (TRUE);
}

void
db_restart_at_pc(boolean_t watchpt)
{
	register db_addr_t	pc = PC_REGS();

	if ((db_run_mode == STEP_COUNT) ||
	    (db_run_mode == STEP_RETURN) ||
	    (db_run_mode == STEP_CALLT)) {
	    db_expr_t		ins;

	    /*
	     * We are about to execute this instruction,
	     * so count it now.
	     */

	    ins = db_get_value(pc, sizeof(int), FALSE);
	    db_inst_count++;
	    db_load_count += inst_load(ins);
	    db_store_count += inst_store(ins);
#ifdef	SOFTWARE_SSTEP
	    /* XXX works on mips, but... */
	    if (inst_branch(ins) || inst_call(ins)) {
		ins = db_get_value(next_instr_address(pc,1),
				   sizeof(int), FALSE);
		db_inst_count++;
		db_load_count += inst_load(ins);
		db_store_count += inst_store(ins);
	    }
#endif	/* SOFTWARE_SSTEP */
	}

	if (db_run_mode == STEP_CONTINUE) {
	    if (watchpt || db_find_breakpoint_here(pc)) {
		/*
		 * Step over breakpoint/watchpoint.
		 */
		db_run_mode = STEP_INVISIBLE;
		db_set_single_step();
	    } else {
		db_set_breakpoints();
		db_set_watchpoints();
	    }
	} else {
	    db_set_single_step();
	}
}

#ifdef	SOFTWARE_SSTEP
/*
 *	Software implementation of single-stepping.
 *	If your machine does not have a trace mode
 *	similar to the vax or sun ones you can use
 *	this implementation, done for the mips.
 *	Just define the above conditional and provide
 *	the functions/macros defined below.
 *
 * extern boolean_t
 *	inst_branch(),		returns true if the instruction might branch
 * extern unsigned
 *	branch_taken(),		return the address the instruction might
 *				branch to
 *	db_getreg_val();	return the value of a user register,
 *				as indicated in the hardware instruction
 *				encoding, e.g. 8 for r8
 *
 * next_instr_address(pc,bd)	returns the address of the first
 *				instruction following the one at "pc",
 *				which is either in the taken path of
 *				the branch (bd==1) or not.  This is
 *				for machines (mips) with branch delays.
 *
 *	A single-step may involve at most 2 breakpoints -
 *	one for branch-not-taken and one for branch taken.
 *	If one of these addresses does not already have a breakpoint,
 *	we allocate a breakpoint and save it here.
 *	These breakpoints are deleted on return.
 */

void
db_set_single_step(void)
{
	db_addr_t pc = PC_REGS(), brpc;
	unsigned inst;

	/*
	 *	User was stopped at pc, e.g. the instruction
	 *	at pc was not executed.
	 */
	inst = db_get_value(pc, sizeof(int), FALSE);
	if (inst_branch(inst) || inst_call(inst) || inst_return(inst)) {
		brpc = branch_taken(inst, pc);
		if (brpc != pc) {	/* self-branches are hopeless */
			db_taken_bkpt = db_set_temp_breakpoint(brpc);
		}
		pc = next_instr_address(pc, 1);
	}
	pc = next_instr_address(pc, 0);
	db_not_taken_bkpt = db_set_temp_breakpoint(pc);
}

void
db_clear_single_step(void)
{

	if (db_not_taken_bkpt != 0) {
		db_delete_temp_breakpoint(db_not_taken_bkpt);
		db_not_taken_bkpt = 0;
	}
	if (db_taken_bkpt != 0) {
		db_delete_temp_breakpoint(db_taken_bkpt);
		db_taken_bkpt = 0;
	}
}

#endif	/* SOFTWARE_SSTEP */

extern int	db_cmd_loop_done;

/* single-step */
/*ARGSUSED*/
void
db_single_step_cmd(addr, have_addr, count, modif)
	db_expr_t	addr;
	boolean_t	have_addr;
	db_expr_t	count;
	char *		modif;
{
	boolean_t	print = FALSE;

	if (count == -1)
	    count = 1;

	if (modif[0] == 'p')
	    print = TRUE;

	db_run_mode = STEP_ONCE;
	db_loop_count = count;
	db_sstep_print = print;
	db_inst_count = 0;
	db_load_count = 0;
	db_store_count = 0;

	db_cmd_loop_done = 1;
}

/* trace and print until call/return */
/*ARGSUSED*/
void
db_trace_until_call_cmd(db_expr_t addr, boolean_t have_addr, db_expr_t count,
    char *modif)
{
	boolean_t	print = FALSE;

	if (modif[0] == 'p')
	    print = TRUE;

	db_run_mode = STEP_CALLT;
	db_sstep_print = print;
	db_inst_count = 0;
	db_load_count = 0;
	db_store_count = 0;

	db_cmd_loop_done = 1;
}

/*ARGSUSED*/
void
db_trace_until_matching_cmd(db_expr_t addr, boolean_t have_addr,
    db_expr_t count, char *modif)
{
	boolean_t	print = FALSE;

	if (modif[0] == 'p')
	    print = TRUE;

	db_run_mode = STEP_RETURN;
	db_call_depth = 1;
	db_sstep_print = print;
	db_inst_count = 0;
	db_load_count = 0;
	db_store_count = 0;

	db_cmd_loop_done = 1;
}

/* continue */
/*ARGSUSED*/
void
db_continue_cmd(db_expr_t addr, boolean_t have_addr, db_expr_t count,
    char *modif)
{
	if (modif[0] == 'c')
	    db_run_mode = STEP_COUNT;
	else
	    db_run_mode = STEP_CONTINUE;
	db_inst_count = 0;
	db_load_count = 0;
	db_store_count = 0;

	db_cmd_loop_done = 1;
}