text:
import request from 'request';
import when from 'when';
import fs from 'fs';
import config from 'lib/config';
import guard from 'when/guard';
import https from 'https';
import moment from 'moment';
import poll from 'when/poll';

const host = config.hostPrefix()

var pool = new https.Agent({keepAlive: true, maxSockets: 25, maxFreeSockets: 2, ca: fs.readFileSync('./my-ca.crt') });
const options = {
  agent: pool,
  agentOptions: { ca: fs.readFileSync('./my-ca.crt') }
}

if( config.iracingServiceToken())
  options.authorization = config.iracingServiceToken()

const _baseRequest = request.defaults(options)

function requestPromise(opts) {
  return when.promise((res, rej) => {
    $logger.info('> ' + opts.method + ' ' + opts.uri)
    _baseRequest(opts, (err, response, body) => {
      if(err) {
        $logger.error('! ' + opts.method + ' ' + opts.uri)
        return rej(err)
      }

      $logger.info('< ' + opts.method + ' ' + opts.uri + ' ' + response.statusCode)
      res(response)
    })
  })
}

const baseRequest = guard(guard.n(30), requestPromise)

function retryTimes(f, count = 3) {
  return f()
    .catch( err => when(null).delay(1000).then( () => {
      if (count < 0)
        throw new Error(err.stack);
      else
        return retryTimes(f, count - 1)
    }))
}

const inMemoryCache = new Map()

setInterval(() => {
  try {
    for(let item of inMemoryCache) {
      let expireStamp = item[1].response.headers['expires']
      if( !expireStamp )
        inMemoryCache.delete(item[0])
      else {
        let expiresAt = moment(new Date(expireStamp))
        let age = moment.duration(expiresAt.diff(moment())).asSeconds()
        if( age <= 0 )
          inMemoryCache.delete(item[0])
      }
    }
  } catch(err) {
    $logger.error(err.stack)
  }
}, 5000)

let sweeping = false

setInterval(() => {
  try {
    if(!sweeping && inMemoryCache.size <= 1000)
      return

    sweeping = true
    let orderedItems = Array.from(inMemoryCache).sort((a, b) => a[1].accessedAt - b[1].accessedAt)
    let count = inMemoryCache.size - 1001
    let index = 0
    poll(() => inMemoryCache.delete(orderedItems[index++][0]), 1, () => count-- <= 0)
      .then(() => sweeping = false)
      .catch(() => sweeping = false)

  } catch(err) {
    $logger.error(err.stack)
    sweeping = false
  }
}, 1000)

function get(url) {

  let path = url.match(/^http/) ? url : host + url

  const DEBUG=false
  if( DEBUG )
    path = path.replace('.net.dev', '.net').replace('.net', '.net.dev')

  const cachedHit = inMemoryCache.get(path)
  if(cachedHit)
    return when(cachedHit.response)

  const options = {
    uri: path,
    json: true,
    method: 'GET'
  }

  return retryTimes(() => baseRequest(options), 3)
    .tap(response => inMemoryCache.set(path, { response, accessedAt: moment() }))

}

export default { get: get }


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace TwitchCSharp.Models
{
    [JsonObject("videos")]
    public class Video : TwitchResponse
    {
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("description")]
        public string Description { get; set; }
        [JsonProperty("broadcast_id")]
        public long BroadcastId { get; set; }
        [JsonProperty("status")]
        public string Status { get; set; }
        [JsonProperty("_id")]
        public string Id { get; set; }
        [JsonProperty("tag_list")]
        public string TagList { get; set; }
        [JsonProperty("recorded_at")]
        public DateTime RecordedAt { get; set; }
        [JsonProperty("game")]
        public string Game { get; set; }
        [JsonProperty("length")]
        public long Length { get; set; }
        [JsonProperty("preview")]
        public string Preview { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
        [JsonProperty("views")]
        public long Views { get; set; }
        [JsonProperty("broadcast_type")]
        public string BroadcastType { get; set; }
        [JsonProperty("channel")]
        public Channel Channel { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/gpio/driver.h>
#include <linux/acpi.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/platform_device.h>

#define CHV_INTSTAT			0x300
#define CHV_INTMASK			0x380

#define FAMILY_PAD_REGS_OFF		0x4400
#define FAMILY_PAD_REGS_SIZE		0x400
#define MAX_FAMILY_PAD_GPIO_NO		15
#define GPIO_REGS_SIZE			8

#define CHV_PADCTRL0			0x000
#define CHV_PADCTRL0_INTSEL_SHIFT	28
#define CHV_PADCTRL0_INTSEL_MASK	(0xf << CHV_PADCTRL0_INTSEL_SHIFT)
#define CHV_PADCTRL0_TERM_UP		BIT(23)
#define CHV_PADCTRL0_TERM_SHIFT		20
#define CHV_PADCTRL0_TERM_MASK		(7 << CHV_PADCTRL0_TERM_SHIFT)
#define CHV_PADCTRL0_TERM_20K		1
#define CHV_PADCTRL0_TERM_5K		2
#define CHV_PADCTRL0_TERM_1K		4
#define CHV_PADCTRL0_PMODE_SHIFT	16
#define CHV_PADCTRL0_PMODE_MASK		(0xf << CHV_PADCTRL0_PMODE_SHIFT)
#define CHV_PADCTRL0_GPIOEN		BIT(15)
#define CHV_PADCTRL0_GPIOCFG_SHIFT	8
#define CHV_PADCTRL0_GPIOCFG_MASK	(7 << CHV_PADCTRL0_GPIOCFG_SHIFT)
#define CHV_PADCTRL0_GPIOCFG_GPIO	0
#define CHV_PADCTRL0_GPIOCFG_GPO	1
#define CHV_PADCTRL0_GPIOCFG_GPI	2
#define CHV_PADCTRL0_GPIOCFG_HIZ	3
#define CHV_PADCTRL0_GPIOTXSTATE	BIT(1)
#define CHV_PADCTRL0_GPIORXSTATE	BIT(0)

#define CHV_PADCTRL1			0x004
#define CHV_PADCTRL1_CFGLOCK		BIT(31)
#define CHV_PADCTRL1_INVRXTX_SHIFT	4
#define CHV_PADCTRL1_INVRXTX_MASK	(0xf << CHV_PADCTRL1_INVRXTX_SHIFT)
#define CHV_PADCTRL1_INVRXTX_TXENABLE	(2 << CHV_PADCTRL1_INVRXTX_SHIFT)
#define CHV_PADCTRL1_ODEN		BIT(3)
#define CHV_PADCTRL1_INVRXTX_RXDATA	(4 << CHV_PADCTRL1_INVRXTX_SHIFT)
#define CHV_PADCTRL1_INTWAKECFG_MASK	7
#define CHV_PADCTRL1_INTWAKECFG_FALLING	1
#define CHV_PADCTRL1_INTWAKECFG_RISING	2
#define CHV_PADCTRL1_INTWAKECFG_BOTH	3
#define CHV_PADCTRL1_INTWAKECFG_LEVEL	4

/**
 * struct chv_alternate_function - A per group or per pin alternate function
 * @pin: Pin number (only used in per pin configs)
 * @mode: Mode the pin should be set in
 * @invert_oe: Invert OE for this pin
 */
struct chv_alternate_function {
	unsigned pin;
	u8 mode;
	bool invert_oe;
};

/**
 * struct chv_pincgroup - describes a CHV pin group
 * @name: Name of the group
 * @pins: An array of pins in this group
 * @npins: Number of pins in this group
 * @altfunc: Alternate function applied to all pins in this group
 * @overrides: Alternate function override per pin or %NULL if not used
 * @noverrides: Number of per pin alternate function overrides if
 *              @overrides != NULL.
 */
struct chv_pingroup {
	const char *name;
	const unsigned *pins;
	size_t npins;
	struct chv_alternate_function altfunc;
	const struct chv_alternate_function *overrides;
	size_t noverrides;
};

/**
 * struct chv_function - A CHV pinmux function
 * @name: Name of the function
 * @groups: An array of groups for this function
 * @ngroups: Number of groups in @groups
 */
struct chv_function {
	const char *name;
	const char * const *groups;
	size_t ngroups;
};

/**
 * struct chv_gpio_pinrange - A range of pins that can be used as GPIOs
 * @base: Start pin number
 * @npins: Number of pins in this range
 */
struct chv_gpio_pinrange {
	unsigned base;
	unsigned npins;
};

/**
 * struct chv_community - A community specific configuration
 * @uid: ACPI _UID used to match the community
 * @pins: All pins in this community
 * @npins: Number of pins
 * @groups: All groups in this community
 * @ngroups: Number of groups
 * @functions: All functions in this community
 * @nfunctions: Number of functions
 * @ngpios: Number of GPIOs in this community
 * @gpio_ranges: An array of GPIO ranges in this community
 * @ngpio_ranges: Number of GPIO ranges
 * @ngpios: Total number of GPIOs in this community
 */
struct chv_community {
	const char *uid;
	const struct pinctrl_pin_desc *pins;
	size_t npins;
	const struct chv_pingroup *groups;
	size_t ngroups;
	const struct chv_function *functions;
	size_t nfunctions;
	const struct chv_gpio_pinrange *gpio_ranges;
	size_t ngpio_ranges;
	size_t ngpios;
};

struct chv_pin_context {
	u32 padctrl0;
	u32 padctrl1;
};

/**
 * struct chv_pinctrl - CHV pinctrl private structure
 * @dev: Pointer to the parent device
 * @pctldesc: Pin controller description
 * @pctldev: Pointer to the pin controller device
 * @chip: GPIO chip in this pin controller
 * @regs: MMIO registers
 * @lock: Lock to serialize register accesses
 * @intr_lines: Stores mapping between 16 HW interrupt wires and GPIO
 *		offset (in GPIO number space)
 * @community: Community this pinctrl instance represents
 *
 * The first group in @groups is expected to contain all pins that can be
 * used as GPIOs.
 */
struct chv_pinctrl {
	struct device *dev;
	struct pinctrl_desc pctldesc;
	struct pinctrl_dev *pctldev;
	struct gpio_chip chip;
	void __iomem *regs;
	raw_spinlock_t lock;
	unsigned intr_lines[16];
	const struct chv_community *community;
	u32 saved_intmask;
	struct chv_pin_context *saved_pin_context;
};

#define ALTERNATE_FUNCTION(p, m, i)		\
	{					\
		.pin = (p),			\
		.mode = (m),			\
		.invert_oe = (i),		\
	}

#define PIN_GROUP(n, p, m, i)			\
	{					\
		.name = (n),			\
		.pins = (p),			\
		.npins = ARRAY_SIZE((p)),	\
		.altfunc.mode = (m),		\
		.altfunc.invert_oe = (i),	\
	}

#define PIN_GROUP_WITH_OVERRIDE(n, p, m, i, o)	\
	{					\
		.name = (n),			\
		.pins = (p),			\
		.npins = ARRAY_SIZE((p)),	\
		.altfunc.mode = (m),		\
		.altfunc.invert_oe = (i),	\
		.overrides = (o),		\
		.noverrides = ARRAY_SIZE((o)),	\
	}

#define FUNCTION(n, g)				\
	{					\
		.name = (n),			\
		.groups = (g),			\
		.ngroups = ARRAY_SIZE((g)),	\
	}

#define GPIO_PINRANGE(start, end)		\
	{					\
		.base = (start),		\
		.npins = (end) - (start) + 1,	\
	}

static const struct pinctrl_pin_desc southwest_pins[] = {
	PINCTRL_PIN(0, "FST_SPI_D2"),
	PINCTRL_PIN(1, "FST_SPI_D0"),
	PINCTRL_PIN(2, "FST_SPI_CLK"),
	PINCTRL_PIN(3, "FST_SPI_D3"),
	PINCTRL_PIN(4, "FST_SPI_CS1_B"),
	PINCTRL_PIN(5, "FST_SPI_D1"),
	PINCTRL_PIN(6, "FST_SPI_CS0_B"),
	PINCTRL_PIN(7, "FST_SPI_CS2_B"),

	PINCTRL_PIN(15, "UART1_RTS_B"),
	PINCTRL_PIN(16, "UART1_RXD"),
	PINCTRL_PIN(17, "UART2_RXD"),
	PINCTRL_PIN(18, "UART1_CTS_B"),
	PINCTRL_PIN(19, "UART2_RTS_B"),
	PINCTRL_PIN(20, "UART1_TXD"),
	PINCTRL_PIN(21, "UART2_TXD"),
	PINCTRL_PIN(22, "UART2_CTS_B"),

	PINCTRL_PIN(30, "MF_HDA_CLK"),
	PINCTRL_PIN(31, "MF_HDA_RSTB"),
	PINCTRL_PIN(32, "MF_HDA_SDIO"),
	PINCTRL_PIN(33, "MF_HDA_SDO"),
	PINCTRL_PIN(34, "MF_HDA_DOCKRSTB"),
	PINCTRL_PIN(35, "MF_HDA_SYNC"),
	PINCTRL_PIN(36, "MF_HDA_SDI1"),
	PINCTRL_PIN(37, "MF_HDA_DOCKENB"),

	PINCTRL_PIN(45, "I2C5_SDA"),
	PINCTRL_PIN(46, "I2C4_SDA"),
	PINCTRL_PIN(47, "I2C6_SDA"),
	PINCTRL_PIN(48, "I2C5_SCL"),
	PINCTRL_PIN(49, "I2C_NFC_SDA"),
	PINCTRL_PIN(50, "I2C4_SCL"),
	PINCTRL_PIN(51, "I2C6_SCL"),
	PINCTRL_PIN(52, "I2C_NFC_SCL"),

	PINCTRL_PIN(60, "I2C1_SDA"),
	PINCTRL_PIN(61, "I2C0_SDA"),
	PINCTRL_PIN(62, "I2C2_SDA"),
	PINCTRL_PIN(63, "I2C1_SCL"),
	PINCTRL_PIN(64, "I2C3_SDA"),
	PINCTRL_PIN(65, "I2C0_SCL"),
	PINCTRL_PIN(66, "I2C2_SCL"),
	PINCTRL_PIN(67, "I2C3_SCL"),

	PINCTRL_PIN(75, "SATA_GP0"),
	PINCTRL_PIN(76, "SATA_GP1"),
	PINCTRL_PIN(77, "SATA_LEDN"),
	PINCTRL_PIN(78, "SATA_GP2"),
	PINCTRL_PIN(79, "MF_SMB_ALERTB"),
	PINCTRL_PIN(80, "SATA_GP3"),
	PINCTRL_PIN(81, "MF_SMB_CLK"),
	PINCTRL_PIN(82, "MF_SMB_DATA"),

	PINCTRL_PIN(90, "PCIE_CLKREQ0B"),
	PINCTRL_PIN(91, "PCIE_CLKREQ1B"),
	PINCTRL_PIN(92, "GP_SSP_2_CLK"),
	PINCTRL_PIN(93, "PCIE_CLKREQ2B"),
	PINCTRL_PIN(94, "GP_SSP_2_RXD"),
	PINCTRL_PIN(95, "PCIE_CLKREQ3B"),
	PINCTRL_PIN(96, "GP_SSP_2_FS"),
	PINCTRL_PIN(97, "GP_SSP_2_TXD"),
};

static const unsigned southwest_fspi_pins[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
static const unsigned southwest_uart0_pins[] = { 16, 20 };
static const unsigned southwest_uart1_pins[] = { 15, 16, 18, 20 };
static const unsigned southwest_uart2_pins[] = { 17, 19, 21, 22 };
static const unsigned southwest_i2c0_pins[] = { 61, 65 };
static const unsigned southwest_hda_pins[] = { 30, 31, 32, 33, 34, 35, 36, 37 };
static const unsigned southwest_lpe_pins[] = {
	30, 31, 32, 33, 34, 35, 36, 37, 92, 94, 96, 97,
};
static const unsigned southwest_i2c1_pins[] = { 60, 63 };
static const unsigned southwest_i2c2_pins[] = { 62, 66 };
static const unsigned southwest_i2c3_pins[] = { 64, 67 };
static const unsigned southwest_i2c4_pins[] = { 46, 50 };
static const unsigned southwest_i2c5_pins[] = { 45, 48 };
static const unsigned southwest_i2c6_pins[] = { 47, 51 };
static const unsigned southwest_i2c_nfc_pins[] = { 49, 52 };
static const unsigned southwest_smbus_pins[] = { 79, 81, 82 };
static const unsigned southwest_spi3_pins[] = { 76, 79, 80, 81, 82 };

/* LPE I2S TXD pins need to have invert_oe set */
static const struct chv_alternate_function southwest_lpe_altfuncs[] = {
	ALTERNATE_FUNCTION(30, 1, true),
	ALTERNATE_FUNCTION(34, 1, true),
	ALTERNATE_FUNCTION(97, 1, true),
};

/*
 * Two spi3 chipselects are available in different mode than the main spi3
 * functionality, which is using mode 1.
 */
static const struct chv_alternate_function southwest_spi3_altfuncs[] = {
	ALTERNATE_FUNCTION(76, 3, false),
	ALTERNATE_FUNCTION(80, 3, false),
};

static const struct chv_pingroup southwest_groups[] = {
	PIN_GROUP("uart0_grp", southwest_uart0_pins, 2, false),
	PIN_GROUP("uart1_grp", southwest_uart1_pins, 1, false),
	PIN_GROUP("uart2_grp", southwest_uart2_pins, 1, false),
	PIN_GROUP("hda_grp", southwest_hda_pins, 2, false),
	PIN_GROUP("i2c0_grp", southwest_i2c0_pins, 1, true),
	PIN_GROUP("i2c1_grp", southwest_i2c1_pins, 1, true),
	PIN_GROUP("i2c2_grp", southwest_i2c2_pins, 1, true),
	PIN_GROUP("i2c3_grp", southwest_i2c3_pins, 1, true),
	PIN_GROUP("i2c4_grp", southwest_i2c4_pins, 1, true),
	PIN_GROUP("i2c5_grp", southwest_i2c5_pins, 1, true),
	PIN_GROUP("i2c6_grp", southwest_i2c6_pins, 1, true),
	PIN_GROUP("i2c_nfc_grp", southwest_i2c_nfc_pins, 2, true),

	PIN_GROUP_WITH_OVERRIDE("lpe_grp", southwest_lpe_pins, 1, false,
				southwest_lpe_altfuncs),
	PIN_GROUP_WITH_OVERRIDE("spi3_grp", southwest_spi3_pins, 2, false,
				southwest_spi3_altfuncs),
};

static const char * const southwest_uart0_groups[] = { "uart0_grp" };
static const char * const southwest_uart1_groups[] = { "uart1_grp" };
static const char * const southwest_uart2_groups[] = { "uart2_grp" };
static const char * const southwest_hda_groups[] = { "hda_grp" };
static const char * const southwest_lpe_groups[] = { "lpe_grp" };
static const char * const southwest_i2c0_groups[] = { "i2c0_grp" };
static const char * const southwest_i2c1_groups[] = { "i2c1_grp" };
static const char * const southwest_i2c2_groups[] = { "i2c2_grp" };
static const char * const southwest_i2c3_groups[] = { "i2c3_grp" };
static const char * const southwest_i2c4_groups[] = { "i2c4_grp" };
static const char * const southwest_i2c5_groups[] = { "i2c5_grp" };
static const char * const southwest_i2c6_groups[] = { "i2c6_grp" };
static const char * const southwest_i2c_nfc_groups[] = { "i2c_nfc_grp" };
static const char * const southwest_spi3_groups[] = { "spi3_grp" };

/*
 * Only do pinmuxing for certain LPSS devices for now. Rest of the pins are
 * enabled only as GPIOs.
 */
static const struct chv_function southwest_functions[] = {
	FUNCTION("uart0", southwest_uart0_groups),
	FUNCTION("uart1", southwest_uart1_groups),
	FUNCTION("uart2", southwest_uart2_groups),
	FUNCTION("hda", southwest_hda_groups),
	FUNCTION("lpe", southwest_lpe_groups),
	FUNCTION("i2c0", southwest_i2c0_groups),
	FUNCTION("i2c1", southwest_i2c1_groups),
	FUNCTION("i2c2", southwest_i2c2_groups),
	FUNCTION("i2c3", southwest_i2c3_groups),
	FUNCTION("i2c4", southwest_i2c4_groups),
	FUNCTION("i2c5", southwest_i2c5_groups),
	FUNCTION("i2c6", southwest_i2c6_groups),
	FUNCTION("i2c_nfc", southwest_i2c_nfc_groups),
	FUNCTION("spi3", southwest_spi3_groups),
};

static const struct chv_gpio_pinrange southwest_gpio_ranges[] = {
	GPIO_PINRANGE(0, 7),
	GPIO_PINRANGE(15, 22),
	GPIO_PINRANGE(30, 37),
	GPIO_PINRANGE(45, 52),
	GPIO_PINRANGE(60, 67),
	GPIO_PINRANGE(75, 82),
	GPIO_PINRANGE(90, 97),
};

static const struct chv_community southwest_community = {
	.uid = "1",
	.pins = southwest_pins,
	.npins = ARRAY_SIZE(southwest_pins),
	.groups = southwest_groups,
	.ngroups = ARRAY_SIZE(southwest_groups),
	.functions = southwest_functions,
	.nfunctions = ARRAY_SIZE(southwest_functions),
	.gpio_ranges = southwest_gpio_ranges,
	.ngpio_ranges = ARRAY_SIZE(southwest_gpio_ranges),
	.ngpios = ARRAY_SIZE(southwest_pins),
};

static const struct pinctrl_pin_desc north_pins[] = {
	PINCTRL_PIN(0, "GPIO_DFX_0"),
	PINCTRL_PIN(1, "GPIO_DFX_3"),
	PINCTRL_PIN(2, "GPIO_DFX_7"),
	PINCTRL_PIN(3, "GPIO_DFX_1"),
	PINCTRL_PIN(4, "GPIO_DFX_5"),
	PINCTRL_PIN(5, "GPIO_DFX_4"),
	PINCTRL_PIN(6, "GPIO_DFX_8"),
	PINCTRL_PIN(7, "GPIO_DFX_2"),
	PINCTRL_PIN(8, "GPIO_DFX_6"),

	PINCTRL_PIN(15, "GPIO_SUS0"),
	PINCTRL_PIN(16, "SEC_GPIO_SUS10"),
	PINCTRL_PIN(17, "GPIO_SUS3"),
	PINCTRL_PIN(18, "GPIO_SUS7"),
	PINCTRL_PIN(19, "GPIO_SUS1"),
	PINCTRL_PIN(20, "GPIO_SUS5"),
	PINCTRL_PIN(21, "SEC_GPIO_SUS11"),
	PINCTRL_PIN(22, "GPIO_SUS4"),
	PINCTRL_PIN(23, "SEC_GPIO_SUS8"),
	PINCTRL_PIN(24, "GPIO_SUS2"),
	PINCTRL_PIN(25, "GPIO_SUS6"),
	PINCTRL_PIN(26, "CX_PREQ_B"),
	PINCTRL_PIN(27, "SEC_GPIO_SUS9"),

	PINCTRL_PIN(30, "TRST_B"),
	PINCTRL_PIN(31, "TCK"),
	PINCTRL_PIN(32, "PROCHOT_B"),
	PINCTRL_PIN(33, "SVIDO_DATA"),
	PINCTRL_PIN(34, "TMS"),
	PINCTRL_PIN(35, "CX_PRDY_B_2"),
	PINCTRL_PIN(36, "TDO_2"),
	PINCTRL_PIN(37, "CX_PRDY_B"),
	PINCTRL_PIN(38, "SVIDO_ALERT_B"),
	PINCTRL_PIN(39, "TDO"),
	PINCTRL_PIN(40, "SVIDO_CLK"),
	PINCTRL_PIN(41, "TDI"),

	PINCTRL_PIN(45, "GP_CAMERASB_05"),
	PINCTRL_PIN(46, "GP_CAMERASB_02"),
	PINCTRL_PIN(47, "GP_CAMERASB_08"),
	PINCTRL_PIN(48, "GP_CAMERASB_00"),
	PINCTRL_PIN(49, "GP_CAMERASB_06"),
	PINCTRL_PIN(50, "GP_CAMERASB_10"),
	PINCTRL_PIN(51, "GP_CAMERASB_03"),
	PINCTRL_PIN(52, "GP_CAMERASB_09"),
	PINCTRL_PIN(53, "GP_CAMERASB_01"),
	PINCTRL_PIN(54, "GP_CAMERASB_07"),
	PINCTRL_PIN(55, "GP_CAMERASB_11"),
	PINCTRL_PIN(56, "GP_CAMERASB_04"),

	PINCTRL_PIN(60, "PANEL0_BKLTEN"),
	PINCTRL_PIN(61, "HV_DDI0_HPD"),
	PINCTRL_PIN(62, "HV_DDI2_DDC_SDA"),
	PINCTRL_PIN(63, "PANEL1_BKLTCTL"),
	PINCTRL_PIN(64, "HV_DDI1_HPD"),
	PINCTRL_PIN(65, "PANEL0_BKLTCTL"),
	PINCTRL_PIN(66, "HV_DDI0_DDC_SDA"),
	PINCTRL_PIN(67, "HV_DDI2_DDC_SCL"),
	PINCTRL_PIN(68, "HV_DDI2_HPD"),
	PINCTRL_PIN(69, "PANEL1_VDDEN"),
	PINCTRL_PIN(70, "PANEL1_BKLTEN"),
	PINCTRL_PIN(71, "HV_DDI0_DDC_SCL"),
	PINCTRL_PIN(72, "PANEL0_VDDEN"),
};

static const struct chv_gpio_pinrange north_gpio_ranges[] = {
	GPIO_PINRANGE(0, 8),
	GPIO_PINRANGE(15, 27),
	GPIO_PINRANGE(30, 41),
	GPIO_PINRANGE(45, 56),
	GPIO_PINRANGE(60, 72),
};

static const struct chv_community north_community = {
	.uid = "2",
	.pins = north_pins,
	.npins = ARRAY_SIZE(north_pins),
	.gpio_ranges = north_gpio_ranges,
	.ngpio_ranges = ARRAY_SIZE(north_gpio_ranges),
	.ngpios = ARRAY_SIZE(north_pins),
};

static const struct pinctrl_pin_desc east_pins[] = {
	PINCTRL_PIN(0, "PMU_SLP_S3_B"),
	PINCTRL_PIN(1, "PMU_BATLOW_B"),
	PINCTRL_PIN(2, "SUS_STAT_B"),
	PINCTRL_PIN(3, "PMU_SLP_S0IX_B"),
	PINCTRL_PIN(4, "PMU_AC_PRESENT"),
	PINCTRL_PIN(5, "PMU_PLTRST_B"),
	PINCTRL_PIN(6, "PMU_SUSCLK"),
	PINCTRL_PIN(7, "PMU_SLP_LAN_B"),
	PINCTRL_PIN(8, "PMU_PWRBTN_B"),
	PINCTRL_PIN(9, "PMU_SLP_S4_B"),
	PINCTRL_PIN(10, "PMU_WAKE_B"),
	PINCTRL_PIN(11, "PMU_WAKE_LAN_B"),

	PINCTRL_PIN(15, "MF_ISH_GPIO_3"),
	PINCTRL_PIN(16, "MF_ISH_GPIO_7"),
	PINCTRL_PIN(17, "MF_ISH_I2C1_SCL"),
	PINCTRL_PIN(18, "MF_ISH_GPIO_1"),
	PINCTRL_PIN(19, "MF_ISH_GPIO_5"),
	PINCTRL_PIN(20, "MF_ISH_GPIO_9"),
	PINCTRL_PIN(21, "MF_ISH_GPIO_0"),
	PINCTRL_PIN(22, "MF_ISH_GPIO_4"),
	PINCTRL_PIN(23, "MF_ISH_GPIO_8"),
	PINCTRL_PIN(24, "MF_ISH_GPIO_2"),
	PINCTRL_PIN(25, "MF_ISH_GPIO_6"),
	PINCTRL_PIN(26, "MF_ISH_I2C1_SDA"),
};

static const struct chv_gpio_pinrange east_gpio_ranges[] = {
	GPIO_PINRANGE(0, 11),
	GPIO_PINRANGE(15, 26),
};

static const struct chv_community east_community = {
	.uid = "3",
	.pins = east_pins,
	.npins = ARRAY_SIZE(east_pins),
	.gpio_ranges = east_gpio_ranges,
	.ngpio_ranges = ARRAY_SIZE(east_gpio_ranges),
	.ngpios = ARRAY_SIZE(east_pins),
};

static const struct pinctrl_pin_desc southeast_pins[] = {
	PINCTRL_PIN(0, "MF_PLT_CLK0"),
	PINCTRL_PIN(1, "PWM1"),
	PINCTRL_PIN(2, "MF_PLT_CLK1"),
	PINCTRL_PIN(3, "MF_PLT_CLK4"),
	PINCTRL_PIN(4, "MF_PLT_CLK3"),
	PINCTRL_PIN(5, "PWM0"),
	PINCTRL_PIN(6, "MF_PLT_CLK5"),
	PINCTRL_PIN(7, "MF_PLT_CLK2"),

	PINCTRL_PIN(15, "SDMMC2_D3_CD_B"),
	PINCTRL_PIN(16, "SDMMC1_CLK"),
	PINCTRL_PIN(17, "SDMMC1_D0"),
	PINCTRL_PIN(18, "SDMMC2_D1"),
	PINCTRL_PIN(19, "SDMMC2_CLK"),
	PINCTRL_PIN(20, "SDMMC1_D2"),
	PINCTRL_PIN(21, "SDMMC2_D2"),
	PINCTRL_PIN(22, "SDMMC2_CMD"),
	PINCTRL_PIN(23, "SDMMC1_CMD"),
	PINCTRL_PIN(24, "SDMMC1_D1"),
	PINCTRL_PIN(25, "SDMMC2_D0"),
	PINCTRL_PIN(26, "SDMMC1_D3_CD_B"),

	PINCTRL_PIN(30, "SDMMC3_D1"),
	PINCTRL_PIN(31, "SDMMC3_CLK"),
	PINCTRL_PIN(32, "SDMMC3_D3"),
	PINCTRL_PIN(33, "SDMMC3_D2"),
	PINCTRL_PIN(34, "SDMMC3_CMD"),
	PINCTRL_PIN(35, "SDMMC3_D0"),

	PINCTRL_PIN(45, "MF_LPC_AD2"),
	PINCTRL_PIN(46, "LPC_CLKRUNB"),
	PINCTRL_PIN(47, "MF_LPC_AD0"),
	PINCTRL_PIN(48, "LPC_FRAMEB"),
	PINCTRL_PIN(49, "MF_LPC_CLKOUT1"),
	PINCTRL_PIN(50, "MF_LPC_AD3"),
	PINCTRL_PIN(51, "MF_LPC_CLKOUT0"),
	PINCTRL_PIN(52, "MF_LPC_AD1"),

	PINCTRL_PIN(60, "SPI1_MISO"),
	PINCTRL_PIN(61, "SPI1_CSO_B"),
	PINCTRL_PIN(62, "SPI1_CLK"),
	PINCTRL_PIN(63, "MMC1_D6"),
	PINCTRL_PIN(64, "SPI1_MOSI"),
	PINCTRL_PIN(65, "MMC1_D5"),
	PINCTRL_PIN(66, "SPI1_CS1_B"),
	PINCTRL_PIN(67, "MMC1_D4_SD_WE"),
	PINCTRL_PIN(68, "MMC1_D7"),
	PINCTRL_PIN(69, "MMC1_RCLK"),

	PINCTRL_PIN(75, "USB_OC1_B"),
	PINCTRL_PIN(76, "PMU_RESETBUTTON_B"),
	PINCTRL_PIN(77, "GPIO_ALERT"),
	PINCTRL_PIN(78, "SDMMC3_PWR_EN_B"),
	PINCTRL_PIN(79, "ILB_SERIRQ"),
	PINCTRL_PIN(80, "USB_OC0_B"),
	PINCTRL_PIN(81, "SDMMC3_CD_B"),
	PINCTRL_PIN(82, "SPKR"),
	PINCTRL_PIN(83, "SUSPWRDNACK"),
	PINCTRL_PIN(84, "SPARE_PIN"),
	PINCTRL_PIN(85, "SDMMC3_1P8_EN"),
};

static const unsigned southeast_pwm0_pins[] = { 5 };
static const unsigned southeast_pwm1_pins[] = { 1 };
static const unsigned southeast_sdmmc1_pins[] = {
	16, 17, 20, 23, 24, 26, 63, 65, 67, 68, 69,
};
static const unsigned southeast_sdmmc2_pins[] = { 15, 18, 19, 21, 22, 25 };
static const unsigned southeast_sdmmc3_pins[] = {
	30, 31, 32, 33, 34, 35, 78, 81, 85,
};
static const unsigned southeast_spi1_pins[] = { 60, 61, 62, 64, 66 };
static const unsigned southeast_spi2_pins[] = { 2, 3, 4, 6, 7 };

static const struct chv_pingroup southeast_groups[] = {
	PIN_GROUP("pwm0_grp", southeast_pwm0_pins, 1, false),
	PIN_GROUP("pwm1_grp", southeast_pwm1_pins, 1, false),
	PIN_GROUP("sdmmc1_grp", southeast_sdmmc1_pins, 1, false),
	PIN_GROUP("sdmmc2_grp", southeast_sdmmc2_pins, 1, false),
	PIN_GROUP("sdmmc3_grp", southeast_sdmmc3_pins, 1, false),
	PIN_GROUP("spi1_grp", southeast_spi1_pins, 1, false),
	PIN_GROUP("spi2_grp", southeast_spi2_pins, 4, false),
};

static const char * const southeast_pwm0_groups[] = { "pwm0_grp" };
static const char * const southeast_pwm1_groups[] = { "pwm1_grp" };
static const char * const southeast_sdmmc1_groups[] = { "sdmmc1_grp" };
static const char * const southeast_sdmmc2_groups[] = { "sdmmc2_grp" };
static const char * const southeast_sdmmc3_groups[] = { "sdmmc3_grp" };
static const char * const southeast_spi1_groups[] = { "spi1_grp" };
static const char * const southeast_spi2_groups[] = { "spi2_grp" };

static const struct chv_function southeast_functions[] = {
	FUNCTION("pwm0", southeast_pwm0_groups),
	FUNCTION("pwm1", southeast_pwm1_groups),
	FUNCTION("sdmmc1", southeast_sdmmc1_groups),
	FUNCTION("sdmmc2", southeast_sdmmc2_groups),
	FUNCTION("sdmmc3", southeast_sdmmc3_groups),
	FUNCTION("spi1", southeast_spi1_groups),
	FUNCTION("spi2", southeast_spi2_groups),
};

static const struct chv_gpio_pinrange southeast_gpio_ranges[] = {
	GPIO_PINRANGE(0, 7),
	GPIO_PINRANGE(15, 26),
	GPIO_PINRANGE(30, 35),
	GPIO_PINRANGE(45, 52),
	GPIO_PINRANGE(60, 69),
	GPIO_PINRANGE(75, 85),
};

static const struct chv_community southeast_community = {
	.uid = "4",
	.pins = southeast_pins,
	.npins = ARRAY_SIZE(southeast_pins),
	.groups = southeast_groups,
	.ngroups = ARRAY_SIZE(southeast_groups),
	.functions = southeast_functions,
	.nfunctions = ARRAY_SIZE(southeast_functions),
	.gpio_ranges = southeast_gpio_ranges,
	.ngpio_ranges = ARRAY_SIZE(southeast_gpio_ranges),
	.ngpios = ARRAY_SIZE(southeast_pins),
};

static const struct chv_community *chv_communities[] = {
	&southwest_community,
	&north_community,
	&east_community,
	&southeast_community,
};

static void __iomem *chv_padreg(struct chv_pinctrl *pctrl, unsigned offset,
				unsigned reg)
{
	unsigned family_no = offset / MAX_FAMILY_PAD_GPIO_NO;
	unsigned pad_no = offset % MAX_FAMILY_PAD_GPIO_NO;

	offset = FAMILY_PAD_REGS_OFF + FAMILY_PAD_REGS_SIZE * family_no +
		 GPIO_REGS_SIZE * pad_no;

	return pctrl->regs + offset + reg;
}

static void chv_writel(u32 value, void __iomem *reg)
{
	writel(value, reg);
	/* simple readback to confirm the bus transferring done */
	readl(reg);
}

/* When Pad Cfg is locked, driver can only change GPIOTXState or GPIORXState */
static bool chv_pad_locked(struct chv_pinctrl *pctrl, unsigned offset)
{
	void __iomem *reg;

	reg = chv_padreg(pctrl, offset, CHV_PADCTRL1);
	return readl(reg) & CHV_PADCTRL1_CFGLOCK;
}

static int chv_get_groups_count(struct pinctrl_dev *pctldev)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	return pctrl->community->ngroups;
}

static const char *chv_get_group_name(struct pinctrl_dev *pctldev,
				      unsigned group)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	return pctrl->community->groups[group].name;
}

static int chv_get_group_pins(struct pinctrl_dev *pctldev, unsigned group,
			      const unsigned **pins, unsigned *npins)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	*pins = pctrl->community->groups[group].pins;
	*npins = pctrl->community->groups[group].npins;
	return 0;
}

static void chv_pin_dbg_show(struct pinctrl_dev *pctldev, struct seq_file *s,
			     unsigned offset)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	unsigned long flags;
	u32 ctrl0, ctrl1;
	bool locked;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	ctrl0 = readl(chv_padreg(pctrl, offset, CHV_PADCTRL0));
	ctrl1 = readl(chv_padreg(pctrl, offset, CHV_PADCTRL1));
	locked = chv_pad_locked(pctrl, offset);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	if (ctrl0 & CHV_PADCTRL0_GPIOEN) {
		seq_puts(s, "GPIO ");
	} else {
		u32 mode;

		mode = ctrl0 & CHV_PADCTRL0_PMODE_MASK;
		mode >>= CHV_PADCTRL0_PMODE_SHIFT;

		seq_printf(s, "mode %d ", mode);
	}

	seq_printf(s, "ctrl0 0x%08x ctrl1 0x%08x", ctrl0, ctrl1);

	if (locked)
		seq_puts(s, " [LOCKED]");
}

static const struct pinctrl_ops chv_pinctrl_ops = {
	.get_groups_count = chv_get_groups_count,
	.get_group_name = chv_get_group_name,
	.get_group_pins = chv_get_group_pins,
	.pin_dbg_show = chv_pin_dbg_show,
};

static int chv_get_functions_count(struct pinctrl_dev *pctldev)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	return pctrl->community->nfunctions;
}

static const char *chv_get_function_name(struct pinctrl_dev *pctldev,
					 unsigned function)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	return pctrl->community->functions[function].name;
}

static int chv_get_function_groups(struct pinctrl_dev *pctldev,
				   unsigned function,
				   const char * const **groups,
				   unsigned * const ngroups)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);

	*groups = pctrl->community->functions[function].groups;
	*ngroups = pctrl->community->functions[function].ngroups;
	return 0;
}

static int chv_pinmux_set_mux(struct pinctrl_dev *pctldev, unsigned function,
			      unsigned group)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	const struct chv_pingroup *grp;
	unsigned long flags;
	int i;

	grp = &pctrl->community->groups[group];

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	/* Check first that the pad is not locked */
	for (i = 0; i < grp->npins; i++) {
		if (chv_pad_locked(pctrl, grp->pins[i])) {
			dev_warn(pctrl->dev, "unable to set mode for locked pin %u\n",
				 grp->pins[i]);
			raw_spin_unlock_irqrestore(&pctrl->lock, flags);
			return -EBUSY;
		}
	}

	for (i = 0; i < grp->npins; i++) {
		const struct chv_alternate_function *altfunc = &grp->altfunc;
		int pin = grp->pins[i];
		void __iomem *reg;
		u32 value;

		/* Check if there is pin-specific config */
		if (grp->overrides) {
			int j;

			for (j = 0; j < grp->noverrides; j++) {
				if (grp->overrides[j].pin == pin) {
					altfunc = &grp->overrides[j];
					break;
				}
			}
		}

		reg = chv_padreg(pctrl, pin, CHV_PADCTRL0);
		value = readl(reg);
		/* Disable GPIO mode */
		value &= ~CHV_PADCTRL0_GPIOEN;
		/* Set to desired mode */
		value &= ~CHV_PADCTRL0_PMODE_MASK;
		value |= altfunc->mode << CHV_PADCTRL0_PMODE_SHIFT;
		chv_writel(value, reg);

		/* Update for invert_oe */
		reg = chv_padreg(pctrl, pin, CHV_PADCTRL1);
		value = readl(reg) & ~CHV_PADCTRL1_INVRXTX_MASK;
		if (altfunc->invert_oe)
			value |= CHV_PADCTRL1_INVRXTX_TXENABLE;
		chv_writel(value, reg);

		dev_dbg(pctrl->dev, "configured pin %u mode %u OE %sinverted\n",
			pin, altfunc->mode, altfunc->invert_oe ? "" : "not ");
	}

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	return 0;
}

static int chv_gpio_request_enable(struct pinctrl_dev *pctldev,
				   struct pinctrl_gpio_range *range,
				   unsigned offset)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	unsigned long flags;
	void __iomem *reg;
	u32 value;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	if (chv_pad_locked(pctrl, offset)) {
		value = readl(chv_padreg(pctrl, offset, CHV_PADCTRL0));
		if (!(value & CHV_PADCTRL0_GPIOEN)) {
			/* Locked so cannot enable */
			raw_spin_unlock_irqrestore(&pctrl->lock, flags);
			return -EBUSY;
		}
	} else {
		int i;

		/* Reset the interrupt mapping */
		for (i = 0; i < ARRAY_SIZE(pctrl->intr_lines); i++) {
			if (pctrl->intr_lines[i] == offset) {
				pctrl->intr_lines[i] = 0;
				break;
			}
		}

		/* Disable interrupt generation */
		reg = chv_padreg(pctrl, offset, CHV_PADCTRL1);
		value = readl(reg);
		value &= ~CHV_PADCTRL1_INTWAKECFG_MASK;
		value &= ~CHV_PADCTRL1_INVRXTX_MASK;
		chv_writel(value, reg);

		reg = chv_padreg(pctrl, offset, CHV_PADCTRL0);
		value = readl(reg);

		/*
		 * If the pin is in HiZ mode (both TX and RX buffers are
		 * disabled) we turn it to be input now.
		 */
		if ((value & CHV_PADCTRL0_GPIOCFG_MASK) ==
		     (CHV_PADCTRL0_GPIOCFG_HIZ << CHV_PADCTRL0_GPIOCFG_SHIFT)) {
			value &= ~CHV_PADCTRL0_GPIOCFG_MASK;
			value |= CHV_PADCTRL0_GPIOCFG_GPI <<
				CHV_PADCTRL0_GPIOCFG_SHIFT;
		}

		/* Switch to a GPIO mode */
		value |= CHV_PADCTRL0_GPIOEN;
		chv_writel(value, reg);
	}

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	return 0;
}

static void chv_gpio_disable_free(struct pinctrl_dev *pctldev,
				  struct pinctrl_gpio_range *range,
				  unsigned offset)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	unsigned long flags;
	void __iomem *reg;
	u32 value;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	reg = chv_padreg(pctrl, offset, CHV_PADCTRL0);
	value = readl(reg) & ~CHV_PADCTRL0_GPIOEN;
	chv_writel(value, reg);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);
}

static int chv_gpio_set_direction(struct pinctrl_dev *pctldev,
				  struct pinctrl_gpio_range *range,
				  unsigned offset, bool input)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	void __iomem *reg = chv_padreg(pctrl, offset, CHV_PADCTRL0);
	unsigned long flags;
	u32 ctrl0;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	ctrl0 = readl(reg) & ~CHV_PADCTRL0_GPIOCFG_MASK;
	if (input)
		ctrl0 |= CHV_PADCTRL0_GPIOCFG_GPI << CHV_PADCTRL0_GPIOCFG_SHIFT;
	else
		ctrl0 |= CHV_PADCTRL0_GPIOCFG_GPO << CHV_PADCTRL0_GPIOCFG_SHIFT;
	chv_writel(ctrl0, reg);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	return 0;
}

static const struct pinmux_ops chv_pinmux_ops = {
	.get_functions_count = chv_get_functions_count,
	.get_function_name = chv_get_function_name,
	.get_function_groups = chv_get_function_groups,
	.set_mux = chv_pinmux_set_mux,
	.gpio_request_enable = chv_gpio_request_enable,
	.gpio_disable_free = chv_gpio_disable_free,
	.gpio_set_direction = chv_gpio_set_direction,
};

static int chv_config_get(struct pinctrl_dev *pctldev, unsigned pin,
			  unsigned long *config)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	enum pin_config_param param = pinconf_to_config_param(*config);
	unsigned long flags;
	u32 ctrl0, ctrl1;
	u16 arg = 0;
	u32 term;

	raw_spin_lock_irqsave(&pctrl->lock, flags);
	ctrl0 = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	ctrl1 = readl(chv_padreg(pctrl, pin, CHV_PADCTRL1));
	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	term = (ctrl0 & CHV_PADCTRL0_TERM_MASK) >> CHV_PADCTRL0_TERM_SHIFT;

	switch (param) {
	case PIN_CONFIG_BIAS_DISABLE:
		if (term)
			return -EINVAL;
		break;

	case PIN_CONFIG_BIAS_PULL_UP:
		if (!(ctrl0 & CHV_PADCTRL0_TERM_UP))
			return -EINVAL;

		switch (term) {
		case CHV_PADCTRL0_TERM_20K:
			arg = 20000;
			break;
		case CHV_PADCTRL0_TERM_5K:
			arg = 5000;
			break;
		case CHV_PADCTRL0_TERM_1K:
			arg = 1000;
			break;
		}

		break;

	case PIN_CONFIG_BIAS_PULL_DOWN:
		if (!term || (ctrl0 & CHV_PADCTRL0_TERM_UP))
			return -EINVAL;

		switch (term) {
		case CHV_PADCTRL0_TERM_20K:
			arg = 20000;
			break;
		case CHV_PADCTRL0_TERM_5K:
			arg = 5000;
			break;
		}

		break;

	case PIN_CONFIG_DRIVE_OPEN_DRAIN:
		if (!(ctrl1 & CHV_PADCTRL1_ODEN))
			return -EINVAL;
		break;

	case PIN_CONFIG_BIAS_HIGH_IMPEDANCE: {
		u32 cfg;

		cfg = ctrl0 & CHV_PADCTRL0_GPIOCFG_MASK;
		cfg >>= CHV_PADCTRL0_GPIOCFG_SHIFT;
		if (cfg != CHV_PADCTRL0_GPIOCFG_HIZ)
			return -EINVAL;

		break;
	}

	default:
		return -ENOTSUPP;
	}

	*config = pinconf_to_config_packed(param, arg);
	return 0;
}

static int chv_config_set_pull(struct chv_pinctrl *pctrl, unsigned pin,
			       enum pin_config_param param, u16 arg)
{
	void __iomem *reg = chv_padreg(pctrl, pin, CHV_PADCTRL0);
	unsigned long flags;
	u32 ctrl0, pull;

	raw_spin_lock_irqsave(&pctrl->lock, flags);
	ctrl0 = readl(reg);

	switch (param) {
	case PIN_CONFIG_BIAS_DISABLE:
		ctrl0 &= ~(CHV_PADCTRL0_TERM_MASK | CHV_PADCTRL0_TERM_UP);
		break;

	case PIN_CONFIG_BIAS_PULL_UP:
		ctrl0 &= ~(CHV_PADCTRL0_TERM_MASK | CHV_PADCTRL0_TERM_UP);

		switch (arg) {
		case 1000:
			/* For 1k there is only pull up */
			pull = CHV_PADCTRL0_TERM_1K << CHV_PADCTRL0_TERM_SHIFT;
			break;
		case 5000:
			pull = CHV_PADCTRL0_TERM_5K << CHV_PADCTRL0_TERM_SHIFT;
			break;
		case 20000:
			pull = CHV_PADCTRL0_TERM_20K << CHV_PADCTRL0_TERM_SHIFT;
			break;
		default:
			raw_spin_unlock_irqrestore(&pctrl->lock, flags);
			return -EINVAL;
		}

		ctrl0 |= CHV_PADCTRL0_TERM_UP | pull;
		break;

	case PIN_CONFIG_BIAS_PULL_DOWN:
		ctrl0 &= ~(CHV_PADCTRL0_TERM_MASK | CHV_PADCTRL0_TERM_UP);

		switch (arg) {
		case 5000:
			pull = CHV_PADCTRL0_TERM_5K << CHV_PADCTRL0_TERM_SHIFT;
			break;
		case 20000:
			pull = CHV_PADCTRL0_TERM_20K << CHV_PADCTRL0_TERM_SHIFT;
			break;
		default:
			raw_spin_unlock_irqrestore(&pctrl->lock, flags);
			return -EINVAL;
		}

		ctrl0 |= pull;
		break;

	default:
		raw_spin_unlock_irqrestore(&pctrl->lock, flags);
		return -EINVAL;
	}

	chv_writel(ctrl0, reg);
	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	return 0;
}

static int chv_config_set(struct pinctrl_dev *pctldev, unsigned pin,
			  unsigned long *configs, unsigned nconfigs)
{
	struct chv_pinctrl *pctrl = pinctrl_dev_get_drvdata(pctldev);
	enum pin_config_param param;
	int i, ret;
	u16 arg;

	if (chv_pad_locked(pctrl, pin))
		return -EBUSY;

	for (i = 0; i < nconfigs; i++) {
		param = pinconf_to_config_param(configs[i]);
		arg = pinconf_to_config_argument(configs[i]);

		switch (param) {
		case PIN_CONFIG_BIAS_DISABLE:
		case PIN_CONFIG_BIAS_PULL_UP:
		case PIN_CONFIG_BIAS_PULL_DOWN:
			ret = chv_config_set_pull(pctrl, pin, param, arg);
			if (ret)
				return ret;
			break;

		default:
			return -ENOTSUPP;
		}

		dev_dbg(pctrl->dev, "pin %d set config %d arg %u\n", pin,
			param, arg);
	}

	return 0;
}

static const struct pinconf_ops chv_pinconf_ops = {
	.is_generic = true,
	.pin_config_set = chv_config_set,
	.pin_config_get = chv_config_get,
};

static struct pinctrl_desc chv_pinctrl_desc = {
	.pctlops = &chv_pinctrl_ops,
	.pmxops = &chv_pinmux_ops,
	.confops = &chv_pinconf_ops,
	.owner = THIS_MODULE,
};

static unsigned chv_gpio_offset_to_pin(struct chv_pinctrl *pctrl,
				       unsigned offset)
{
	return pctrl->community->pins[offset].number;
}

static int chv_gpio_get(struct gpio_chip *chip, unsigned offset)
{
	struct chv_pinctrl *pctrl = gpiochip_get_data(chip);
	int pin = chv_gpio_offset_to_pin(pctrl, offset);
	unsigned long flags;
	u32 ctrl0, cfg;

	raw_spin_lock_irqsave(&pctrl->lock, flags);
	ctrl0 = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	cfg = ctrl0 & CHV_PADCTRL0_GPIOCFG_MASK;
	cfg >>= CHV_PADCTRL0_GPIOCFG_SHIFT;

	if (cfg == CHV_PADCTRL0_GPIOCFG_GPO)
		return !!(ctrl0 & CHV_PADCTRL0_GPIOTXSTATE);
	return !!(ctrl0 & CHV_PADCTRL0_GPIORXSTATE);
}

static void chv_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
	struct chv_pinctrl *pctrl = gpiochip_get_data(chip);
	unsigned pin = chv_gpio_offset_to_pin(pctrl, offset);
	unsigned long flags;
	void __iomem *reg;
	u32 ctrl0;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	reg = chv_padreg(pctrl, pin, CHV_PADCTRL0);
	ctrl0 = readl(reg);

	if (value)
		ctrl0 |= CHV_PADCTRL0_GPIOTXSTATE;
	else
		ctrl0 &= ~CHV_PADCTRL0_GPIOTXSTATE;

	chv_writel(ctrl0, reg);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);
}

static int chv_gpio_get_direction(struct gpio_chip *chip, unsigned offset)
{
	struct chv_pinctrl *pctrl = gpiochip_get_data(chip);
	unsigned pin = chv_gpio_offset_to_pin(pctrl, offset);
	u32 ctrl0, direction;
	unsigned long flags;

	raw_spin_lock_irqsave(&pctrl->lock, flags);
	ctrl0 = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	direction = ctrl0 & CHV_PADCTRL0_GPIOCFG_MASK;
	direction >>= CHV_PADCTRL0_GPIOCFG_SHIFT;

	return direction != CHV_PADCTRL0_GPIOCFG_GPO;
}

static int chv_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
	return pinctrl_gpio_direction_input(chip->base + offset);
}

static int chv_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
				     int value)
{
	chv_gpio_set(chip, offset, value);
	return pinctrl_gpio_direction_output(chip->base + offset);
}

static const struct gpio_chip chv_gpio_chip = {
	.owner = THIS_MODULE,
	.request = gpiochip_generic_request,
	.free = gpiochip_generic_free,
	.get_direction = chv_gpio_get_direction,
	.direction_input = chv_gpio_direction_input,
	.direction_output = chv_gpio_direction_output,
	.get = chv_gpio_get,
	.set = chv_gpio_set,
};

static void chv_gpio_irq_ack(struct irq_data *d)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct chv_pinctrl *pctrl = gpiochip_get_data(gc);
	int pin = chv_gpio_offset_to_pin(pctrl, irqd_to_hwirq(d));
	u32 intr_line;

	raw_spin_lock(&pctrl->lock);

	intr_line = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	intr_line &= CHV_PADCTRL0_INTSEL_MASK;
	intr_line >>= CHV_PADCTRL0_INTSEL_SHIFT;
	chv_writel(BIT(intr_line), pctrl->regs + CHV_INTSTAT);

	raw_spin_unlock(&pctrl->lock);
}

static void chv_gpio_irq_mask_unmask(struct irq_data *d, bool mask)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct chv_pinctrl *pctrl = gpiochip_get_data(gc);
	int pin = chv_gpio_offset_to_pin(pctrl, irqd_to_hwirq(d));
	u32 value, intr_line;
	unsigned long flags;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	intr_line = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	intr_line &= CHV_PADCTRL0_INTSEL_MASK;
	intr_line >>= CHV_PADCTRL0_INTSEL_SHIFT;

	value = readl(pctrl->regs + CHV_INTMASK);
	if (mask)
		value &= ~BIT(intr_line);
	else
		value |= BIT(intr_line);
	chv_writel(value, pctrl->regs + CHV_INTMASK);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);
}

static void chv_gpio_irq_mask(struct irq_data *d)
{
	chv_gpio_irq_mask_unmask(d, true);
}

static void chv_gpio_irq_unmask(struct irq_data *d)
{
	chv_gpio_irq_mask_unmask(d, false);
}

static unsigned chv_gpio_irq_startup(struct irq_data *d)
{
	/*
	 * Check if the interrupt has been requested with 0 as triggering
	 * type. In that case it is assumed that the current values
	 * programmed to the hardware are used (e.g BIOS configured
	 * defaults).
	 *
	 * In that case ->irq_set_type() will never be called so we need to
	 * read back the values from hardware now, set correct flow handler
	 * and update mappings before the interrupt is being used.
	 */
	if (irqd_get_trigger_type(d) == IRQ_TYPE_NONE) {
		struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
		struct chv_pinctrl *pctrl = gpiochip_get_data(gc);
		unsigned offset = irqd_to_hwirq(d);
		int pin = chv_gpio_offset_to_pin(pctrl, offset);
		irq_flow_handler_t handler;
		unsigned long flags;
		u32 intsel, value;

		raw_spin_lock_irqsave(&pctrl->lock, flags);
		intsel = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
		intsel &= CHV_PADCTRL0_INTSEL_MASK;
		intsel >>= CHV_PADCTRL0_INTSEL_SHIFT;

		value = readl(chv_padreg(pctrl, pin, CHV_PADCTRL1));
		if (value & CHV_PADCTRL1_INTWAKECFG_LEVEL)
			handler = handle_level_irq;
		else
			handler = handle_edge_irq;

		if (!pctrl->intr_lines[intsel]) {
			irq_set_handler_locked(d, handler);
			pctrl->intr_lines[intsel] = offset;
		}
		raw_spin_unlock_irqrestore(&pctrl->lock, flags);
	}

	chv_gpio_irq_unmask(d);
	return 0;
}

static int chv_gpio_irq_type(struct irq_data *d, unsigned type)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct chv_pinctrl *pctrl = gpiochip_get_data(gc);
	unsigned offset = irqd_to_hwirq(d);
	int pin = chv_gpio_offset_to_pin(pctrl, offset);
	unsigned long flags;
	u32 value;

	raw_spin_lock_irqsave(&pctrl->lock, flags);

	/*
	 * Pins which can be used as shared interrupt are configured in
	 * BIOS. Driver trusts BIOS configurations and assigns different
	 * handler according to the irq type.
	 *
	 * Driver needs to save the mapping between each pin and
	 * its interrupt line.
	 * 1. If the pin cfg is locked in BIOS:
	 *	Trust BIOS has programmed IntWakeCfg bits correctly,
	 *	driver just needs to save the mapping.
	 * 2. If the pin cfg is not locked in BIOS:
	 *	Driver programs the IntWakeCfg bits and save the mapping.
	 */
	if (!chv_pad_locked(pctrl, pin)) {
		void __iomem *reg = chv_padreg(pctrl, pin, CHV_PADCTRL1);

		value = readl(reg);
		value &= ~CHV_PADCTRL1_INTWAKECFG_MASK;
		value &= ~CHV_PADCTRL1_INVRXTX_MASK;

		if (type & IRQ_TYPE_EDGE_BOTH) {
			if ((type & IRQ_TYPE_EDGE_BOTH) == IRQ_TYPE_EDGE_BOTH)
				value |= CHV_PADCTRL1_INTWAKECFG_BOTH;
			else if (type & IRQ_TYPE_EDGE_RISING)
				value |= CHV_PADCTRL1_INTWAKECFG_RISING;
			else if (type & IRQ_TYPE_EDGE_FALLING)
				value |= CHV_PADCTRL1_INTWAKECFG_FALLING;
		} else if (type & IRQ_TYPE_LEVEL_MASK) {
			value |= CHV_PADCTRL1_INTWAKECFG_LEVEL;
			if (type & IRQ_TYPE_LEVEL_LOW)
				value |= CHV_PADCTRL1_INVRXTX_RXDATA;
		}

		chv_writel(value, reg);
	}

	value = readl(chv_padreg(pctrl, pin, CHV_PADCTRL0));
	value &= CHV_PADCTRL0_INTSEL_MASK;
	value >>= CHV_PADCTRL0_INTSEL_SHIFT;

	pctrl->intr_lines[value] = offset;

	if (type & IRQ_TYPE_EDGE_BOTH)
		irq_set_handler_locked(d, handle_edge_irq);
	else if (type & IRQ_TYPE_LEVEL_MASK)
		irq_set_handler_locked(d, handle_level_irq);

	raw_spin_unlock_irqrestore(&pctrl->lock, flags);

	return 0;
}

static struct irq_chip chv_gpio_irqchip = {
	.name = "chv-gpio",
	.irq_startup = chv_gpio_irq_startup,
	.irq_ack = chv_gpio_irq_ack,
	.irq_mask = chv_gpio_irq_mask,
	.irq_unmask = chv_gpio_irq_unmask,
	.irq_set_type = chv_gpio_irq_type,
	.flags = IRQCHIP_SKIP_SET_WAKE,
};

static void chv_gpio_irq_handler(struct irq_desc *desc)
{
	struct gpio_chip *gc = irq_desc_get_handler_data(desc);
	struct chv_pinctrl *pctrl = gpiochip_get_data(gc);
	struct irq_chip *chip = irq_desc_get_chip(desc);
	unsigned long pending;
	u32 intr_line;

	chained_irq_enter(chip, desc);

	pending = readl(pctrl->regs + CHV_INTSTAT);
	for_each_set_bit(intr_line, &pending, 16) {
		unsigned irq, offset;

		offset = pctrl->intr_lines[intr_line];
		irq = irq_find_mapping(gc->irqdomain, offset);
		generic_handle_irq(irq);
	}

	chained_irq_exit(chip, desc);
}

static int chv_gpio_probe(struct chv_pinctrl *pctrl, int irq)
{
	const struct chv_gpio_pinrange *range;
	struct gpio_chip *chip = &pctrl->chip;
	int ret, i, offset;

	*chip = chv_gpio_chip;

	chip->ngpio = pctrl->community->ngpios;
	chip->label = dev_name(pctrl->dev);
	chip->parent = pctrl->dev;
	chip->base = -1;

	ret = gpiochip_add_data(chip, pctrl);
	if (ret) {
		dev_err(pctrl->dev, "Failed to register gpiochip\n");
		return ret;
	}

	for (i = 0, offset = 0; i < pctrl->community->ngpio_ranges; i++) {
		range = &pctrl->community->gpio_ranges[i];
		ret = gpiochip_add_pin_range(chip, dev_name(pctrl->dev), offset,
					     range->base, range->npins);
		if (ret) {
			dev_err(pctrl->dev, "failed to add GPIO pin range\n");
			goto fail;
		}

		offset += range->npins;
	}

	/* Mask and clear all interrupts */
	chv_writel(0, pctrl->regs + CHV_INTMASK);
	chv_writel(0xffff, pctrl->regs + CHV_INTSTAT);

	ret = gpiochip_irqchip_add(chip, &chv_gpio_irqchip, 0,
				   handle_simple_irq, IRQ_TYPE_NONE);
	if (ret) {
		dev_err(pctrl->dev, "failed to add IRQ chip\n");
		goto fail;
	}

	gpiochip_set_chained_irqchip(chip, &chv_gpio_irqchip, irq,
				     chv_gpio_irq_handler);
	return 0;

fail:
	gpiochip_remove(chip);

	return ret;
}

static int chv_pinctrl_probe(struct platform_device *pdev)
{
	struct chv_pinctrl *pctrl;
	struct acpi_device *adev;
	struct resource *res;
	int ret, irq, i;

	adev = ACPI_COMPANION(&pdev->dev);
	if (!adev)
		return -ENODEV;

	pctrl = devm_kzalloc(&pdev->dev, sizeof(*pctrl), GFP_KERNEL);
	if (!pctrl)
		return -ENOMEM;

	for (i = 0; i < ARRAY_SIZE(chv_communities); i++)
		if (!strcmp(adev->pnp.unique_id, chv_communities[i]->uid)) {
			pctrl->community = chv_communities[i];
			break;
		}
	if (i == ARRAY_SIZE(chv_communities))
		return -ENODEV;

	raw_spin_lock_init(&pctrl->lock);
	pctrl->dev = &pdev->dev;

#ifdef CONFIG_PM_SLEEP
	pctrl->saved_pin_context = devm_kcalloc(pctrl->dev,
		pctrl->community->npins, sizeof(*pctrl->saved_pin_context),
		GFP_KERNEL);
	if (!pctrl->saved_pin_context)
		return -ENOMEM;
#endif

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	pctrl->regs = devm_ioremap_resource(&pdev->dev, res);
	if (IS_ERR(pctrl->regs))
		return PTR_ERR(pctrl->regs);

	irq = platform_get_irq(pdev, 0);
	if (irq < 0) {
		dev_err(&pdev->dev, "failed to get interrupt number\n");
		return irq;
	}

	pctrl->pctldesc = chv_pinctrl_desc;
	pctrl->pctldesc.name = dev_name(&pdev->dev);
	pctrl->pctldesc.pins = pctrl->community->pins;
	pctrl->pctldesc.npins = pctrl->community->npins;

	pctrl->pctldev = pinctrl_register(&pctrl->pctldesc, &pdev->dev, pctrl);
	if (IS_ERR(pctrl->pctldev)) {
		dev_err(&pdev->dev, "failed to register pinctrl driver\n");
		return PTR_ERR(pctrl->pctldev);
	}

	ret = chv_gpio_probe(pctrl, irq);
	if (ret) {
		pinctrl_unregister(pctrl->pctldev);
		return ret;
	}

	platform_set_drvdata(pdev, pctrl);

	return 0;
}

static int chv_pinctrl_remove(struct platform_device *pdev)
{
	struct chv_pinctrl *pctrl = platform_get_drvdata(pdev);

	gpiochip_remove(&pctrl->chip);
	pinctrl_unregister(pctrl->pctldev);

	return 0;
}

#ifdef CONFIG_PM_SLEEP
static int chv_pinctrl_suspend(struct device *dev)
{
	struct platform_device *pdev = to_platform_device(dev);
	struct chv_pinctrl *pctrl = platform_get_drvdata(pdev);
	int i;

	pctrl->saved_intmask = readl(pctrl->regs + CHV_INTMASK);

	for (i = 0; i < pctrl->community->npins; i++) {
		const struct pinctrl_pin_desc *desc;
		struct chv_pin_context *ctx;
		void __iomem *reg;

		desc = &pctrl->community->pins[i];
		if (chv_pad_locked(pctrl, desc->number))
			continue;

		ctx = &pctrl->saved_pin_context[i];

		reg = chv_padreg(pctrl, desc->number, CHV_PADCTRL0);
		ctx->padctrl0 = readl(reg) & ~CHV_PADCTRL0_GPIORXSTATE;

		reg = chv_padreg(pctrl, desc->number, CHV_PADCTRL1);
		ctx->padctrl1 = readl(reg);
	}

	return 0;
}

static int chv_pinctrl_resume(struct device *dev)
{
	struct platform_device *pdev = to_platform_device(dev);
	struct chv_pinctrl *pctrl = platform_get_drvdata(pdev);
	int i;

	/*
	 * Mask all interrupts before restoring per-pin configuration
	 * registers because we don't know in which state BIOS left them
	 * upon exiting suspend.
	 */
	chv_writel(0, pctrl->regs + CHV_INTMASK);

	for (i = 0; i < pctrl->community->npins; i++) {
		const struct pinctrl_pin_desc *desc;
		const struct chv_pin_context *ctx;
		void __iomem *reg;
		u32 val;

		desc = &pctrl->community->pins[i];
		if (chv_pad_locked(pctrl, desc->number))
			continue;

		ctx = &pctrl->saved_pin_context[i];

		/* Only restore if our saved state differs from the current */
		reg = chv_padreg(pctrl, desc->number, CHV_PADCTRL0);
		val = readl(reg) & ~CHV_PADCTRL0_GPIORXSTATE;
		if (ctx->padctrl0 != val) {
			chv_writel(ctx->padctrl0, reg);
			dev_dbg(pctrl->dev, "restored pin %2u ctrl0 0x%08x\n",
				desc->number, readl(reg));
		}

		reg = chv_padreg(pctrl, desc->number, CHV_PADCTRL1);
		val = readl(reg);
		if (ctx->padctrl1 != val) {
			chv_writel(ctx->padctrl1, reg);
			dev_dbg(pctrl->dev, "restored pin %2u ctrl1 0x%08x\n",
				desc->number, readl(reg));
		}
	}

	/*
	 * Now that all pins are restored to known state, we can restore
	 * the interrupt mask register as well.
	 */
	chv_writel(0xffff, pctrl->regs + CHV_INTSTAT);
	chv_writel(pctrl->saved_intmask, pctrl->regs + CHV_INTMASK);

	return 0;
}
#endif

static const struct dev_pm_ops chv_pinctrl_pm_ops = {
	SET_LATE_SYSTEM_SLEEP_PM_OPS(chv_pinctrl_suspend, chv_pinctrl_resume)
};

static const struct acpi_device_id chv_pinctrl_acpi_match[] = {
	{ "INT33FF" },
	{ }
};
MODULE_DEVICE_TABLE(acpi, chv_pinctrl_acpi_match);

static struct platform_driver chv_pinctrl_driver = {
	.probe = chv_pinctrl_probe,
	.remove = chv_pinctrl_remove,
	.driver = {
		.name = "cherryview-pinctrl",
		.pm = &chv_pinctrl_pm_ops,
		.acpi_match_table = chv_pinctrl_acpi_match,
	},
};

static int __init chv_pinctrl_init(void)
{
	return platform_driver_register(&chv_pinctrl_driver);
}
subsys_initcall(chv_pinctrl_init);

static void __exit chv_pinctrl_exit(void)
{
	platform_driver_unregister(&chv_pinctrl_driver);
}
module_exit(chv_pinctrl_exit);

MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
MODULE_DESCRIPTION("Intel Cherryview/Braswell pinctrl driver");
MODULE_LICENSE("GPL v2");


text:
<?php
if(!defined('IN_INDEX')) exit;

$template->assign('subtitle', $lang['maintenance_subtitle']);
$template->assign('subtemplate','maintenance.inc.tpl');

?>


text:
using BEPUutilities2.Collections;
using BEPUutilities2.Memory;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace SolverPrototypeTests.SpecializedTests
{
    public static class SortTest
    {

        struct Comparer : IComparerRef<int>
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public int Compare(ref int a, ref int b)
            {
                return a < b ? -1 : a > b ? 1 : 0;
            }
        }

        public static void Test()
        {
            void VerifySort<TSpan>(TSpan keys) where TSpan : ISpan<int>
            {
                for (int i = 1; i < keys.Length; ++i)
                {
                    Debug.Assert(keys[i] >= keys[i - 1]);
                }
            }
            const int elementCount = 4096;
            const int elementExclusiveUpperBound = 32768;// 1 << 5;

            var bufferPool = new BufferPool();
            var threadDispatcher = new SimpleThreadDispatcher(8);
            for (int iteration = 0; iteration < 4; ++iteration)
            {
                GC.Collect(3, GCCollectionMode.Forced, true);
                var keys = new Array<int>(new int[elementCount]);
                var indexMap = new Array<int>(new int[elementCount]);
                Random random = new Random(5);
                for (int i = 0; i < elementCount; ++i)
                {
                    indexMap[i] = i;
                    //keys[i] = i / (elementCount / elementExclusiveUpperBound);
                    //keys[i] = i % elementExclusiveUpperBound;
                    //keys[i] = i;
                    keys[i] = random.Next(elementExclusiveUpperBound);
                }
                var keys2 = new Array<int>(new int[elementCount]);
                var indexMap2 = new Array<int>(new int[elementCount]);
                var keys3 = new Array<int>(new int[elementCount]);
                var indexMap3 = new Array<int>(new int[elementCount]);
                var keys4 = new Array<int>(new int[elementCount]);
                var indexMap4 = new Array<int>(new int[elementCount]);
                keys.CopyTo(0, ref keys2, 0, elementCount);
                keys.CopyTo(0, ref keys3, 0, elementCount);
                keys.CopyTo(0, ref keys4, 0, elementCount);
                indexMap.CopyTo(0, ref indexMap2, 0, elementCount);
                indexMap.CopyTo(0, ref indexMap3, 0, elementCount);
                indexMap.CopyTo(0, ref indexMap4, 0, elementCount);

                var timer = Stopwatch.StartNew();

                var keysScratch = new int[elementCount];
                var valuesScratch = new int[elementCount];
                var bucketCounts = new int[1024];
                for (int t = 0; t < 16; ++t)
                {
                    //keys2.CopyTo(0, ref keys, 0, elementCount);
                    //unsafe
                    //{
                    //    var comparer = new Comparer();
                    //    fixed (int* keysPointer = keys.Memory)
                    //    fixed (int* valuesPointer = indexMap.Memory)
                    //    {
                    //        var keysBuffer = new Buffer<int>(keysPointer, keys.Length);
                    //        var valuesBuffer = new Buffer<int>(valuesPointer, indexMap.Length);
                    //        timer.Restart();
                    //        QuickSort.Sort(ref keysBuffer[0], ref valuesBuffer[0], 0, elementCount - 1, ref comparer);
                    //    }
                    //}
                    ////QuickSort.Sort2(ref keys[0], ref indexMap[0], 0, elementCount - 1, ref comparer);
                    //timer.Stop();
                    //VerifySort(keys);
                    //Console.WriteLine($"QuickSort time (ms): {timer.Elapsed.TotalSeconds * 1e3}");

                    //keys.CopyTo(0, ref keys2, 0, elementCount);
                    //timer.Restart();
                    //Array.Sort(keys2.Memory, indexMap2.Memory, 0, elementCount);
                    //timer.Stop();
                    //VerifySort(keys2);
                    //Console.WriteLine($"Array.Sort time (ms): {timer.Elapsed.TotalSeconds * 1e3}");

                    keys.CopyTo(0, ref keys3, 0, elementCount);
                    timer.Restart();
                    Array.Clear(bucketCounts, 0, bucketCounts.Length);
                    LSBRadixSort.SortU16(ref keys3[0], ref indexMap3[0], ref keysScratch[0], ref valuesScratch[0], ref bucketCounts[0], elementCount);
                    timer.Stop();
                    VerifySort(keys3);
                    Console.WriteLine($"{t} LSBRadixSort time (ms): {timer.Elapsed.TotalSeconds * 1e3}");

                    //keys.CopyTo(0, ref keys4, 0, elementCount);
                    //var originalIndices = new int[256];
                    //timer.Restart();
                    ////MSBRadixSort.SortU32(ref keys4[0], ref indexMap4[0], ref bucketCounts[0], ref originalIndices[0], elementCount, 24);
                    //MSBRadixSort.SortU32(ref keys4[0], ref indexMap4[0], elementCount, SpanHelper.GetContainingPowerOf2(elementExclusiveUpperBound));
                    //timer.Stop();
                    //VerifySort(keys4);
                    //Console.WriteLine($"{t} MSBRadixSort time (ms): {timer.Elapsed.TotalSeconds * 1e3}");

                }
            }

        }
    }
}


text:
package io.github.ihongs.normal.serv;

import io.github.ihongs.Core;
import io.github.ihongs.action.ActionDriver;
import io.github.ihongs.action.ActionDriver.URLPatterns;
import io.github.ihongs.util.Synt;
import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 反射脚本拦截
 * @author Hongs
 */
public class XurlFilter implements Filter {

    private String      inside = null; // 过滤器标识
    private URLPatterns patter = null; // 待忽略用例
    private boolean     blocks = false ; // 屏蔽全部

    @Override
    public void init(FilterConfig fc) throws ServletException {
        inside = XsrfFilter.class.getName()+":"+fc.getFilterName()+":INSIDE";
        blocks = Synt.declare (fc.getInitParameter ("block-force") , false );
        patter = new ActionDriver.URLPatterns(
            fc.getInitParameter("url-include"),
            fc.getInitParameter("url-exclude")
        );
    }

    @Override
    public void doFilter(ServletRequest rxq, ServletResponse rxp, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest  req = (HttpServletRequest ) rxq;
        HttpServletResponse rsp = (HttpServletResponse) rxp;

        /**
         * 对于嵌套相同过滤, 不在内部重复执行;
         * 如外部设置了忽略, 则跳过忽略的路径.
         */
        if ((inside != null &&  Synt  .declare(req.getAttribute(inside), false ))
        ||  (patter != null && !patter.matches(ActionDriver.getRecentPath(req)))) {
            fc.doFilter(req, rsp);
            return;
        }

        /**
         * 文件缺失无需理会,将会自动转入 404
         */
        if (! blocks
        &&  ! new File(Core.BASE_PATH+ActionDriver.getRecentPath(req)).exists()) {
            fc.doFilter(req, rsp);
            return;
        }

        rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "What's your problem?");
    }

    @Override
    public void destroy() {
        // Nothing todo.
    }

}


text:
class GraphicalFrontend: public Frontend
{
protected:
    int width, height;
public:
    GraphicalFrontend(SimulationParameters& parameters) : Frontend(parameters) {
        width = parameters.get<int>("windowWidth");
        height = parameters.get<int>("windowHeight");
    }
    virtual bool should_exit() = 0;
};


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

class User
  include CouchSurfer::Model
  include CouchSurfer::Validations

  key_accessor :name, :email, :postcode, :account_id

  view_by :account_id, :email
  view_by :name

  validates_presence_of :name
  validates_format_of   :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_length_of   :postcode, :is => 7, :message => "not the correct length"
  validates_uniqueness_of :name, :message => "No two Beatles have the same name"
  validates_uniqueness_of :email, :view => :by_account_id_and_email, :query => lambda{ {:key => [account_id, email]} }, :message => "Already taken!"
end

describe CouchSurfer::Validations do
  before(:all) do
    db = CouchRest.database!('couch_surfer-test')
    db.delete!
    CouchSurfer::Model.default_database = CouchRest.database!('http://127.0.0.1:5984/couch_surfer-test')
  end
  before(:each) do
    @user = User.new(:name => nil, :email => "foo.bar.com", :postcode => "WD2", :account_id => 1)
  end
  describe "Validations" do
    before(:each) do
      @user.save.should be_false
    end
    describe "presence_of" do
      it "should display relevant error messages" do
        @user.errors.on(:name).should == "can't be empty"
      end
    end
    describe "format_of" do
      it "should display relevant errors messages" do
        @user.errors.on(:email).should == "is invalid"
      end
    end
    describe "length_of" do
      it "should check the length of the field" do
        @user.errors.on(:postcode).should == "not the correct length"
      end
    end
    describe "uniqueness_of" do
      before(:all) do
        paul = User.new(:name => "Paul", :email => "paul@beatles.com", :postcode => "WD2 4WF", :account_id => 1)
        paul.save.should be_true
        @user_with_invalid_email = User.new(:name => "John", :email => "paul@beatles.com", :postcode => "WD2 4WF", :account_id => 1)
        @user_with_invalid_name = User.new(:name => "Paul", :email => "george@beatles.com", :postcode => "WD2 4WF", :account_id => 1)
      end

      describe "basic" do
        it "should display relevant errors messages" do
          @user_with_invalid_name.save.should be_false
          @user_with_invalid_name.errors.on(:name).should == "No two Beatles have the same name"
        end

        it "should save if the user is unique within the scope" do
          @user_with_invalid_name.name = "George"
          @user_with_invalid_name.save.should be_true
        end
      end

      describe "with scope" do
        it "should display relevant error messages" do
          @user_with_invalid_email.save.should be_false
          @user_with_invalid_email.errors.on(:email).should == "Already taken!"
        end

        it "should save if the user is unique within the scope" do
          @user_with_invalid_email.email = "george@beatles.com"
          @user_with_invalid_email.save.should be_true
        end
      end

    end
    describe "when valid" do
      it "should save the document" do
        @user.name = "Foo"
        @user.postcode = "WD2 3AX"
        @user.email = "foo2@bar.com"
        @user.save.should be_true
      end
    end
  end

end


text:
mainModule.filter('context', function() {
   return function (input, id) {
       $('#' + id).attr("value", input);
   }
});


text:
package com.lotaris.maven.plugin.glassfish.model;

import java.util.Set;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Represent the information for the hosts to add
 *
 * @author Laurent Prevost, laurent.prevost@lotaris.com
 */
public class JmsHost {
	@Parameter(required = true)
	private String name;

	@Parameter(required = true)
	private String mqHost;

	@Parameter
	private Integer mqPort;

	@Parameter
	private String mqUser;

	@Parameter
	private String mqPassword;

	@Parameter
	private Set<Property> properties;

	public String getMqHost() {
		return mqHost;
	}

	public String getName() {
		return name;
	}

	public String getMqPassword() {
		return mqPassword;
	}

	public Integer getMqPort() {
		return mqPort;
	}

	public boolean hasProperties() {
		return properties != null && !properties.isEmpty();
	}

	public Set<Property> getProperties() {
		return properties;
	}

	public String getMqUser() {
		return mqUser;
	}

	@Override
	public String toString() {
		return
			"mqhost=" + mqHost + ", " +
			"mqpassword=" + mqPassword + ", " +
			"mqport=" + mqPort + ", " +
			"mquser=" + mqUser + ", " +
			"name=" + name + ", " +
			"properties=" + properties;
	}
}


text:
<form action="form/goto.php?OLD=<?php echo $_GET['FS']; ?>" method="post">
<input type="text" name="dir" class="imp"><input class="imp" type="submit" value="go">
</form>


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExpressiveReflection.Tests
{
    [TestClass]
    public class APIEquivalenceComparisonTests
    {
        [TestMethod]
        public void Test001()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(string).GetMethod("ToString", new Type[] { });
            var member2 = typeof(object).GetMethod("ToString", new Type[] { });

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test002()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(string).GetMethod("ToString", new Type[] { typeof(IFormatProvider) });
            var member2 = typeof(object).GetMethod("ToString", new Type[] { });

            Assert.IsFalse(comparison.Matches(member1, member2));
        }

        class Dummy01 : IEnumerable
        {
            public IEnumerator GetEnumerator()
            {
                throw new NotImplementedException();
            }
        }
        [TestMethod]
        public void Test003()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy01).GetMethod("GetEnumerator", new Type[] { });
            var member2 = typeof(IEnumerable).GetMethod("GetEnumerator", new Type[] { });

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        class Dummy02 : IEnumerable
        {
            public IEnumerator GetEnumerator()
            {
                throw new NotImplementedException();
            }
        }
        [TestMethod]
        public void Test004()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy01).GetMethod("GetEnumerator", new Type[] { });
            var member2 = typeof(Dummy02).GetMethod("GetEnumerator", new Type[] { });

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test005()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(ICollection<string>).GetProperty("Count");
            var member2 = typeof(List<string>).GetProperty("Count");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test006()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(List<string>).GetProperty("Count");
            var member2 = typeof(ICollection<string>).GetProperty("Count");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test007()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(HashSet<string>).GetProperty("Count");
            var member2 = typeof(List<string>).GetProperty("Count");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test008()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(List<string>).GetProperty("Count");
            var member2 = typeof(HashSet<string>).GetProperty("Count");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        interface IDummy03 {
            int X { set; }
        }
        class Dummy04 : IDummy03 {
            public int X { set { } }
        }
        class Dummy05 : IDummy03 {
            public int X { set { } }
        }

        [TestMethod]
        public void Test009()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(IDummy03).GetProperty("X");
            var member2 = typeof(Dummy04).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test010()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy04).GetProperty("X");
            var member2 = typeof(IDummy03).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test011()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy05).GetProperty("X");
            var member2 = typeof(Dummy04).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test012()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy04).GetProperty("X");
            var member2 = typeof(Dummy05).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        class Dummy06 {
            public virtual int X { get { return default(int); } }
        }
        class Dummy07 : Dummy06
        {
        }
        class Dummy08 : Dummy06 {
            public override int X { get { return default(int); } }
        }

        [TestMethod]
        public void Test013()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy06).GetProperty("X");
            var member2 = typeof(Dummy07).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test014()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy06).GetProperty("X");
            var member2 = typeof(Dummy08).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test015()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy07).GetProperty("X");
            var member2 = typeof(Dummy06).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test016()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy08).GetProperty("X");
            var member2 = typeof(Dummy06).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test017()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy08).GetProperty("X");
            var member2 = typeof(Dummy07).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test018()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy07).GetProperty("X");
            var member2 = typeof(Dummy08).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        class Dummy09
        {
            public virtual int X { set {  } }
        }
        class Dummy10 : Dummy09
        {
        }
        class Dummy11 : Dummy09
        {
            public override int X { set {  } }
        }

        [TestMethod]
        public void Test019()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy09).GetProperty("X");
            var member2 = typeof(Dummy10).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test020()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy09).GetProperty("X");
            var member2 = typeof(Dummy11).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test021()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy10).GetProperty("X");
            var member2 = typeof(Dummy09).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test022()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy11).GetProperty("X");
            var member2 = typeof(Dummy09).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

        [TestMethod]
        public void Test023()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy11).GetProperty("X");
            var member2 = typeof(Dummy10).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }
        [TestMethod]
        public void Test024()
        {
            var comparison = new APIEquivalenceComparison();

            var member1 = typeof(Dummy10).GetProperty("X");
            var member2 = typeof(Dummy11).GetProperty("X");

            Assert.IsTrue(comparison.Matches(member1, member2));
        }

    }
}


text:
package net.malisis.core.client.gui.component.interaction;

import static com.google.common.base.Preconditions.*;
import static net.malisis.core.client.gui.element.position.Positions.*;

import com.google.common.base.Converter;

import net.malisis.core.client.gui.component.UIComponent;
import net.malisis.core.client.gui.component.content.IContentHolder;
import net.malisis.core.client.gui.element.size.Size;
import net.malisis.core.client.gui.event.ComponentEvent;
import net.malisis.core.client.gui.render.GuiIcon;
import net.malisis.core.client.gui.render.shape.GuiShape;
import net.malisis.core.client.gui.text.GuiText;
import net.malisis.core.renderer.font.FontOptions;
import net.malisis.core.util.MouseButton;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextFormatting;

/**
 * @author Ordinastie
 *
 */
public class UISlider<T> extends UIComponent implements IContentHolder
{
	private static int SLIDER_WIDTH = 8;

	/** Text to display over the slider. */
	protected final GuiText text;

	/** Current value. */
	protected T value;
	/** Position offset of the slider. */
	protected float offset;

	/** Amount of offset scrolled by when using the scroll wheel. */
	protected float scrollStep = 0.05F;

	/** Converter from float (0-1 offset) to the value. */
	protected Converter<Float, T> converter;

	public UISlider(int width, Converter<Float, T> converter, String text)
	{
		this.converter = checkNotNull(converter);
		this.value = converter.convert(0F);

		this.text = GuiText	.builder()
							.parent(this)
							.text(text)
							.position(this::textPosition, o -> middleAligned(o, 0))
							.bind("value", this::getValue)
							.zIndex(this::getZIndex)
							.fontOptions(FontOptions.builder().color(0xFFFFFF).shadow().when(this::isHovered).color(0xFFFFA0).build())
							.build();

		setSize(Size.of(width, 20));

		GuiShape sliderShape = GuiShape	.builder(this)
										.position(this::scrollPosition, 0)
										.size(Size.of(SLIDER_WIDTH, () -> size().height()))
										.icon(GuiIcon.SLIDER)
										.border(5)
										.build();
		setBackground(GuiShape.builder(this).icon(GuiIcon.SLIDER_BG).build());
		setForeground(this.text.and(sliderShape));
	}

	//#region Getters/Setters
	@Override
	public GuiText content()
	{
		return text;
	}

	/**
	 * Sets the value for this {@link UISlider}.
	 *
	 * @param value the value
	 * @return this UI slider
	 */
	public UISlider<T> setValue(T value)
	{
		if (this.value == value)
			return this;
		if (!fireEvent(new ComponentEvent.ValueChange<>(this, this.value, value)))
			return this;

		this.value = value;
		this.offset = MathHelper.clamp(converter.reverse().convert(value), 0, 1);
		return this;
	}

	/**
	 * Gets the value for this {@link UISlider}.
	 *
	 * @return the value
	 */
	public T getValue()
	{
		return value;
	}

	public void setFontOptions(FontOptions fontOptions)
	{
		text.setFontOptions(fontOptions);
	}

	public int scrollPosition()
	{
		return (int) (offset * (size().width() - SLIDER_WIDTH));
	}

	public int textPosition()
	{
		int w = size().width(); //width
		int tw = text.size().width(); //text width
		int tx = (w - tw) / 2; //text x
		int sx = scrollPosition(); //scroll x

		if (sx > w / 2)
		{
			if (tx + tw + 2 > sx)
				return sx - tw - 2;
		}
		else
		{
			if (sx + SLIDER_WIDTH + 2 > tx)
				return sx + SLIDER_WIDTH + 2;
		}
		return tx;
	}

	/**
	 * Sets the amount of offset to scroll with the wheel.
	 *
	 * @param scrollStep the scroll step
	 * @return the UI slider
	 */
	public UISlider<T> setScrollStep(float scrollStep)
	{
		this.scrollStep = scrollStep;
		return this;
	}

	//#end Getters/Setters
	@Override
	public boolean onClick()
	{
		slideTo();
		return true;
	}

	@Override
	public boolean onScrollWheel(int delta)
	{
		slideTo(offset + delta * scrollStep);
		return true;
	}

	@Override
	public boolean onDrag(MouseButton button)
	{
		slideTo();
		return true;
	}

	/**
	 * Slides the slider to the specified pixel position.

	 */
	public void slideTo()
	{
		int l = size().width() - SLIDER_WIDTH;
		int pos = MathHelper.clamp(mousePosition().x() - SLIDER_WIDTH / 2, 0, l);
		slideTo((float) pos / l);
	}

	/**
	 * Slides the slider to the specified offset between 0 and 1.

	 * Sets the value relative to the offset.
	 *
	 * @param offset the offset
	 */
	public void slideTo(float offset)
	{
		if (!isEnabled())
			return;

		setValue(converter.convert(MathHelper.clamp(offset, 0, 1)));
	}

	@Override
	public String getPropertyString()
	{
		return "[" + TextFormatting.GREEN + text + " | " + text.position() + "@" + text.size() + TextFormatting.RESET + "] "
				+ super.getPropertyString();
	}
}


text:
namespace Microsoft.TeamFoundation.VersionControl.Client
{
    public class GetStatus
    {
        internal GetStatus(int numOperations)
        {
            this.NumOperations = numOperations;
        }

        public int NumOperations { get; private set; }
    }
}


text:
import React from 'react'; // eslint-disable-line import/no-extraneous-dependencies
import Spinner from '../../src/';
import { spinkitSpinners, loadersCssSpinners } from '../../src/spinners';

const colors = [
  'aqua',
  'blue',
  'coral',
  'fuchsia',
  'goldenrod',
  'green',
  'olive',
  'orange',
  'purple',
  'red',
  'steelblue',
];

function randomColor() {
  return colors[Math.floor(Math.random() * colors.length)];
}

function spinnerPreview(spinner, idx) {
  const color = randomColor();
  return (

        <Spinner name="{spinner}" />
        <Spinner name={spinner} />

        <Spinner name="{spinner}" color="{color}"/>
        <Spinner name={spinner} color={color} />

  );
}

function SpinnerExamples() {
  return (

React-Spinkit

      Browse code on GitHub

Spinkit Spinners

      {Object.keys(spinkitSpinners).map(spinnerPreview)}

loaders.css Spinners

(not all of these center here, but are easily centerable with flexbox)

      {Object.keys(loadersCssSpinners).map(spinnerPreview)}

Spinner Options

      <Spinner name="wordpress" fadeIn="none" />
      <Spinner name="wordpress" fadeIn="none" />

      <Spinner name="wordpress" fadeIn="quarter" />
      <Spinner name="wordpress" fadeIn="quarter" />

      <Spinner name="wordpress" fadeIn="half" />
      <Spinner name="wordpress" fadeIn="half" />

        <Spinner name="wordpress" overrideSpinnerClassName="my-class-to-override" />

      <Spinner name="wordpress" overrideSpinnerClassName="my-class-to-override" />

      <Spinner name="wordpress" className="my-class" />
      <Spinner name="wordpress" className="my-class" />

      <Spinner name="wordpress" color="green" />
      <Spinner name="wordpress" color="green" />

  );
}

export default SpinnerExamples;


text:
title: Proof of Concept Cordova integration with Brackets
date: 2014-07-08 10:18:00 Z
tags:
- PhoneGap Network
author: Raymond Camden
external: true
link: http://www.raymondcamden.com/2014/07/08/Proof-of-Concept-Cordova-integration-with-Brackets
type: post
format: html
status: publish
---

The past few days I've been working on a new Brackets extension that integrated with the Cordova command line tool. I've got a rough draft of it ready with almost every feature prepared so I thought I'd go ahead and let people know in case they wanted to start hacking on it. As it is not complete yet I've not added it to the extension manager, but once I wrap the last feature I'll go ahead and submit it. You can find the code for the extension on GitHub: https://github.com/cfjedimaster/Cordova-Extension.

The extension relies on the Cordova CLI to exist, so keep that in mind, and it assumes you've already set up some mobile SDKs already. This extension doesn't remove the need to go through those steps, it merely serves to help you use those tools from within Brackets. Once loaded, you get a new icon in the right side menu:

It is a bit hard to see, but the icon is grayscale. Switching to a Cordova project switches the state to enabled.

Clicking the icon opens up a bottom panel with two tabs: Platforms and Plugins. Platforms is just that - a list of currently installed platforms for the project as well as which are enabled.

All I'm doing here is wrapping calls to the CLI. To be clear, I don't think the Cordova CLI is hard to use, but I think having a quick visual look at my Cordova settings is pretty useful. Note that there is poor visual feedback currently in the extension. The very first time you use a platform, like Firefox OS, the CLI will fetch the bits remotely. That can take 30-60 seconds. My extension doesn't provide any good visual feedback that it is working. It will correctly update the UI when done, but you don't get a loading indicator. For platforms already installed system-wide though it will be super quick. Also, Run doesn't actually work well now. I emulate more often anyway.

The next tab is Plugins. This will allow you to list, remove, and add plugins. Currently only list works.

The search field will hit plugins.cordova.io and use autocomplete. I may even "fudge" it a bit since "accelerometer" doesn't match the plugin it uses (device-motion). You won't believe how many times that screws me up.

Anyway, I think this plugin could be useful more for the "what am I using" feature than actually firing off builds and modifying platforms. Let me know what you think. I wrote the code somewhat quickly so it has not been linted yet. I plan on doing that before my "official" release for 1.0.


text:
namespace content {
class BrowserContext;
}  // namespace content

namespace page_actions {
class ServiceImpl : public Service, public content_injection::Provider {
 public:
  ServiceImpl(content::BrowserContext* browser_context);
  ~ServiceImpl() override;
  ServiceImpl(const ServiceImpl&) = delete;
  ServiceImpl& operator=(const ServiceImpl&) = delete;

  void Load();

  // Implementing Service
  bool IsLoaded() override;
  bool AddPath(const base::FilePath& path) override;
  bool UpdatePath(const base::FilePath& old_path,
                  const base::FilePath& new_path) override;
  bool RemovePath(const base::FilePath& path) override;
  std::vector<base::FilePath> GetAllScriptPaths() override;
  bool SetScriptOverrideForTab(content::WebContents* tab_contents,
                               const base::FilePath& script_path,
                               ScriptOverride script_override) override;
  void AddObserver(Observer* observer) override;
  void RemoveObserver(Observer* observer) override;

  // Implementing content_injection::Provider
  content_injection::mojom::InjectionsForFramePtr GetInjectionsForFrame(
      const GURL& url,
      content::RenderFrameHost* frame) override;
  const std::map<std::string, content_injection::StaticInjectionItem>&
  GetStaticContent() override;

 private:
  class RestoreInfo : public content::WebContentsObserver {
   public:
    RestoreInfo(content::WebContents* web_contents);
    ~RestoreInfo() override;
    RestoreInfo(const RestoreInfo& other) = delete;
    RestoreInfo& operator=(const RestoreInfo& other) = delete;

    void Add(const base::FilePath& script_path,
             page_actions::Service::ScriptOverride script_override);
    const std::map<base::FilePath, page_actions::Service::ScriptOverride>&
    script_overrides() const {
      return script_overrides_;
    }

    // Implementing content::WebContentsObserver;
    void WebContentsDestroyed() override;

   private:
    std::map<base::FilePath, page_actions::Service::ScriptOverride>
        script_overrides_;
  };

  void OnFilesUpdated(DirectoryWatcher::UpdatedFileContents updated_contents,
                      std::vector<base::FilePath> invalid_paths);

  void RestoreOverrides();
  bool DoSetScriptOverrideForTab(content::WebContents* tab_contents,
                                 const base::FilePath& script_path,
                                 ScriptOverride script_override);

  void RebuildStaticInjections();

  content::BrowserContext* browser_context_;
  std::map<base::FilePath, ScriptDirectory> directories_;

  std::map<content::WebContents*, RestoreInfo> script_overrides_to_restore_;

  std::unique_ptr<DirectoryWatcher, DirectoryWatcher::Deleter>
      directory_watcher_;
  std::map<std::string, content_injection::StaticInjectionItem>
      static_injections_;
  absl::optional<int> javascript_world_id_;

  base::ObserverList<Observer> observers_;

  base::WeakPtrFactory<ServiceImpl> weak_factory_{this};
};
}  // namespace page_actions

#endif  // COMPONENTS_PAGE_ACTIONS_PAGE_ACTIONS_SERVICE_IMPL_H_


text:
namespace app_list {
class SearchBoxModel;
class SearchResult;
}

class AutocompleteController;
class AutocompleteResult;
class ExtensionAppProvider;
class Profile;

// SearchBuilder creates app list search results via AutoCompleteController.
class SearchBuilder : public AutocompleteControllerDelegate {
 public:
  SearchBuilder(Profile* profile,
                app_list::SearchBoxModel* search_box,
                app_list::AppListModel::SearchResults* results);
  virtual ~SearchBuilder();

  void StartSearch();
  void StopSearch();

  void OpenResult(const app_list::SearchResult& result, int event_flags);

 private:
  // Populates result list from AutocompleteResult.
  void PopulateFromACResult(const AutocompleteResult& result);

  // AutocompleteControllerDelegate overrides:
  virtual void OnResultChanged(bool default_match_changed) OVERRIDE;

  Profile* profile_;

  // Sub models of AppListModel that represent search box and result list.
  app_list::SearchBoxModel* search_box_;
  app_list::AppListModel::SearchResults* results_;

  // The omnibox AutocompleteController that collects/sorts/dup-
  // eliminates the results as they come in.
  scoped_ptr<AutocompleteController> controller_;

  // ExtensionAppProvider used for apps only mode. If apps only mode becomes the
  // only mode, remove the AutocompleteController above. Otherwise, remove this.
  scoped_refptr<ExtensionAppProvider> apps_provider_;

  DISALLOW_COPY_AND_ASSIGN(SearchBuilder);
};

#endif  // CHROME_BROWSER_UI_VIEWS_ASH_APP_LIST_SEARCH_BUILDER_H_


text:
package com.dattack.jtoolbox.util;

import org.junit.jupiter.api.Test;

import static com.dattack.junit.AssertionsExt.assertTrue;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Test for {@link com.dattack.jtoolbox.util.MultiStopWatch}.
 *
 * @author cvarela
 * @since 0.6
 */
@SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts")
/* default */ class MultiStopWatchTest {

    private static final String EVENT_1 = "event-1";
    private static final String EVENT_2 = "event-2";

    @Test /* default */ void emptyStopWatch() {
        MultiStopWatch stopWatch = new MultiStopWatch();
        long elapsedTime = stopWatch.getElapsedTimeInNanos();
        assertEquals(0, elapsedTime, "Invalid elapsed time for a stopwatch without events");
    }

    @Test /* default */ void eventWithoutStart() throws InterruptedException {
        MultiStopWatch stopWatch = new MultiStopWatch();
        doWait(1_000);
        stopWatch.stop(EVENT_1);
        doWait(1_000);
        long elapsedTime = stopWatch.getElapsedTimeInMillis();

        assertAll("elapsed time",
                () -> assertTrue(elapsedTime >= 1_000, "elapsed time should be at least 1000ms."),
                () -> assertTrue(elapsedTime < 2_000, "elapsed time should be less than 2000ms.")
        );
    }

    @Test /* default */ void eventWithoutStop() throws InterruptedException {
        MultiStopWatch stopWatch = new MultiStopWatch();
        doWait(1_000);
        stopWatch.start(EVENT_1);
        doWait(1_000);
        assertTrue(stopWatch.getElapsedTimeInMillis() >= 2_000, "elapsed time should be at least 2000ms.");
    }

    @Test /* default */ void startAndStop() throws InterruptedException {
        MultiStopWatch stopWatch = new MultiStopWatch();

        for (int i = 0; i < 3; i++) { // 1000 + 1100 + 1200 = 3300
            stopWatch.start(EVENT_1);
            doWait(1_000 + 100 * i);
            stopWatch.stop(EVENT_1);
        }

        stopWatch.start(EVENT_2);
        doWait(300);
        stopWatch.stop(EVENT_2);

        doWait(500);

        stopWatch.start(EVENT_1);
        doWait(100);
        stopWatch.stop(EVENT_1);

        long elapsedTimeEvent1 = stopWatch.getElapsedTimeInMillis(EVENT_1);
        long elapsedTimeEvent2 = stopWatch.getElapsedTimeInMillis(EVENT_2);
        long elapsedTime = stopWatch.getElapsedTimeInMillis();

        assertAll("elapsed time",
                () -> assertTrue(elapsedTime > 4_200, "elapsed time should be at least 4200ms."),
                () -> assertAll(EVENT_1,
                        () -> assertTrue(elapsedTimeEvent1 >= 3_400, "elapsed time should be at least 3400ms."),
                        () -> assertTrue(elapsedTimeEvent1 < 3_600, "elapsed time should be less than 3600ms.")
                ),
                () -> assertAll(EVENT_2,
                        () -> assertTrue(elapsedTimeEvent2 < 400, "elapsed time should be less than 400ms.")
                )
        );
    }

    private void doWait(long timeout) throws InterruptedException {
        synchronized (this) {
            wait(timeout);
        }
    }
}


text:
package ee.ria.xroad.signer.protocol.handler;

import ee.ria.xroad.common.CodedException;
import ee.ria.xroad.common.cert.CertChain;
import ee.ria.xroad.common.cert.CertChainVerifier;
import ee.ria.xroad.common.conf.globalconf.GlobalConf;
import ee.ria.xroad.common.identifier.ClientId;
import ee.ria.xroad.common.util.CertUtils;
import ee.ria.xroad.signer.certmanager.OcspResponseManager;
import ee.ria.xroad.signer.protocol.dto.CertRequestInfo;
import ee.ria.xroad.signer.protocol.dto.CertificateInfo;
import ee.ria.xroad.signer.protocol.dto.KeyInfo;
import ee.ria.xroad.signer.protocol.dto.KeyUsageInfo;
import ee.ria.xroad.signer.protocol.dto.TokenInfo;
import ee.ria.xroad.signer.protocol.message.ImportCert;
import ee.ria.xroad.signer.protocol.message.ImportCertResponse;
import ee.ria.xroad.signer.tokenmanager.TokenManager;
import ee.ria.xroad.signer.util.SignerUtil;

import lombok.extern.slf4j.Slf4j;

import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Date;

import static ee.ria.xroad.common.ErrorCodes.X_CERT_EXISTS;
import static ee.ria.xroad.common.ErrorCodes.X_CERT_IMPORT_FAILED;
import static ee.ria.xroad.common.ErrorCodes.X_INCORRECT_CERTIFICATE;
import static ee.ria.xroad.common.ErrorCodes.X_KEY_NOT_FOUND;
import static ee.ria.xroad.common.ErrorCodes.X_WRONG_CERT_USAGE;
import static ee.ria.xroad.common.util.CryptoUtils.calculateCertHexHash;
import static ee.ria.xroad.common.util.CryptoUtils.encodeBase64;
import static ee.ria.xroad.common.util.CryptoUtils.readCertificate;

/**
 * Handles certificate import requests.
 */
@Slf4j
public class ImportCertRequestHandler
        extends AbstractDeleteFromKeyInfo<ImportCert> {

    @Override
    protected Object handle(ImportCert message) throws Exception {
        X509Certificate cert = null;
        try {
            cert = readCertificate(message.getCertData());
        } catch (Exception e) {
            throw CodedException.tr(X_INCORRECT_CERTIFICATE,
                    "failed_to_parse_cert",
                    "Failed to parse certificate: %s", e.getMessage());
        }

        String keyId = importCertificate(cert, message.getInitialStatus(),
                message.getMemberId());
        return new ImportCertResponse(keyId);
    }

    private String importCertificate(X509Certificate cert,
            String initialStatus, ClientId memberId) throws Exception {
        String publicKey = encodeBase64(cert.getPublicKey().getEncoded());

        // Find the key based on the public key of the cert
        for (TokenInfo tokenInfo : TokenManager.listTokens()) {
            for (KeyInfo keyInfo : tokenInfo.getKeyInfo()) {
                if (matchesPublicKeyOrExistingCert(publicKey, cert, keyInfo)) {
                    String keyId = keyInfo.getId();
                    log.debug("Importing certificate under key '{}'", keyId);

                    importCertificateToKey(keyInfo, cert, initialStatus,
                            memberId);
                    return keyId;
                }
            }
        }

        throw CodedException.tr(X_KEY_NOT_FOUND,
                "key_not_found_for_certificate",
                "Could not find key that has public key that matches the "
                        + "public key of certificate");
    }

    // XXX: #2955 Currently, if the key does not have public key, we also check
    // if the key contains the (unsaved) certificate
    private boolean matchesPublicKeyOrExistingCert(String publicKey,
            X509Certificate cert, KeyInfo keyInfo) throws Exception {
        if (keyInfo.getPublicKey() != null
                && keyInfo.getPublicKey().equals(publicKey)) {
            return true;
        }

        for (CertificateInfo certInfo : keyInfo.getCerts()) {
            if (Arrays.equals(certInfo.getCertificateBytes(),
                    cert.getEncoded())) {
                return true;
            }
        }

        return false;
    }

    private void importCertificateToKey(KeyInfo keyInfo, X509Certificate cert,
            String initialStatus, ClientId memberId) throws Exception {
        String certHash = calculateCertHexHash(cert.getEncoded());

        CertificateInfo existingCert =
                TokenManager.getCertificateInfoForCertHash(certHash);
        if (existingCert != null && existingCert.isSavedToConfiguration()) {
            throw CodedException.tr(X_CERT_EXISTS,
                    "cert_exists_under_key",
                    "Certificate already exists under key '%s'",
                    keyInfo.getFriendlyName() == null
                        ? keyInfo.getId()
                        : keyInfo.getFriendlyName());
        }

        boolean signing = CertUtils.isSigningCert(cert);
        boolean authentication = CertUtils.isAuthCert(cert);

        if (signing && authentication) {
            throw CodedException.tr(X_WRONG_CERT_USAGE,
                    "wrong_cert_usage.both",
                    "Both signing and authentication, "
                            + "only one of them allowed.");
        }

        KeyUsageInfo keyUsage = getKeyUsage(keyInfo, signing);

        validateCertKeyUsage(signing, authentication, keyUsage);
        verifyCertChain(cert);

        if (existingCert != null) {
            TokenManager.removeCert(existingCert.getId());
        }

        CertificateInfo certType = new CertificateInfo(memberId,
                !authentication, true, initialStatus, SignerUtil.randomId(),
                cert.getEncoded(), null);

        TokenManager.addCert(keyInfo.getId(), certType);
        TokenManager.setKeyUsage(keyInfo.getId(), keyUsage);
        updateOcspResponse(cert);

        log.info("Imported certificate to key '{}', certificate hash:\n{}",
                keyInfo.getId(), certHash);

        deleteCertRequest(keyInfo.getId(), memberId);
    }

    private void updateOcspResponse(X509Certificate cert) {
        try {
            OcspResponseManager.getOcspResponse(getContext(), cert);
        } catch (Exception e) {
            log.error("Failed to update OCSP response for certificate "
                    + cert.getSerialNumber(), e);
        }
    }

    private void validateCertKeyUsage(boolean signing, boolean authentication,
            KeyUsageInfo keyUsage) {
        // Check that the cert is a signing or auth cert
        if (!signing && !authentication) {
            throw CodedException.tr(X_WRONG_CERT_USAGE,
                    "wrong_cert_usage.none",
                    "Certificate cannot be used for signing nor "
                            + "authentication");
        }

        // Check that the key usage and cert usage match
        if (authentication && !signing
                && keyUsage != KeyUsageInfo.AUTHENTICATION) {
            throw CodedException.tr(X_WRONG_CERT_USAGE,
                    "wrong_cert_usage.auth_to_sign",
                    "Authentication certificate cannot be imported to "
                            + "signing keys");
        }

        if (signing && !authentication && keyUsage != KeyUsageInfo.SIGNING) {
            throw CodedException.tr(X_WRONG_CERT_USAGE,
                    "wrong_cert_usage.sign_to_auth",
                    "Signing certificate cannot be imported to "
                            + "authentication keys");
        }
    }

    private void verifyCertChain(X509Certificate cert) {
        if (CertUtils.isSelfSigned(cert)) {
            // do not verify self-signed certs
            return;
        }

        GlobalConf.verifyValidity();
        try {
            CertChain chain = CertChain.create(
                    GlobalConf.getInstanceIdentifier(), cert, null);
            new CertChainVerifier(chain).verifyChainOnly(new Date());
        } catch (Exception e) {
            log.error("Failed to import certificate", e);
            throw CodedException.tr(X_CERT_IMPORT_FAILED,
                    "cert_import_failed", "%s", "Certificate is not valid");
        }
    }

    protected void deleteCertRequest(String keyId, ClientId memberId)
            throws Exception {
        CertRequestInfo certReq =
                TokenManager.getCertRequestInfo(keyId, memberId);
        if (certReq != null) {
            deleteCertRequest(certReq.getId());
        }
    }

    private static KeyUsageInfo getKeyUsage(KeyInfo keyInfo, boolean sign) {
        KeyUsageInfo keyUsage = keyInfo.getUsage();
        if (keyUsage == null) {
            return sign ? KeyUsageInfo.SIGNING : KeyUsageInfo.AUTHENTICATION;
        }

        return keyUsage;
    }
}