text:
RTIMUMPU9150::RTIMUMPU9150(RTIMUSettings *settings) : RTIMU(settings)
{

}

RTIMUMPU9150::~RTIMUMPU9150()
{
}

bool RTIMUMPU9150::setLpf(unsigned char lpf)
{
    switch (lpf) {
    case MPU9150_LPF_256:
    case MPU9150_LPF_188:
    case MPU9150_LPF_98:
    case MPU9150_LPF_42:
    case MPU9150_LPF_20:
    case MPU9150_LPF_10:
    case MPU9150_LPF_5:
        m_lpf = lpf;
        return true;

    default:
        HAL_ERROR1("Illegal MPU9150 lpf %d\n", lpf);
        return false;
    }
}

bool RTIMUMPU9150::setSampleRate(int rate)
{
    if ((rate < MPU9150_SAMPLERATE_MIN) || (rate > MPU9150_SAMPLERATE_MAX)) {
        HAL_ERROR1("Illegal sample rate %d\n", rate);
        return false;
    }
    m_sampleRate = rate;
    m_sampleInterval = (uint64_t)1000000 / m_sampleRate;
    return true;
}

bool RTIMUMPU9150::setCompassRate(int rate)
{
    if ((rate < MPU9150_COMPASSRATE_MIN) || (rate > MPU9150_COMPASSRATE_MAX)) {
        HAL_ERROR1("Illegal compass rate %d\n", rate);
        return false;
    }
    m_compassRate = rate;
    return true;
}

bool RTIMUMPU9150::setGyroFsr(unsigned char fsr)
{
    switch (fsr) {
    case MPU9150_GYROFSR_250:
        m_gyroFsr = fsr;
        m_gyroScale = RTMATH_PI / (131.0 * 180.0);
        return true;

    case MPU9150_GYROFSR_500:
        m_gyroFsr = fsr;
        m_gyroScale = RTMATH_PI / (62.5 * 180.0);
        return true;

    case MPU9150_GYROFSR_1000:
        m_gyroFsr = fsr;
        m_gyroScale = RTMATH_PI / (32.8 * 180.0);
        return true;

    case MPU9150_GYROFSR_2000:
        m_gyroFsr = fsr;
        m_gyroScale = RTMATH_PI / (16.4 * 180.0);
        return true;

    default:
        HAL_ERROR1("Illegal MPU9150 gyro fsr %d\n", fsr);
        return false;
    }
}

bool RTIMUMPU9150::setAccelFsr(unsigned char fsr)
{
    switch (fsr) {
    case MPU9150_ACCELFSR_2:
        m_accelFsr = fsr;
        m_accelScale = 1.0/16384.0;
        return true;

    case MPU9150_ACCELFSR_4:
        m_accelFsr = fsr;
        m_accelScale = 1.0/8192.0;
        return true;

    case MPU9150_ACCELFSR_8:
        m_accelFsr = fsr;
        m_accelScale = 1.0/4096.0;
        return true;

    case MPU9150_ACCELFSR_16:
        m_accelFsr = fsr;
        m_accelScale = 1.0/2048.0;
        return true;

    default:
        HAL_ERROR1("Illegal MPU9150 accel fsr %d\n", fsr);
        return false;
    }
}

bool RTIMUMPU9150::IMUInit()
{
    unsigned char result;

    m_firstTime = true;

#ifdef MPU9150_CACHE_MODE
    m_cacheIn = m_cacheOut = m_cacheCount = 0;
#endif

    // set validity flags

    m_imuData.fusionPoseValid = false;
    m_imuData.fusionQPoseValid = false;
    m_imuData.gyroValid = true;
    m_imuData.accelValid = true;
    m_imuData.compassValid = true;
    m_imuData.pressureValid = false;
    m_imuData.temperatureValid = false;
    m_imuData.humidityValid = false;

    //  configure IMU

    m_slaveAddr = m_settings->m_I2CSlaveAddress;

    setSampleRate(m_settings->m_MPU9150GyroAccelSampleRate);
    setCompassRate(m_settings->m_MPU9150CompassSampleRate);
    setLpf(m_settings->m_MPU9150GyroAccelLpf);
    setGyroFsr(m_settings->m_MPU9150GyroFsr);
    setAccelFsr(m_settings->m_MPU9150AccelFsr);

    setCalibrationData();

    //  enable the I2C bus

    if (!m_settings->HALOpen())
        return false;

    //  reset the MPU9150

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_PWR_MGMT_1, 0x80, "Failed to initiate MPU9150 reset"))
        return false;

    m_settings->delayMs(100);

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_PWR_MGMT_1, 0x00, "Failed to stop MPU9150 reset"))
        return false;

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_WHO_AM_I, 1, &result, "Failed to read MPU9150 id"))
        return false;

    if (result != MPU9150_ID) {
        HAL_ERROR1("Incorrect MPU9150 id %d\n", result);
        return false;
    }

    //  now configure the various components

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_LPF_CONFIG, m_lpf, "Failed to set lpf"))
        return false;

    if (!setSampleRate())
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_GYRO_CONFIG, m_gyroFsr, "Failed to set gyro fsr"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_ACCEL_CONFIG, m_accelFsr, "Failed to set accel fsr"))
         return false;

    //  now configure compass

    if (!configureCompass())
        return false;

    //  enable the sensors

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_PWR_MGMT_1, 1, "Failed to set pwr_mgmt_1"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_PWR_MGMT_2, 0, "Failed to set pwr_mgmt_2"))
         return false;

    //  select the data to go into the FIFO and enable

    if (!resetFifo())
        return false;

    gyroBiasInit();

    HAL_INFO("MPU9150 init complete\n");
    return true;
}

bool RTIMUMPU9150::configureCompass()
{
    unsigned char asa[3];
    unsigned char id;

    m_compassIs5883 = false;
    m_compassDataLength = 8;

    bypassOn();

    // get fuse ROM data

    if (!m_settings->HALWrite(AK8975_ADDRESS, AK8975_CNTL, 0, "Failed to set compass in power down mode 1")) {
        bypassOff();
        return false;
    }

    if (!m_settings->HALWrite(AK8975_ADDRESS, AK8975_CNTL, 0x0f, "Failed to set compass in fuse ROM mode")) {
        bypassOff();
        return false;
    }

    if (!m_settings->HALRead(AK8975_ADDRESS, AK8975_ASAX, 3, asa, "")) {

        //  check to see if an HMC5883L is fitted

        if (!m_settings->HALRead(HMC5883_ADDRESS, HMC5883_ID, 1, &id, "Failed to find 5883")) {
            bypassOff();

            //  this is returning true so that MPU-6050 by itself will work

            HAL_INFO("Detected MPU-6050 without compass\n");

            m_imuData.compassValid = false;
            return true;
        }
        if (id != 0x48) {                                   // incorrect id for HMC5883L

            bypassOff();

            //  this is returning true so that MPU-6050 by itself will work

            HAL_INFO("Detected MPU-6050 without compass\n");

            m_imuData.compassValid = false;
            return true;
        }

        // HMC5883 is present - use that

        if (!m_settings->HALWrite(HMC5883_ADDRESS, HMC5883_CONFIG_A, 0x38, "Failed to set HMC5883 config A")) {
            bypassOff();
            return false;
        }

        if (!m_settings->HALWrite(HMC5883_ADDRESS, HMC5883_CONFIG_B, 0x20, "Failed to set HMC5883 config B")) {
            bypassOff();
            return false;
        }

        if (!m_settings->HALWrite(HMC5883_ADDRESS, HMC5883_MODE, 0x00, "Failed to set HMC5883 mode")) {
            bypassOff();
            return false;
        }

        HAL_INFO("Detected MPU-6050 with HMC5883\n");

        m_compassDataLength = 6;
        m_compassIs5883 = true;
    } else {

        //  convert asa to usable scale factor

        m_compassAdjust[0] = ((float)asa[0] - 128.0) / 256.0 + 1.0f;
        m_compassAdjust[1] = ((float)asa[1] - 128.0) / 256.0 + 1.0f;
        m_compassAdjust[2] = ((float)asa[2] - 128.0) / 256.0 + 1.0f;

        if (!m_settings->HALWrite(AK8975_ADDRESS, AK8975_CNTL, 0, "Failed to set compass in power down mode 2")) {
            bypassOff();
            return false;
        }
    }

    bypassOff();

    //  now set up MPU9150 to talk to the compass chip

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_MST_CTRL, 0x40, "Failed to set I2C master mode"))
        return false;

    if (m_compassIs5883) {
        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_ADDR, 0x80 | HMC5883_ADDRESS, "Failed to set slave 0 address"))
                return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_REG, HMC5883_DATA_X_HI, "Failed to set slave 0 reg"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_CTRL, 0x86, "Failed to set slave 0 ctrl"))
            return false;
    } else {
        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_ADDR, 0x80 | AK8975_ADDRESS, "Failed to set slave 0 address"))
                return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_REG, AK8975_ST1, "Failed to set slave 0 reg"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV0_CTRL, 0x88, "Failed to set slave 0 ctrl"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV1_ADDR, AK8975_ADDRESS, "Failed to set slave 1 address"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV1_REG, AK8975_CNTL, "Failed to set slave 1 reg"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV1_CTRL, 0x81, "Failed to set slave 1 ctrl"))
            return false;

        if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV1_DO, 0x1, "Failed to set slave 1 DO"))
            return false;

    }

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_MST_DELAY_CTRL, 0x3, "Failed to set mst delay"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_YG_OFFS_TC, 0x80, "Failed to set yg offs tc"))
        return false;

    if (!setCompassRate())
        return false;

    return true;
}

bool RTIMUMPU9150::resetFifo()
{
    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_INT_ENABLE, 0, "Writing int enable"))
        return false;
    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_FIFO_EN, 0, "Writing fifo enable"))
        return false;
    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_USER_CTRL, 0, "Writing user control"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_USER_CTRL, 0x04, "Resetting fifo"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_USER_CTRL, 0x60, "Enabling the fifo"))
        return false;

    m_settings->delayMs(50);

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_INT_ENABLE, 1, "Writing int enable"))
        return false;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_FIFO_EN, 0x78, "Failed to set FIFO enables"))
        return false;

    return true;
}

bool RTIMUMPU9150::bypassOn()
{
    unsigned char userControl;

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_USER_CTRL, 1, &userControl, "Failed to read user_ctrl reg"))
        return false;

    userControl &= ~0x20;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_USER_CTRL, 1, &userControl, "Failed to write user_ctrl reg"))
        return false;

    m_settings->delayMs(50);

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_INT_PIN_CFG, 0x82, "Failed to write int_pin_cfg reg"))
        return false;

    m_settings->delayMs(50);
    return true;
}

bool RTIMUMPU9150::bypassOff()
{
    unsigned char userControl;

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_USER_CTRL, 1, &userControl, "Failed to read user_ctrl reg"))
        return false;

    userControl |= 0x20;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_USER_CTRL, 1, &userControl, "Failed to write user_ctrl reg"))
        return false;

    m_settings->delayMs(50);

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_INT_PIN_CFG, 0x80, "Failed to write int_pin_cfg reg"))
         return false;

    m_settings->delayMs(50);
    return true;
}

bool RTIMUMPU9150::setSampleRate()
{
    int clockRate = 1000;

    if (m_lpf == MPU9150_LPF_256)
        clockRate = 8000;

    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_SMPRT_DIV, (unsigned char)(clockRate / m_sampleRate - 1),
                  "Failed to set sample rate"))
        return false;

    return true;
}

bool RTIMUMPU9150::setCompassRate()
{
    int rate;

    rate = m_sampleRate / m_compassRate - 1;

    if (rate > 31)
        rate = 31;
    if (!m_settings->HALWrite(m_slaveAddr, MPU9150_I2C_SLV4_CTRL, rate, "Failed to set slave ctrl 4"))
         return false;
    return true;
}

int RTIMUMPU9150::IMUGetPollInterval()
{
    return (400 / m_sampleRate);
}

bool RTIMUMPU9150::IMURead()
{
    unsigned char fifoCount[2];
    unsigned int count;
    unsigned char fifoData[12];
    unsigned char compassData[8];

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_FIFO_COUNT_H, 2, fifoCount, "Failed to read fifo count"))
         return false;

    count = ((unsigned int)fifoCount[0] << 8) + fifoCount[1];

    if (count == 1024) {
        HAL_INFO("MPU9150 fifo has overflowed");
        resetFifo();
        m_imuData.timestamp += m_sampleInterval * (1024 / MPU9150_FIFO_CHUNK_SIZE + 1); // try to fix timestamp
        return false;
    }

#ifdef MPU9150_CACHE_MODE
    if ((m_cacheCount == 0) && (count  >= MPU9150_FIFO_CHUNK_SIZE) && (count < (MPU9150_CACHE_SIZE * MPU9150_FIFO_CHUNK_SIZE))) {
        // special case of a small fifo and nothing cached - just handle as simple read

        if (!m_settings->HALRead(m_slaveAddr, MPU9150_FIFO_R_W, MPU9150_FIFO_CHUNK_SIZE, fifoData, "Failed to read fifo data"))
            return false;

        if (!m_settings->HALRead(m_slaveAddr, MPU9150_EXT_SENS_DATA_00, m_compassDataLength, compassData, "Failed to read compass data"))
            return false;
    } else {
        if (count >= (MPU9150_CACHE_SIZE * MPU9150_FIFO_CHUNK_SIZE)) {
            if (m_cacheCount == MPU9150_CACHE_BLOCK_COUNT) {
                // all cache blocks are full - discard oldest and update timestamp to account for lost samples
                m_imuData.timestamp += m_sampleInterval * m_cache[m_cacheOut].count;
                if (++m_cacheOut == MPU9150_CACHE_BLOCK_COUNT)
                    m_cacheOut = 0;
                m_cacheCount--;
            }

            int blockCount = count / MPU9150_FIFO_CHUNK_SIZE;   // number of chunks in fifo

            if (blockCount > MPU9150_CACHE_SIZE)
                blockCount = MPU9150_CACHE_SIZE;

            if (!m_settings->HALRead(m_slaveAddr, MPU9150_FIFO_R_W, MPU9150_FIFO_CHUNK_SIZE * blockCount,
                                m_cache[m_cacheIn].data, "Failed to read fifo data"))
                return false;

            if (!m_settings->HALRead(m_slaveAddr, MPU9150_EXT_SENS_DATA_00, 8, m_cache[m_cacheIn].compass, "Failed to read compass data"))
                return false;

            m_cache[m_cacheIn].count = blockCount;
            m_cache[m_cacheIn].index = 0;

            m_cacheCount++;
            if (++m_cacheIn == MPU9150_CACHE_BLOCK_COUNT)
                m_cacheIn = 0;

        }

        //  now fifo has been read if necessary, get something to process

        if (m_cacheCount == 0)
            return false;

        memcpy(fifoData, m_cache[m_cacheOut].data + m_cache[m_cacheOut].index, MPU9150_FIFO_CHUNK_SIZE);
        memcpy(compassData, m_cache[m_cacheOut].compass, 8);

        m_cache[m_cacheOut].index += MPU9150_FIFO_CHUNK_SIZE;

        if (--m_cache[m_cacheOut].count == 0) {
            //  this cache block is now empty

            if (++m_cacheOut == MPU9150_CACHE_BLOCK_COUNT)
                m_cacheOut = 0;
            m_cacheCount--;
        }
    }

#else

    if (count > MPU9150_FIFO_CHUNK_SIZE * 40) {
        // more than 40 samples behind - going too slowly so discard some samples but maintain timestamp correctly
        while (count >= MPU9150_FIFO_CHUNK_SIZE * 10) {
            if (!m_settings->HALRead(m_slaveAddr, MPU9150_FIFO_R_W, MPU9150_FIFO_CHUNK_SIZE, fifoData, "Failed to read fifo data"))
                return false;
            count -= MPU9150_FIFO_CHUNK_SIZE;
            m_imuData.timestamp += m_sampleInterval;
        }
    }

    if (count < MPU9150_FIFO_CHUNK_SIZE)
        return false;

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_FIFO_R_W, MPU9150_FIFO_CHUNK_SIZE, fifoData, "Failed to read fifo data"))
        return false;

    if (!m_settings->HALRead(m_slaveAddr, MPU9150_EXT_SENS_DATA_00, m_compassDataLength, compassData, "Failed to read compass data"))
        return false;

#endif

    RTMath::convertToVector(fifoData, m_imuData.accel, m_accelScale, true);
    RTMath::convertToVector(fifoData + 6, m_imuData.gyro, m_gyroScale, true);

    if (m_compassIs5883)
        RTMath::convertToVector(compassData, m_imuData.compass, 0.092f, true);
    else
        RTMath::convertToVector(compassData + 1, m_imuData.compass, 0.3f, false);

    //  sort out gyro axes

    m_imuData.gyro.setX(m_imuData.gyro.x());
    m_imuData.gyro.setY(-m_imuData.gyro.y());
    m_imuData.gyro.setZ(-m_imuData.gyro.z());

    //  sort out accel data;

    m_imuData.accel.setX(-m_imuData.accel.x());

    if (m_compassIs5883) {
        //  sort out compass axes

        float temp;

        temp = m_imuData.compass.y();
        m_imuData.compass.setY(-m_imuData.compass.z());
        m_imuData.compass.setZ(-temp);

    } else {

        //  use the compass fuse data adjustments

        m_imuData.compass.setX(m_imuData.compass.x() * m_compassAdjust[0]);
        m_imuData.compass.setY(m_imuData.compass.y() * m_compassAdjust[1]);
        m_imuData.compass.setZ(m_imuData.compass.z() * m_compassAdjust[2]);

        //  sort out compass axes

        float temp;

        temp = m_imuData.compass.x();
        m_imuData.compass.setX(m_imuData.compass.y());
        m_imuData.compass.setY(-temp);
    }

    //  now do standard processing

    handleGyroBias();
    calibrateAverageCompass();
    calibrateAccel();

    if (m_firstTime)
        m_imuData.timestamp = RTMath::currentUSecsSinceEpoch();
    else
        m_imuData.timestamp += m_sampleInterval;

    m_firstTime = false;

    //  now update the filter

    updateFusion();

    return true;
}


text:
from django.conf.urls import url
from signup import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^ios_gurug/$', views.ios_gurug, name='ios_gurug'),
]

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Surfnet\Migrations;

use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Add the ra_institution column to the audit_log
 *
 * This column is set with the ra institution that was in context at the time of the event that is logged.
 *
 * Example: John Doe is accredited to become RA by Joe from institution-a. The actual institution John is
 * appointed RA for is stored in this field.
 */
class Version20181101103348 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE audit_log ADD ra_institution VARCHAR(255) DEFAULT NULL');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE audit_log DROP ra_institution;');
    }
}


text:
es-proxy is a proxy to AWS's ElasticSearch that signs request with a given set of AWS credentials.

## Usage

```
export AWS_ACCESS_KEY_ID=<key-id>
export AWS_SECRET_ACCESS_KEY=<access-key>
export AWS_REGION=<region>
./aws-signing-proxy -domain search-my-cluster.us-west-2.es.amazonaws.com
```

## Help

```
Usage of ./es-proxy:
  -domain string
        The elasticsearch domain to proxy (default "os.Getenv(\"ES_DOMAIN\")")
  -port int
        Listening port for proxy (default 8080)
  -region string
        AWS region for credentials (default "os.Getenv(\"AWS_REGION\")")
```

## Contributing

All code in the `/vendor` director is managed by [`govendor`](https://github.com/kardianos/govendor)

## Wishlist

- [ ] Add tests/CI
- [ ] Add docker builds to CI

## License
MIT License. See [License](/LICENSE) for full text


text:
@extends('laramanager::layouts.default')

@section('title')
    Dashboard
@endsection

@section('content')

@endsection


text:
package com.xml2code.java.util;

import java.util.Iterator;
import java.util.Set;

import com.xml2code.java.annotation.Annotation;

public class AnnotationUtil {

	public static <T extends Annotation> boolean containsAnnotationClass(Class<T> annotationClass, Set<Annotation> annotations) {

		Iterator<Annotation> iterator = annotations.iterator();
		while (iterator.hasNext()) {

			if (iterator.next().getClass().equals(annotationClass)) {

				return true;

			}

		}

		return false;

	}

}


text:
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)

// This is just a rough experiment that was used to test the
// order independant transparency

static const float SqrtHalf = 0.70710678f;
static const float3 NegativeLightDirection = float3(SqrtHalf, 0.f, SqrtHalf);

// float Square(float x) { return x*x; }

// float SchlickFresnel(float3 viewDirection, float3 halfVector, float refractiveIndex)
// {
// 		// (note -- the 1.f here assumes one side of the interface is air)
// 	float f0 = Square((1.f - refractiveIndex) / (1.f + refractiveIndex));
//
// 	float A = 1.0f - saturate(dot(viewDirection, halfVector));
// 	float sq = A*A;
// 	float cb = sq*sq;
// 	float q = cb*A;
//
// 	return f0 + (1.f - f0) * q;	// (note, use lerp for this..?)
// }

float FresnelForReflection_Local(VSOutput geo, float refractiveIndex)
{
    float3 localSpaceNormal = normalize(geo.localNormal);
    float3 localViewDirection = normalize(geo.localViewVector);
    float3 localSpaceReflection = reflect(-localViewDirection, localSpaceNormal);

    // float3 halfVector = normalize(NegativeLightDirection + localViewDirection);
    float3 halfVector = normalize(localSpaceReflection + localViewDirection);
    return SchlickFresnel(localViewDirection, halfVector, refractiveIndex);
}

float FresnelForReflection_World(VSOutput geo, float refractiveIndex)
{
    float3 worldSpaceNormal = GetNormal(geo);
    float3 worldViewDirection = normalize(geo.worldViewVector);
    float3 worldSpaceReflection = reflect(-worldViewDirection, worldSpaceNormal);

    float3 halfVector = normalize(worldSpaceReflection + worldViewDirection);
    return SchlickFresnel(worldViewDirection, halfVector, refractiveIndex);
}

// Texture2D ReflectionBox12	: register(t8);
// Texture2D ReflectionBox34	: register(t9);
// Texture2D ReflectionBox5	: register(t10);

Texture2D SkyReflectionTexture[3] : register(t7);

void GlassShader(VSOutput geo)
{
    float3 worldSpaceNormal = GetNormal(geo);
    // worldSpaceNormal = normalize(worldSpaceNormal);

    // float noiseValue2 = PerlinNoise3D(45.f * geo.worldPosition);
    // noiseValue2 = .5 + .5 * noiseValue2;
    // OutputFragmentNode(uint2(geo.position.xy), float4(1,1,1,noiseValue2), geo.position.z);
    // return;

    float3 noiseDerivative;
    float noiseValue = PerlinNoise3DDev(
        /*45.f * */ 15.f * geo.worldPosition, noiseDerivative);
    noiseValue = 0.5f + 0.5f * noiseValue;
    worldSpaceNormal += 0.075f * (noiseDerivative);
    worldSpaceNormal = normalize(worldSpaceNormal);

    const float refractiveIndex = 1.9f;
    float d = FresnelForReflection_World(geo, refractiveIndex);

    uint2 reflectionTextureDims;
    // ReflectionBox12.GetDimensions(reflectionTextureDims.x, reflectionTextureDims.y);
    SkyReflectionTexture[0].GetDimensions(reflectionTextureDims.x, reflectionTextureDims.y);

    float3 worldViewDirection = normalize(geo.worldViewVector);
    float3 worldSpaceReflection = reflect(-worldViewDirection, worldSpaceNormal);
    //float4 reflectionLookup = ReadReflectionHemiBox(
    //	worldSpaceReflection,
    //	ReflectionBox12, ReflectionBox34, ReflectionBox5,
    //	reflectionTextureDims, 4);
    float2 skyReflectionCoord = EquirectangularMappingCoord(worldSpaceReflection);
    float4 reflectionLookup = SkyReflectionTexture[0].Load(
        int3(skyReflectionCoord.xy * float2(reflectionTextureDims.xy), 0));

    // float3 localSpaceNormal = normalize(geo.localNormal);
    // float3 localViewDirection = normalize(geo.localViewVector);
    // float3 localSpaceReflection = reflect(-localViewDirection, localSpaceNormal);
    //
    // // float3 halfVector = normalize(NegativeLightDirection + localViewDirection);
    // float3 halfVector = normalize(localSpaceReflection + localViewDirection);
    // const float refractiveIndex = 1.05f;
    // float d = SchlickFresnel(localViewDirection, halfVector, refractiveIndex);

    // d = 1.f-abs(dot(localViewDirection,localSpaceNormal));
    // d = saturate(dot(halfVector, localSpaceNormal));

    // localSpaceReflection = reflect(-localViewDirection, localSpaceNormal);
    // d = saturate(dot(localSpaceReflection, NegativeLightDirection));
    // d = pow(d,32.f);

    reflectionLookup.rgb = 5.f * pow(reflectionLookup.rgb, 4.f);
    reflectionLookup.rgb = lerp(SRGBLuminance(reflectionLookup.rgb).xxx, reflectionLookup.rgb, 0.25f);
    reflectionLookup.rgb += 8.0.xxx * pow(saturate(dot(worldSpaceReflection, NegativeLightDirection)), 128.f);

    float alpha = 0.5f; // lerp(0.15f, 1.f, d);
    const float minAlpha =   4.f / 255.f;
    if (alpha > minAlpha) {
        // const float3 baseColor = 0.75.xxx;
        alpha *= reflectionLookup.a;
        const float3 baseColor = reflectionLookup.rgb;
        float4 finalColor = float4(baseColor*lerp(0.1f, 1.f, d), alpha);

        // finalColor = float4(0.5f + 0.5f * worldSpaceNormal.xyz, 1);
        OutputFragmentNode(uint2(geo.position.xy), finalColor, geo.position.z);
    }
}


text:
#import "CPTDefinitions.h"
#import "CPTPlotRange.h"
#import "CPTNumericDataType.h"
#import "CPTAnnotationHostLayer.h"
#import "CPTMutableTextStyle.h"

@class CPTLegend;
@class CPTMutableNumericData;
@class CPTNumericData;
@class CPTPlot;
@class CPTPlotArea;
@class CPTPlotSpace;
@class CPTPlotSpaceAnnotation;
@class CPTPlotRange;

///	@file

/**	@brief Enumeration of cache precisions.
 **/
typedef enum _CPTPlotCachePrecision {
    CPTPlotCachePrecisionAuto,		///< Cache precision is determined automatically from the data. All cached data will be converted to match the last data loaded.
    CPTPlotCachePrecisionDouble,		///< All cached data will be converted to double precision.
    CPTPlotCachePrecisionDecimal		///< All cached data will be converted to NSDecimal.
} CPTPlotCachePrecision;

#pragma mark -

/**	@brief A plot data source.
 **/
@protocol CPTPlotDataSource <NSObject>
/**	@brief The number of data points for the plot.
 *	@param plot The plot.
 *	@return The number of data points for the plot.
 **/
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot;

@optional

/// @name Implement one of the following
/// @{

/**	@brief Gets a range of plot data for the given plot and field.
 *	@param plot The plot.
 *	@param fieldEnum The field index.
 *	@param indexRange The range of the data indexes of interest.
 *	@return An array of data points.
 **/
-(NSArray *)numbersForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange;

/**	@brief Gets a plot data value for the given plot and field.
 *	@param plot The plot.
 *	@param fieldEnum The field index.
 *	@param index The data index of interest.
 *	@return A data point.
 **/
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;

/**	@brief Gets a range of plot data for the given plot and field.
 *	@param plot The plot.
 *	@param fieldEnum The field index.
 *	@param indexRange The range of the data indexes of interest.
 *	@return A retained C array of data points.
 **/
-(double *)doublesForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange;

/**	@brief Gets a plot data value for the given plot and field.
 *	@param plot The plot.
 *	@param fieldEnum The field index.
 *	@param index The data index of interest.
 *	@return A data point.
 **/
-(double)doubleForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;

/**	@brief Gets a range of plot data for the given plot and field.
 *	@param plot The plot.
 *	@param fieldEnum The field index.
 *	@param indexRange The range of the data indexes of interest.
 *	@return A one-dimensional array of data points.
 **/
-(CPTNumericData *)dataForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange;

///	@}

/// @name Data Labels
/// @{

/** @brief Gets a data label for the given plot. This method is optional.
 *	@param plot The plot.
 *	@param index The data index of interest.
 *	@return The data label for the point with the given index.
 *  If you return nil, the default data label will be used. If you return an instance of NSNull,
 *  no label will be shown for the index in question.
 **/
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index;

///	@}

@end

#pragma mark -

@interface CPTPlot : CPTAnnotationHostLayer {
	@private
    id <CPTPlotDataSource> dataSource;
    id <NSCopying, NSCoding, NSObject> identifier;
	NSString *title;
    CPTPlotSpace *plotSpace;
    BOOL dataNeedsReloading;
    NSMutableDictionary *cachedData;
    NSUInteger cachedDataCount;
    CPTPlotCachePrecision cachePrecision;
	BOOL needsRelabel;
	CGFloat labelOffset;
    CGFloat labelRotation;
	NSUInteger labelField;
	CPTTextStyle *labelTextStyle;
	NSNumberFormatter *labelFormatter;
	BOOL labelFormatterChanged;
	NSRange labelIndexRange;
	NSMutableArray *labelAnnotations;
	CPTShadow *labelShadow;
	BOOL alignsPointsToPixels;
}

/// @name Data Source
/// @{
@property (nonatomic, readwrite, assign) id <CPTPlotDataSource> dataSource;
///	@}

/// @name Identification
/// @{
@property (nonatomic, readwrite, copy) id <NSCopying, NSCoding, NSObject> identifier;
@property (nonatomic, readwrite, copy) NSString *title;
///	@}

/// @name Plot Space
/// @{
@property (nonatomic, readwrite, retain) CPTPlotSpace *plotSpace;
///	@}

/// @name Plot Area
/// @{
@property (nonatomic, readonly, retain) CPTPlotArea *plotArea;
///	@}

/// @name Data Loading
/// @{
@property (nonatomic, readonly, assign) BOOL dataNeedsReloading;
///	@}

/// @name Data Cache
/// @{
@property (nonatomic, readonly, assign) NSUInteger cachedDataCount;
@property (nonatomic, readonly, assign) BOOL doublePrecisionCache;
@property (nonatomic, readwrite, assign) CPTPlotCachePrecision cachePrecision;
@property (nonatomic, readonly, assign) CPTNumericDataType doubleDataType;
@property (nonatomic, readonly, assign) CPTNumericDataType decimalDataType;
///	@}

/// @name Data Labels
/// @{
@property (nonatomic, readonly, assign) BOOL needsRelabel;
@property (nonatomic, readwrite, assign) CGFloat labelOffset;
@property (nonatomic, readwrite, assign) CGFloat labelRotation;
@property (nonatomic, readwrite, assign) NSUInteger labelField;
@property (nonatomic, readwrite, copy) CPTTextStyle *labelTextStyle;
@property (nonatomic, readwrite, retain) NSNumberFormatter *labelFormatter;
@property (nonatomic, readwrite, retain) CPTShadow *labelShadow;
///	@}

/// @name Drawing
/// @{
@property (nonatomic, readwrite, assign) BOOL alignsPointsToPixels;
///	@}

/// @name Data Labels
/// @{
-(void)setNeedsRelabel;
-(void)relabel;
-(void)relabelIndexRange:(NSRange)indexRange;
-(void)repositionAllLabelAnnotations;
///	@}

/// @name Data Loading
/// @{
-(void)setDataNeedsReloading;
-(void)reloadData;
-(void)reloadDataIfNeeded;
-(void)reloadDataInIndexRange:(NSRange)indexRange;
-(void)insertDataAtIndex:(NSUInteger)index numberOfRecords:(NSUInteger)numberOfRecords;
-(void)deleteDataInIndexRange:(NSRange)indexRange;
///	@}

/// @name Plot Data
/// @{
-(id)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange;
///	@}

/// @name Data Cache
/// @{
-(CPTMutableNumericData *)cachedNumbersForField:(NSUInteger)fieldEnum;
-(NSNumber *)cachedNumberForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;
-(double)cachedDoubleForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;
-(NSDecimal)cachedDecimalForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index;
-(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum;
-(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum atRecordIndex:(NSUInteger)index;
///	@}

/// @name Plot Data Ranges
/// @{
-(CPTPlotRange *)plotRangeForField:(NSUInteger)fieldEnum;
-(CPTPlotRange *)plotRangeForCoordinate:(CPTCoordinate)coord;
///	@}

/// @name Legends
/// @{
-(NSUInteger)numberOfLegendEntries;
-(NSString *)titleForLegendEntryAtIndex:(NSUInteger)index;
-(void)drawSwatchForLegend:(CPTLegend *)legend atIndex:(NSUInteger)index inRect:(CGRect)rect inContext:(CGContextRef)context;
///	@}

@end

#pragma mark -

/**	@category CPTPlot(AbstractMethods)
 *	@brief CPTPlot abstract methods—must be overridden by subclasses
 **/
@interface CPTPlot(AbstractMethods)

/// @name Fields
/// @{
-(NSUInteger)numberOfFields;
-(NSArray *)fieldIdentifiers;
-(NSArray *)fieldIdentifiersForCoordinate:(CPTCoordinate)coord;
///	@}

/// @name Data Labels
/// @{
-(void)positionLabelAnnotation:(CPTPlotSpaceAnnotation *)label forIndex:(NSUInteger)index;
///	@}

@end


text:
var assert = require('assert')

module.exports = function (gm, dir, finish, GM) {
  if (!GM.integration)
    return finish();

  gm
  .res(function getterres (err, res) {
    if (err) return finish(err);
    if (gm._options.imageMagick) {
      assert.equal('72x72', res);
    } else {
      assert.equal('72x72 pixels/inch', res);
    }
    assert.equal(res, this.data.Resolution)
    finish();
  });
}


text:
<?php
namespace Role\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Role
{
	/**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    */
    protected $id;

    /** @ORM\Column(type="string") */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="User\Entity\User", mappedBy="role")
     */
    private $users;

    /**
     * @ORM\ManyToMany(targetEntity="Resource\Entity\Resource", inversedBy="roles")
     * @ORM\JoinTable(name="resources_roles")
     */
    private $resources;

    /**
     * @ORM\ManyToMany(targetEntity="Privilege\Entity\Privilege", inversedBy="roles")
     * @ORM\JoinTable(name="roles_privileges",
     *     joinColumns={@ORM\JoinColumn(name="roles_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="privilege_id", referencedColumnName="id")}
     *     )
     */
    protected $privileges;

    /**
     * @ORM\ManyToMany(targetEntity="Role", mappedBy="parents")
     */
    private $children;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="children")
     * @ORM\JoinTable(name="roles_parents",
     *      joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="parent_role_id", referencedColumnName="id")}
     *      )
     */
    private $parents;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
        $this->resources = new \Doctrine\Common\Collections\ArrayCollection();
        $this->privileges = new \Doctrine\Common\Collections\ArrayCollection();
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
        $this->parents = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Role
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Add user
     *
     * @param \User\Entity\User $user
     *
     * @return Role
     */
    public function addUser(\User\Entity\User $user)
    {
        $this->users[] = $user;

        return $this;
    }

    /**
     * Remove user
     *
     * @param \User\Entity\User $user
     */
    public function removeUser(\User\Entity\User $user)
    {
        $this->users->removeElement($user);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsers()
    {
        return $this->users;
    }

    /**
     * Add resource
     *
     * @param \Resource\Entity\Resource $resource
     *
     * @return Role
     */
    public function addResource(\Resource\Entity\Resource $resource)
    {
        $this->resources[] = $resource;

        return $this;
    }

    /**
     * Remove resource
     *
     * @param \Resource\Entity\Resource $resource
     */
    public function removeResource(\Resource\Entity\Resource $resource)
    {
        $this->resources->removeElement($resource);
    }

    /**
     * Get resources
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getResources()
    {
        return $this->resources;
    }

    /**
     * Add privilege
     *
     * @param \Privilege\Entity\Privilege $privilege
     *
     * @return Role
     */
    public function addPrivilege(\Privilege\Entity\Privilege $privilege)
    {
        $this->privileges[] = $privilege;

        return $this;
    }

    /**
     * Remove privilege
     *
     * @param \Privilege\Entity\Privilege $privilege
     */
    public function removePrivilege(\Privilege\Entity\Privilege $privilege)
    {
        $this->privileges->removeElement($privilege);
    }

    /**
     * Get privileges
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPrivileges()
    {
        return $this->privileges;
    }

    /**
     * Add child
     *
     * @param \Role\Entity\Role $child
     *
     * @return Role
     */
    public function addChild(\Role\Entity\Role $child)
    {
        $this->children[] = $child;

        return $this;
    }

    /**
     * Remove child
     *
     * @param \Role\Entity\Role $child
     */
    public function removeChild(\Role\Entity\Role $child)
    {
        $this->children->removeElement($child);
    }

    /**
     * Get children
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Add parent
     *
     * @param \Role\Entity\Role $parent
     *
     * @return Role
     */
    public function addParent(\Role\Entity\Role $parent)
    {
        $this->parents[] = $parent;

        return $this;
    }

    /**
     * Remove parent
     *
     * @param \Role\Entity\Role $parent
     */
    public function removeParent(\Role\Entity\Role $parent)
    {
        $this->parents->removeElement($parent);
    }

    /**
     * Get parents
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getParents()
    {
        return $this->parents;
    }
}


text:
===============================
Sphinx and RTFD Demo
===============================

Demonstration of Sphinx and RTFD for PUG presentation

* Free software: BSD license
* Documentation: http://sphinx-and-rtfd-demo.rtfd.org/


text:
package org.camunda.bpm.qa.upgrade.scenarios7110.timestamp;

import org.camunda.bpm.engine.externaltask.ExternalTask;
import org.camunda.bpm.qa.upgrade.Origin;
import org.camunda.bpm.qa.upgrade.ScenarioUnderTest;
import org.junit.Test;

import java.util.Date;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * @author Nikola Koevski
 */
@ScenarioUnderTest("ExternalTaskLockExpTimeScenario")
@Origin("7.11.0")
public class ExternalTaskLockExpTimeTest extends AbstractTimestampMigrationTest {

  protected static final Date LOCK_EXP_TIME =  new Date(TIME + 1000L);
  protected static final String TOPIC_NAME = "externalTaskLockExpTimeTestTopic";

  @ScenarioUnderTest("initExternalTaskLockExpTime.1")
  @Test
  public void testLockExpirationTimeConversion() {

    // when
    ExternalTask externalTask = externalTaskService.createExternalTaskQuery()
      .topicName(TOPIC_NAME)
      .singleResult();

    // assume
    assertNotNull(externalTask);

    // then
    assertThat(externalTask.getLockExpirationTime(), is(LOCK_EXP_TIME));
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:id="@+id/listPersonParent">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="" android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/idEquipageText" android:gravity="center_vertical|left" android:singleLine="true"
            android:ellipsize="marquee" android:textColor="@color/DMilitary" android:textStyle="bold"
            android:layout_margin="5dp"/>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/nameLayout" android:layout_margin="5dp">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/equipage_commander" android:textAppearance="?android:attr/textAppearanceLarge"
                android:id="@+id/commanderTitle" android:gravity="center_vertical|left" android:singleLine="true"
                android:ellipsize="marquee" android:textColor="@color/DMilitary"/>
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" android:textAppearance="?android:attr/textAppearanceLarge"
                android:id="@+id/commanderView" android:gravity="center_vertical|left" android:singleLine="true"
                android:ellipsize="marquee" android:textColor="@color/DMilitary" android:textStyle="bold"/>
    </LinearLayout>
</LinearLayout>


text:
import { Map } from 'immutable';

import range from 'lodash/utility/range';

import { typeToState } from 'state/actions/pickTile';

import { entities } from 'state/definitions/entities';
import { grounds } from 'state/definitions/grounds';

import level from 'state/models/level';

const typeToEntityPropSetter = Object.freeze({
  entity: 'setEntityPropAt',
  ground: 'setGroundPropAt',
});

const typeToGetter = Object.freeze({
  entity: 'getEntities',
  ground: 'getGrounds',
});

const typeToDefinition = Object.freeze({
  entity: entities,
  ground: grounds
});

const typeToStorageKey = Object.freeze({
  entity: 'entities',
  ground: 'grounds'
});

function mapTypeToShortType(def) {
  return Object.keys(def).reduce((map, shortKey) => {
    const { type } = def[shortKey];
    map[type] = shortKey;
    return map;
  }, {});
}

const defToShortTypeMap = new WeakMap();
defToShortTypeMap.set(entities, mapTypeToShortType(entities));
defToShortTypeMap.set(grounds, mapTypeToShortType(grounds));

// Transforms the current "expanded" tile data into compact
// level data by mapping tile types in their respective rows
// and columns into an array on short types understood by the
// level paring code.
function toLevel(getter, def, state) {
  const data = level[getter](state).toJS();
  return data.map((row) => (
    row.map((tile) => defToShortTypeMap.get(def)[tile.type]).join(' ')
  ));
}

function storeLevelData(key, getter, def, state) {
  localStorage.setItem(
    key,
    JSON.stringify(toLevel(getter, def, state))
  );
}

export const type = 'PLACE_TILE';

export function reduce(state, { tileType, col, row }) {
  const definition = typeToDefinition[tileType];
  const shortType = state.getIn(['editor', typeToState[tileType]]);
  if (!shortType) { return state; }
  const { type } = definition[shortType];
  const setter = typeToEntityPropSetter[tileType];
  const getter = typeToGetter[tileType];
  const lsKey = typeToStorageKey[tileType];
  state = level[setter](col, row, 'type', type, state);
  // TODO: this should be middleware
  storeLevelData(lsKey, getter, definition, state);
  return state;
};

export function toPlaceTile(tileType, col, row) {
  return { type, tileType, col, row };
};


text:
\section{Trimble Resolution T receivers}

Trimble Resolution T receivers are obsolete and further development of the software
described here has ceased. The successor to the Resolution T, the SMT 360,
cannot currently be used for time-transfer because of changes in the message set.
It is possible though that a future TSIP-based receiver may be suitable for time-transfer.

\subsection{restlog.pl} \hypertarget{h:restlog}{}

\subsubsection{usage}

\begin{lstlisting}[mathescape=true]
restlog.pl [option] $\ldots$
\end{lstlisting}

The command line options are:
\begin{description*}
	\item[-c \textless{file}\textgreater] use the specified configuration file
	\item[-h] print help and exit
	\item[-d] run in debugging mode
	\item[-r] reset the receiver on startup
	\item[-v] print version information and exit
\end{description*}

\subsubsection{configuration}

\cc{restlog.pl} respects the \cc{receiver::model} configuration option.
The valid values are:
\begin{enumerate}
	\item Resolution T
	\item Resolution SMT 360
\end{enumerate}

\subsection{restextract.pl} \hypertarget{h:restextract}{}

\cc{restextract.pl} is used to decode and extract information from Trimble receiver log files.
It will decompress the file if necessary.

\subsubsection{usage}

\begin{lstlisting}[mathescape=true]
restextract.pl [option] $\ldots$
\end{lstlisting}

Given an MJD via a command line option, it will construct a file name using the information in \cc{gpscv.conf}. If no MJD is given, it assumes the current MJD for the file.

The command line options are:
\begin{description*}
	\item[-c \textless{file}\textgreater] use the specified configuration file
	\item[-h] print help and exit
	\item[-v] print version information and exit
  \item[-a] extract S/N for visible satellites
	\item[-f] show firmware version
  \item[-l] leap second warning
  \item[-L] leap second info )
  \item[-m \textless{mjd}\textgreater]  MJD of the file to process
  \item[-p] position fix message
  \item[-r \textless{svn}\textgreater] pseudoranges for satellite with given SVN
			(svn=999 reports all satellites)
  \item[-s] number of visible satellites
  \item[-t] temperature
  \item[-u] UTC offset
  \item[-x] alarms and gps decoding status
\end{description*}

\subsection{restinfo.pl} \hypertarget{h:restinfo}{}

\cc{restinfo.pl} communicates with the receiver configured in \cc{gpscv.conf},
polling it for information such as hardware, software and firmware versions.
The serial port communication speed must be 115200 baud.

\subsubsection{usage}

\begin{lstlisting}[mathescape=true]
restinfo.pl [option] $\ldots$
\end{lstlisting}

The command line options are:
\begin{description*}
	\item[-c \textless{file}\textgreater] use the specified configuration file
	\item[-h] print help and exit
	\item[-d] run in debugging mode
	\item[-v] print version information and exit
\end{description*}

\subsection{restconfig.pl} \hypertarget{h:restconfig}{}

\cc{restconfig.pl} is used to configure the receiver serial port for 115200 baud and no parity bit.
The latter is necessary for using the SMT 360 with \cc{ntpd}.
The new configuration is written to flash memory.

\subsubsection{usage}

\begin{lstlisting}[mathescape=true]
restconfig.pl [option] $\ldots$
\end{lstlisting}

The command line options are:
\begin{description*}
	\item[-c \textless{file}\textgreater] use the specified configuration file
	\item[-h] print help and exit
	\item[-d] run in debugging mode
	\item[-v] print version information and exit
\end{description*}

The serial port device name is read from \cc{gpscv.conf} or the specified file.

\subsection{restplayer.pl} \hypertarget{h:restplayer}{}

This is used to replay raw data files through a serial port, simulating the
operation of the GNSS receiver. This is useful for testing the operation of
\cc{ntpd}, for example. This script will have to be modified for individual
use because it currently hard codes paths and device names.


text:
"""
This is the Python implementation for the Java package "org.omg.CORBA", compiled by Pava.
"""

import pava
from pava import nan, inf

pava_classes = {}
pava.module(__name__)

import CORBA


text:
module Brevity
  class DynamicNode < Treetop::Runtime::SyntaxNode
    def primitives env
      [ self.to_dynamic ]
    end
  end

  class PianississimoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Pianississimo.new
    end
  end

  class PianissimoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Pianissimo.new
    end
  end

  class PianoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Piano.new
    end
  end

  class MezzoPianoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::MezzoPiano.new
    end
  end

  class  MezzoForteNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::MezzoForte.new
    end
  end

  class ForteNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Forte.new
    end
  end

  class  FortissimoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Fortissimo.new
    end
  end

  class FortississimoNode < DynamicNode
    def to_dynamic
      Music::Transcription::Dynamic::Fortississimo.new
    end
  end
end


text:
import os
import ujson
import unittest
import docsbox

class BaseTestCase(unittest.TestCase):

    def setUp(self):
        self.app = docsbox.app
        self.app.config["TESTING"] = True
        self.app.config["RQ_ASYNC"] = False
        self.samples = os.path.join(
            self.app.config["BASE_DIR"],
            "docs/tests/samples/"
        )
        self.client = docsbox.app.test_client()

    def submit_file(self, filename, options):
        with open(filename, "rb") as source:
            response = self.client.post("/api/v1/", data={
                "file": source,
                "options": ujson.dumps(options),
            })
        return response

class DocumentViewTestCase(BaseTestCase):

    def test_get_task_by_valid_uuid(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["txt"]
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(json.get("id"))
        self.assertEqual(json.get("status"), "queued")
        response = self.client.get("/api/v1/{0}".format(json.get("id")))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(ujson.loads(response.data), {
            "id": json.get("id"),
            "status": "queued",
            "result_url": None,
        })

    def test_get_task_by_invalid_uuid(self):
        response = self.client.get("/api/v1/uuid-with-ponies")
        self.assertEqual(response.status_code, 404)
        self.assertEqual(ujson.loads(response.data), {
            "message": "Unknown task_id"
        })

class DocumentCreateViewTestCase(BaseTestCase):

    def test_submit_without_file(self):
        response = self.client.post("/api/v1/", data={
            "options": ujson.dumps(["pdf"])
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "file field is required"
        })

    def test_submit_invalid_mimetype(self):
        response = self.submit_file("/bin/sh", {
            "formats": ["pdf"],
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "Not supported mimetype: 'application/x-sharedlib'"
        })

    def test_submit_empty_formats(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": []
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "Invalid 'formats' value"
        })

    def test_submit_invalid_formats(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["csv"]
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "'application/vnd.openxmlformats-offi"
                       "cedocument.wordprocessingml.document'"
                       " mimetype can't be converted to 'csv'"
        })

    def test_submit_invalid_thumbnails_field(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["pdf"],
            "thumbnails": 1,
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "Invalid 'thumbnails' value"
        })

    def test_submit_invalid_thumbnails_size_field(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["pdf"],
            "thumbnails": {
                "size": None,
            },
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "Invalid 'size' value"
        })

    def test_submit_invalid_thumbnails_size_field_value(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["pdf"],
            "thumbnails": {
                "size": "ZZx43",
            },
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json, {
            "message": "Invalid 'size' value"
        })

    def test_submit_valid_thumbnails(self):
        filename = os.path.join(self.samples, "sample.docx")
        response = self.submit_file(filename, {
            "formats": ["pdf"],
            "thumbnails": {
                "size": "640x480",
            },
        })
        json = ujson.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.get("status"), "queued")


text:
package com.triangleleft.flashcards.ui.common;

public interface OnItemClickListener<VH> {
    void onItemClick(VH viewHolder, int position);
}


text:
[![Build Status](https://secure.travis-ci.org/doctrine/mongodb-odm.png?branch=master)](http://travis-ci.org/doctrine/mongodb-odm)
[![Code Coverage](https://codecov.io/gh/doctrine/mongodb-odm/branch/master/graph/badge.svg)](https://codecov.io/gh/doctrine/mongodb-odm/branch/master)
[![Gitter](https://badges.gitter.im/doctrine/mongodb-odm.svg)](https://gitter.im/doctrine/mongodb-odm)

The Doctrine MongoDB ODM project is a library that provides a PHP object mapping functionality for MongoDB.

## More resources:

* [Website](https://www.doctrine-project.org/projects/mongodb-odm.html)
* [Documentation](https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/stable/)
* [API](https://www.doctrine-project.org/api/mongodb-odm/stable/)
* [Issue Tracker](https://github.com/doctrine/mongodb-odm/issues)
* [Releases](https://github.com/doctrine/mongodb-odm/releases)


text:
require File.expand_path('../../../spec_helper', __FILE__)

platform_is_not :darwin do
  process_is_foreground do
    with_feature :readline do
      require 'readline'

      describe "Readline.emacs_editing_mode" do
        it "returns nil" do
          Readline.emacs_editing_mode.should be_nil
        end
      end
    end
  end
end


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace TTC2017.SmartGrids.OutagePreventionJointarget
{

    /// <summary>
    /// The public interface for ControlArea
    /// </summary>
    [DefaultImplementationTypeAttribute(typeof(ControlArea))]
    [XmlDefaultImplementationTypeAttribute(typeof(ControlArea))]
    public interface IControlArea : IModelElement
    {

        /// <summary>
        /// The mRID property
        /// </summary>
        string MRID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets fired before the MRID property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MRIDChanging;

        /// <summary>
        /// Gets fired when the MRID property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> MRIDChanged;
    }
}


text:
<?php
namespace Bunny\Protocol;

use Bunny\Constants;

/**
 * AMQP 'connection.open' (class #10, method #40) frame.
 *
 * THIS CLASS IS GENERATED FROM amqp-rabbitmq-0.9.1.json. **DO NOT EDIT!**
 *
 * @author Jakub Kulhan <jakub.kulhan@gmail.com>
 */
class MethodConnectionOpenFrame extends MethodFrame
{

    /** @var string */
    public $virtualHost = '/';

    /** @var string */
    public $capabilities = '';

    /** @var boolean */
    public $insist = false;

    public function __construct()
    {
        parent::__construct(Constants::CLASS_CONNECTION, Constants::METHOD_CONNECTION_OPEN);
        $this->channel = Constants::CONNECTION_CHANNEL;
    }

}


text:
function [Cluster Codebook] = cvKmeans(X, K, stopIter, distFunc, verbose)
% cvKmeans - K-means clustering
%
% Synopsis
%   [Cluster Codebook] = cvKmeans(X, K, [stopIter], [distFunc], [verbose])
%
% Description
%   K-means clustering
%
% Inputs ([]s are optional)
%   (matrix) X        D x N matrix representing feature vectors by columns
%                     where D is the number of dimensions and N is the
%                     number of vectors.
%   (scalar) K        The number of clusters.
%   (scalar) [stopIter = .05]
%                     A scalar between [0, 1]. Stop iterations if the
%                     improved rate is less than this threshold value.
%   (func)   [distFunc = @cvEucdist]
%                     A function handle for distance measure. The function
%                     must have two arguments for matrix X and Y. See
%                     cvEucdist.m (Euclidean distance) as a reference.
%   (bool)   [verbose = false]
%                     Show progress or not.
%
% Outputs ([]s are optional)
%   (vector) Cluster  1 x N vector cntaining intergers indicating the
%                     cluster indicies. Cluster(n) is the cluster id for
%                     X(:,n).
%   (matrix) Codebook D x K matrix representing cluster centroids (means)
%                     or VQ codewords (codebook)
%
% Examples
%   See also demo/cvKmeansDemo.m, cvKmeansDemoVQ.m, cvKmeansDemoClassifi.m
%
%   X = rand(2, 10); % 2-dimensional vectors
%   [Cluster, Mu] = cvKmeans(X, 2);
%   % Use kmeans.m in practice that equivalent codes are as
%   [Cluster, Mu] = kmeans(X.', 2);
%   Cluster = Cluster.'; Mu = Mu.';
%   XCluster(:,:,1) = X(:, Cluster == 1);
%
% See also
%   cvAutolabel, cvEucdist, kmeans (Statistics Toolbox)

% Authors
%   Naotoshi Seo <sonots(at)sonots.com>
%
% License
%   The program is free to use for non-commercial academic purposes,
%   but for course works, you must understand what is going inside to use.
%   The program can be used, modified, or re-distributed for any purposes
%   if you or one of your group understand codes (the one must come to
%   court if court cases occur.) Please contact the authors if you are
%   interested in using the program without meeting the above conditions.
%
% Changes
%   04/01/2006  First Edition
if ~exist('stopIter', 'var') || isempty(stopIter)
    stopIter = .05;
end
if ~exist('distFunc', 'var') || isempty(distFunc)
    distFunc = @cvEucdist;
end
if ~exist('verbose', 'var') || isempty(verbose)
    verbose = false;
end
[D N] = size(X);
if K > N,
    error('K must be less than or equal to the number of vectors N');
end

% Initial centroids
Codebook = X(:, randsample(N, K));

improvedRatio = Inf;
distortion = Inf;
iter = 0;
while true
    % Calculate euclidean distances between each sample and each centroid
    d = distFunc(Codebook, X);
    % Assign each sample to the nearest codeword (centroid)
    [dataNearClusterDist, Cluster] = min(d, [], 1);
    % distortion. If centroids are unchanged, distortion is also unchanged.
    % smaller distortion is better
    old_distortion = distortion;
    distortion = mean(dataNearClusterDist);

    % If no more improved, break;
    improvedRatio = 1 - (distortion / old_distortion);
    if verbose
        fprintf('%d: improved ratio = %f\n', iter, improvedRatio);
    end
    iter = iter + 1;
    if improvedRatio <= stopIter, break, end;

    % Renew Codebook
    for i=1:K
        % Get the id of samples which were clusterd into cluster i.
        idx = find(Cluster == i);
        % Calculate centroid of each cluter, and replace Codebook
        Codebook(:, i) = mean(X(:, idx),2);
    end
end


text:
<?php

namespace Jowy\Tests\Subscribers;

use Jowy\Tests\Events\TestEvent;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class TestSubscriber
 * @package Jowy\Tests\Subscribers
 */
class TestSubscriber implements EventSubscriberInterface
{
    /**
     * @param Event $event
     */
    public function onTestEvent(Event $event)
    {
        if (! $event instanceof TestEvent) {
            throw new \RuntimeException("invalid event");
        }

        $event->setNick("jowy");
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            "test.event" => [
                [
                    "onTestEvent",
                    0
                ]
            ]
        ];
    }
}

// EOF


text:
/* eslint-disable @typescript-eslint/no-use-before-define */
export const isUndefined = (obj: any): obj is undefined =>
  typeof obj === 'undefined';

export const isObject = (fn: any): fn is object =>
  !isNil(fn) && typeof fn === 'object';

export const isPlainObject = (fn: any): fn is object => {
  if (!isObject(fn)) {
    return false;
  }
  const proto = Object.getPrototypeOf(fn);
  if (proto === null) {
    return true;
  }
  const ctor =
    Object.prototype.hasOwnProperty.call(proto, 'constructor') &&
    proto.constructor;
  return (
    typeof ctor === 'function' &&
    ctor instanceof ctor &&
    Function.prototype.toString.call(ctor) ===
      Function.prototype.toString.call(Object)
  );
};

export const addLeadingSlash = (path?: string): string =>
  path ? (path.charAt(0) !== '/' ? '/' + path : path) : '';

/**
 * Deprecated. Use the "addLeadingSlash" function instead.
 * @deprecated
 */
export const validatePath = addLeadingSlash;

export const isFunction = (fn: any): boolean => typeof fn === 'function';
export const isString = (fn: any): fn is string => typeof fn === 'string';
export const isConstructor = (fn: any): boolean => fn === 'constructor';
export const isNil = (obj: any): obj is null | undefined =>
  isUndefined(obj) || obj === null;
export const isEmpty = (array: any): boolean => !(array && array.length > 0);
export const isSymbol = (fn: any): fn is symbol => typeof fn === 'symbol';


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using SportsStore.Models;

namespace SportsStore.Migrations
{
    [DbContext(typeof(ApplicationDbContext))]
    partial class ApplicationDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.0-rtm-21431");

            modelBuilder.Entity("SportsStore.Models.CartLine", b =>
                {
                    b.Property<int>("CartLineID")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("OrderID");

                    b.Property<int?>("ProductID");

                    b.Property<int>("Quantity");

                    b.HasKey("CartLineID");

                    b.HasIndex("OrderID");

                    b.HasIndex("ProductID");

                    b.ToTable("CartLine");
                });

            modelBuilder.Entity("SportsStore.Models.Order", b =>
                {
                    b.Property<int>("OrderID")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("City")
                        .IsRequired();

                    b.Property<string>("Country")
                        .IsRequired();

                    b.Property<bool>("GiftWrap");

                    b.Property<string>("Line1")
                        .IsRequired();

                    b.Property<string>("Line2");

                    b.Property<string>("Line3");

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<bool>("Shipped");

                    b.Property<string>("State")
                        .IsRequired();

                    b.Property<string>("Zip");

                    b.HasKey("OrderID");

                    b.ToTable("Orders");
                });

            modelBuilder.Entity("SportsStore.Models.Product", b =>
                {
                    b.Property<int>("ProductID")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Category")
                        .IsRequired();

                    b.Property<string>("Description")
                        .IsRequired();

                    b.Property<string>("Name")
                        .IsRequired();

                    b.Property<decimal>("Price");

                    b.HasKey("ProductID");

                    b.ToTable("Products");
                });

            modelBuilder.Entity("SportsStore.Models.CartLine", b =>
                {
                    b.HasOne("SportsStore.Models.Order")
                        .WithMany("Lines")
                        .HasForeignKey("OrderID");

                    b.HasOne("SportsStore.Models.Product", "Product")
                        .WithMany()
                        .HasForeignKey("ProductID");
                });
        }
    }
}


text:
package org.apache.accumulo.test.functional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Duration;
import java.util.Map.Entry;

import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.DataFileColumnFamily;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Iterators;

public class CleanTmpIT extends ConfigurableMacBase {
  private static final Logger log = LoggerFactory.getLogger(CleanTmpIT.class);

  @Override
  protected Duration defaultTimeout() {
    return Duration.ofMinutes(4);
  }

  @Override
  public void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
    cfg.setProperty(Property.INSTANCE_ZK_TIMEOUT, "15s");
    cfg.setNumTservers(1);
    // use raw local file system so walogs sync and flush will work
    hadoopCoreSite.set("fs.file.impl", RawLocalFileSystem.class.getName());
  }

  @Test
  public void test() throws Exception {
    try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) {
      // make a table
      String tableName = getUniqueNames(1)[0];
      c.tableOperations().create(tableName);
      // write to it
      try (BatchWriter bw = c.createBatchWriter(tableName)) {
        Mutation m = new Mutation("row");
        m.put("cf", "cq", "value");
        bw.addMutation(m);
        bw.flush();
        // Compact memory to make a file
        c.tableOperations().compact(tableName, null, null, true, true);
        // Make sure that we'll have a WAL
        m = new Mutation("row2");
        m.put("cf", "cq", "value");
        bw.addMutation(m);
      }

      // create a fake _tmp file in its directory
      String id = c.tableOperations().tableIdMap().get(tableName);
      Path file;
      try (Scanner s = c.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
        s.setRange(Range.prefix(id));
        s.fetchColumnFamily(DataFileColumnFamily.NAME);
        Entry<Key,Value> entry = getOnlyElement(s);
        file = new Path(entry.getKey().getColumnQualifier().toString());
      }

      FileSystem fs = getCluster().getFileSystem();
      assertTrue(fs.exists(file), "Could not find file: " + file);
      Path tabletDir = file.getParent();
      assertNotNull(tabletDir, "Tablet dir should not be null");
      Path tmp = new Path(tabletDir, "junk.rf_tmp");
      // Make the file
      fs.create(tmp).close();
      log.info("Created tmp file {}", tmp);
      getCluster().stop();
      getCluster().start();

      try (Scanner scanner = c.createScanner(tableName, Authorizations.EMPTY)) {
        assertEquals(2, Iterators.size(scanner.iterator()));
        // If we performed log recovery, we should have cleaned up any stray files
        assertFalse(fs.exists(tmp), "File still exists: " + tmp);
      }
    }
  }
}


text:
package com.nsysmon.servlet.threaddump;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.text.Collator;
import java.util.*;

/**
 * @author arno
 */
class AThreadDumper {
    static final Comparator<ThreadInfo> threadNameComparator = (o1, o2) -> Collator.getInstance().compare(o1.getThreadName(), o2.getThreadName());

    private static final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

    public static Collection<ThreadInfo> getThreadInfo() {
        final Collection<ThreadInfo> result = new TreeSet<>(threadNameComparator);

        result.addAll(Arrays.asList(mxBean.dumpAllThreads(mxBean.isObjectMonitorUsageSupported(), mxBean.isSynchronizerUsageSupported())));

        return result;
    }

    private static final long[] NO_LONGS = new long[0];
    private static long[] nullToEmpty(long[] longs) {
        return longs != null ? longs : NO_LONGS;
    }

    public static Collection<Long> getDeadlockedThreads() {
        final Collection<Long> result = new HashSet<>();

        if(mxBean != null) { // may happen, depending on JVM version
            for(long threadId: nullToEmpty(mxBean.findDeadlockedThreads())) {
                result.add(threadId);
            }

            for(long threadId: nullToEmpty(mxBean.findMonitorDeadlockedThreads())) {
                result.add(threadId);
            }
        }

        return result;
    }
}


text:
<?php

namespace RectorPrefix20210615\Symfony\Component\DependencyInjection\Compiler;

use RectorPrefix20210615\Symfony\Component\DependencyInjection\Definition;
use RectorPrefix20210615\Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
 * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
 */
class ResolveFactoryClassPass extends \RectorPrefix20210615\Symfony\Component\DependencyInjection\Compiler\AbstractRecursivePass
{
    /**
     * {@inheritdoc}
     */
    protected function processValue($value, bool $isRoot = \false)
    {
        if ($value instanceof \RectorPrefix20210615\Symfony\Component\DependencyInjection\Definition && \is_array($factory = $value->getFactory()) && null === $factory[0]) {
            if (null === ($class = $value->getClass())) {
                throw new \RectorPrefix20210615\Symfony\Component\DependencyInjection\Exception\RuntimeException(\sprintf('The "%s" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?', $this->currentId));
            }
            $factory[0] = $class;
            $value->setFactory($factory);
        }
        return parent::processValue($value, $isRoot);
    }
}


text:
function loginVM() {
    var self = this;

    // could also be te user's email
    self.email = ko.observable("");
    self.password = ko.observable("");
    self.passwordRetype = ko.observable("");
}

loginVM.prototype.doLogin = function(){
    var self = this;

    $.ajax({
        type: "POST",
        url: "http://localhost:8080/api/customer/login",
        data: { email : self.email(), password: self.password }
    }).done(function(data) {
            if(data.hasErrors)
            {
                alert(data.messages);
            }
            else
            {
                window.location = './pages/dashboard.html';
            }
        });
};

ko.applyBindings(new loginVM());


text:
/* BEGIN SQLCIPHER */
#ifdef SQLITE_HAS_CODEC
#ifndef SQLCIPHER_H
#define SQLCIPHER_H

typedef struct {
  int (*activate)(void *ctx);
  int (*deactivate)(void *ctx);
  const char* (*get_provider_name)(void *ctx);
  int (*add_random)(void *ctx, void *buffer, int length);
  int (*random)(void *ctx, void *buffer, int length);
  int (*hmac)(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out);
  int (*kdf)(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key);
  int (*cipher)(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out);
  int (*set_cipher)(void *ctx, const char *cipher_name);
  const char* (*get_cipher)(void *ctx);
  int (*get_key_sz)(void *ctx);
  int (*get_iv_sz)(void *ctx);
  int (*get_block_sz)(void *ctx);
  int (*get_hmac_sz)(void *ctx);
  int (*ctx_copy)(void *target_ctx, void *source_ctx);
  int (*ctx_cmp)(void *c1, void *c2);
  int (*ctx_init)(void **ctx);
  int (*ctx_free)(void **ctx);
} sqlcipher_provider;

/* utility functions */
void sqlcipher_free(void *ptr, int sz);
void* sqlcipher_malloc(int sz);
void* sqlcipher_memset(void *v, unsigned char value, int len);
int sqlcipher_ismemset(const void *v, unsigned char value, int len);
int sqlcipher_memcmp(const void *v0, const void *v1, int len);
void sqlcipher_free(void *, int);

/* provider interfaces */
int sqlcipher_register_provider(sqlcipher_provider *p);
sqlcipher_provider* sqlcipher_get_provider();

#endif
#endif
/* END SQLCIPHER */


text:
const initialState = {
    knownTypes: {},
    importableTypes: [],
    importableFormats: [],
    yes: {},
    no: {}
};

const mergeObjects = (from, to) => {
    const result = {
        ...to
    };
    for (const key of Object.keys(from)) {
        result[key] = new Set([
            ...from[key],
            ...(to[key] || [])
        ]);
    }
    return result;
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
    case 'MEMOIZE_SUBTYPE': {
        const newState = {
            ...state,
            yes: mergeObjects(action.results.yes, state.yes),
            no: mergeObjects(action.results.no, state.no)
        };
        return newState;
    }
    case 'FOUND_TYPES': {
        const newState = {
            ...state,
            knownTypes: { ...state.knownTypes, ...action.typeList }
        };
        return newState;
    }
    case 'IMPORTABLE_TYPES': {
        const newState = {
            ...state,
            importableTypes: action.importableTypesList.sort().map(
                item => ({ value: item, label: item })
            )
        };
        return newState;
    }
    case 'IMPORTABLE_FORMATS': {
        const newState = {
            ...state,
            importableFormats: action.importableFormatsList.sort().map(
                item => ({ value: item, label: item })
            )
        };
        return newState;
    }
    default: return state;
    }
};

export default reducer;


text:
package cn.com.editline;

import org.junit.Assert;
import org.junit.Test;

public class PreviousHistoryTest extends BaseTest {
	@Test
	public void previousHistory() {
		Assert.assertTrue(editLine.addHistory("one"));
		Assert.assertTrue(editLine.addHistory("two"));
		Assert.assertFalse(editLine.addHistory(""));
		Assert.assertTrue(editLine.addHistory(" "));
		Assert.assertTrue(editLine.addHistory("three"));

		Assert.assertEquals("three", editLine.previousHistory().getLine());
		Assert.assertEquals(" ", editLine.previousHistory().getLine());
		Assert.assertEquals("two", editLine.previousHistory().getLine());
		Assert.assertEquals("one", editLine.previousHistory().getLine());
		Assert.assertNull(editLine.previousHistory());
	}
}


text:
import { Component, Input } from '@angular/core';

import { Theme } from './theme_page.component';

@Component({
  selector: 'tune-theme-tile',
  templateUrl: './theme_tile.component.html',
  styleUrls: ['./theme_tile.component.css']
})
export class ThemeTileComponent {
  @Input() theme: Theme;
  @Input() isSelected: boolean;
}


text:
package org.caleydo.view.tourguide.entourage;

import java.util.Arrays;
import java.util.Collections;

import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.EDimension;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.datadomain.DataSupportDefinitions;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.datadomain.genetic.GeneticDataDomain;
import org.caleydo.view.tourguide.api.adapter.ATourGuideDataMode;
import org.caleydo.view.tourguide.api.model.ADataDomainQuery;
import org.caleydo.view.tourguide.api.model.CategoricalDataDomainQuery;
import org.caleydo.view.tourguide.api.model.InhomogenousDataDomainQuery;
import org.caleydo.view.tourguide.entourage.model.SingleIDDataDomainQuery;
import org.caleydo.vis.lineup.model.RankTableModel;
import org.caleydo.vis.lineup.model.StringRankColumnModel;

import com.google.common.collect.Sets;

/**
 * @author Samuel Gratzl
 *
 */
public class NonGeneticDataMode extends ATourGuideDataMode {
	@Override
	public boolean apply(IDataDomain input) {
		if (!(input instanceof ATableBasedDataDomain))
			return false;
		if (input instanceof GeneticDataDomain)
			return false;
		return true;
	}

	@Override
	public void addDefaultColumns(RankTableModel table) {
		addDataDomainRankColumn(table);
		final StringRankColumnModel base = new StringRankColumnModel(GLRenderers.drawText("Name"),
				StringRankColumnModel.DEFAULT);
		table.add(base);
		base.setWidth(150);
		base.orderByMe();
	}

	@Override
	public Iterable<? extends ADataDomainQuery> createDataDomainQuery(IDataDomain dd) {
		assert dd instanceof ATableBasedDataDomain;
		ATableBasedDataDomain d = (ATableBasedDataDomain) dd;
		if (!DataSupportDefinitions.homogenousTables.apply(dd))
			return Collections.singleton(new InhomogenousDataDomainQuery(d, Sets.immutableEnumSet(
					EDataClass.NATURAL_NUMBER, EDataClass.REAL_NUMBER, EDataClass.CATEGORICAL)));
		if (DataSupportDefinitions.categoricalTables.apply(dd)) {
			return Arrays.asList(new CategoricalDataDomainQuery(d, EDimension.DIMENSION),
					new CategoricalDataDomainQuery(d, EDimension.RECORD));
		} else {
			return Arrays.asList(new SingleIDDataDomainQuery(d, EDimension.DIMENSION), new SingleIDDataDomainQuery(d,
					EDimension.RECORD));
		}
	}
}


text:
import os
import sys
import time
from source.k3d_directives.plot import K3D_Plot
import shutil
import json

sys.path.insert(0, os.path.abspath('../..'))

# -- Project information -----------------------------------------------------

project = 'K3D-jupyter'
author = u'Artur Trzęsiok, Marcin Kostur, Tomasz Gandor, Thomas Mattone'
copyright = time.strftime(
    '%Y') + ' ' + author

# The full version, including alpha/beta/rc tags
here = os.path.dirname(__file__)
repo = os.path.join(here, '..', '..')
_version_py = os.path.join(repo, 'package.json')
version_ns = {}

with open(_version_py) as f:
    version = json.load(f)["version"]

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages',
    'sphinx_copybutton',
    'sphinx.ext.napoleon'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The root document.
root_doc = 'index'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'pydata_sphinx_theme'

html_theme_options = {
    "show_prev_next": False,
    "google_analytics_id": 'UA-141840477-1',
    "icon_links": [
        {
            "name": "GitHub",
            "url": "https://github.com/K3D-tools/K3D-jupyter",
            "icon": "fab fa-github",
            "type": "fontawesome",
        },
        {
            "name": "PyPi",
            "url": "https://pypi.org/project/k3d/",
            "icon": "fas fa-box-open",
            "type": "fontawesome",
        },
        {
            "name": "Conda",
            "url": "https://anaconda.org/conda-forge/k3d",
            "icon": "fas fa-circle-notch",
            "type": "fontawesome",
        }
    ]
}

html_sidebars = {
    "index": ["search-field", "sidebar_index"],
    "gallery/*": []
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

def setup(app):
    shutil.copy('./../js/dist/standalone.js', './source/_static/standalone.js')
    shutil.copy('./../node_modules/requirejs/require.js', './source/_static/require.js')

    try:
        app.add_css_file('style.css')
        app.add_javascript('require.js')
        app.add_javascript('standalone.js?k3d')
    except AttributeError:
        app.add_css_file('style.css')
        app.add_js_file('require.js')
        app.add_js_file('standalone.js?k3d')

    app.add_directive('k3d_plot', K3D_Plot)


text:
package com.tsanikgr.whist_multiplayer;

import com.tsanikgr.whist_multiplayer.models.GameModel;
import com.tsanikgr.whist_multiplayer.models.StatisticsModel;

public interface IStatistics {

	interface IStatisticsObserver{
		void onStatisticsChanged(StatisticsModel statisticsModel);
	}

	void addObserver(IStatisticsObserver observer);
	void removeObserver(IStatisticsObserver observer);

	boolean isNameSet();
	StatisticsModel getStatistics();
	void setName(String text);
	StatisticsModel update(GameModel gameModel, int pid);
	StatisticsModel incrementAbandoned(GameModel gameModel, int pid);
	boolean hasEnoughtCoins(int coins);
	boolean placeBet(int bet);
	StatisticsModel refundBet(int bet);

	void unlockAchievement(int achievementId);
	void pushAccomplishments();
	String getName();
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Collections.Generic;
using System.Linq;
using System;

namespace Microsoft.Azure.Management.ResourceManager.Fluent
{
    internal class ProvidersImpl : IProviders
    {
        private IProvidersOperations client;

        internal ProvidersImpl(IProvidersOperations client)
        {
            this.client = client;
        }

        public IProvider GetByName(string resourceProviderNamespace)
        {
            return new ProviderImpl(Extensions.Synchronize(() => client.GetAsync(resourceProviderNamespace)));
        }

        public async Task<IProvider> GetByNameAsync(string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken))
        {
            ProviderInner inner = await client.GetAsync(resourceProviderNamespace, cancellationToken: cancellationToken);
            return new ProviderImpl(inner);
        }

        public IEnumerable<IProvider> List()
        {
            return Extensions.Synchronize(() => client.ListAsync())
                         .AsContinuousCollection(link => Extensions.Synchronize(() => client.ListNextAsync(link)))
                         .Select(inner => WrapModel(inner));
        }

        public async Task<IPagedCollection<IProvider>> ListAsync(bool loadAllPages = true, CancellationToken cancellationToken = default(CancellationToken))
        {
            return await PagedCollection<IProvider, ProviderInner>.LoadPage(
                async (cancellation) => await client.ListAsync(cancellationToken: cancellation),
                client.ListNextAsync,
                WrapModel, loadAllPages, cancellationToken);
        }

        public IProvider Register(string resourceProviderNamespace)
        {
            return WrapModel(Extensions.Synchronize(() => client.RegisterAsync(resourceProviderNamespace)));
        }

        public async Task<IProvider> RegisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken))
        {
            return WrapModel(await client.RegisterAsync(resourceProviderNamespace, cancellationToken));
        }

        public IProvider Unregister(string resourceProviderNamespace)
        {
            return Extensions.Synchronize(() => UnregisterAsync(resourceProviderNamespace));
        }

        public async Task<IProvider> UnregisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken))
        {
            return WrapModel(await client.UnregisterAsync(resourceProviderNamespace, cancellationToken));
        }

        private IProvider WrapModel(ProviderInner innerModel)
        {
            return new ProviderImpl(innerModel);
        }
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
RequestTokenPair
</TITLE>

<META NAME="date" CONTENT="2012-11-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.dropbox.client2.session

Class RequestTokenPair

java.lang.Object
  com.dropbox.client2.session.TokenPair
      com.dropbox.client2.session.AccessTokenPair
          com.dropbox.client2.session.RequestTokenPair

All Implemented Interfaces:
java.io.Serializable

public final class RequestTokenPair
extends AccessTokenPair
implements java.io.Serializable

 Holds a request token and secret for the web OAuth flow.

See Also:
Serialized Form

Field Summary

Fields inherited from class com.dropbox.client2.session.TokenPair

key, secret

Constructor Summary

RequestTokenPair(java.lang.String key,
                 java.lang.String secret)

Method Summary

Methods inherited from class com.dropbox.client2.session.TokenPair

equals, equals, hashCode, toString

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

RequestTokenPair

public RequestTokenPair(java.lang.String key,
                        java.lang.String secret)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
{% extends "micropress/base.html" %}
{% load article_tags %}

{% block title %}Articles | {{ block.super }}{% endblock %}

{% block content %}
  {% if is_paginated %}

      ← Older

      Newer →

  {% endif %}

  {% if not press.closed %}

      Stop the presses!

  {% endif %}

  {% for article in article_list %}
    {% article_content links %}
  {% empty %}

No News Today!

  {% endfor %}

  {% if is_paginated %}

      ← Older

      Newer →

  {% endif %}
{% endblock %}


text:
<?php

##################################################################################
#    HOTELDRUID
#    Copyright (C) 2001-2009 by Marco Maria Francesco De Santis (marco@digitaldruid.net)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    any later version accepted by Marco Maria Francesco De Santis, which
#    shall act as a proxy as defined in Section 14 of version 3 of the
#    license.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##################################################################################

function trova_rel ($rel,&$rel_sing,&$rel_plur,&$tablerel) {
global $tablenazioni,$tableregioni,$tablecitta,$tabledocumentiid,$tableparentele;
$rel_sing = "nazione";
$rel_plur = "nazioni";
$tablerel = $tablenazioni;
if ($rel == "regione") {
$rel_sing = "regione";
$rel_plur = "regioni";
$tablerel = $tableregioni;
} # fine if ($rel == "regione")
if ($rel == "citta") {
$rel_sing = "citta";
$rel_plur = "citta";
$tablerel = $tablecitta;
} # fine if ($rel == "citta")
if ($rel == "documentoid") {
$rel_sing = "documentoid";
$rel_plur = "documentiid";
$tablerel = $tabledocumentiid;
} # fine if ($rel == "documentoid")
if ($rel == "parentela") {
$rel_sing = "parentela";
$rel_plur = "parentele";
$tablerel = $tableparentele;
} # fine if ($rel == "parentela")
} # fine function trova_rel

function mostra_frame_rel ($id,$rel,$rel_sup,$id_ut_sel,$cmp,$mostra_cod,$pieno,$titolo,$size="20",$maxlength="50") {
global $tablerelutenti,$tablenazioni,$tableregioni,$tablecitta,$tabledocumentiid,$tableparentele;

trova_rel($rel,$rel_sing,$rel_plur,$tablerel);
trova_rel($rel_sup,$rel_sup_sing,$rel_sup_plur,$tablerel_sup);

if (get_magic_quotes_gpc()) $id = stripslashes($id);
$id = htmlspecialchars($id);
$id_sup = esegui_query("select distinct $tablerel_sup.id$rel_sup_plur from $tablerelutenti inner join $tablerel_sup on $tablerelutenti.id$rel_sup_sing = $tablerel_sup.id$rel_sup_plur where $tablerelutenti.idutente = '$id_ut_sel' and $tablerel_sup.nome_$rel_sup_sing = '".aggslashdb($id)."' ");
if (numlin_query($id_sup)) $is_id = "= '".risul_query($id_sup,0,"id$rel_sup_plur",$tablerel_sup)."'";
else $is_id = "is NULL";

echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"
        \"http://www.w3.org/TR/html4/strict.dtd\">

<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" >
<title> $titolo </title>

";

$rel_utente = esegui_query("select distinct $tablerel.nome_$rel_sing,$tablerel.codice_$rel_sing,$tablerel.codice2_$rel_sing,$tablerel.codice3_$rel_sing from $tablerelutenti inner join $tablerel on $tablerelutenti.id$rel_sing = $tablerel.id$rel_plur where $tablerelutenti.idutente = '$id_ut_sel' and $tablerelutenti.idsup $is_id order by $tablerel.nome_$rel_sing");
$num_rel_utente = numlin_query($rel_utente);
if ($num_rel_utente) {
echo "<select name=\"$cmp\" id=\"$cmp\">";
if ($pieno != "SI") echo "<option value=\"\">------</option>";
for ($num1 = 0 ; $num1 < $num_rel_utente ; $num1++) {
$rel = htmlspecialchars(risul_query($rel_utente,$num1,"nome_$rel_sing",$tablerel));
echo "<option value=\"$rel\">$rel";
if ($mostra_cod) {
$codice = htmlspecialchars(risul_query($rel_utente,$num1,"codice_$rel_sing",$tablerel));
$codice2 = htmlspecialchars(risul_query($rel_utente,$num1,"codice2_$rel_sing",$tablerel));
$codice3 = htmlspecialchars(risul_query($rel_utente,$num1,"codice3_$rel_sing",$tablerel));
if (strcmp($codice,"")) echo " ($codice)";
if (strcmp($codice2,"")) echo " (".mex("2°",'personalizza.php')." $codice2)";
if (strcmp($codice3,"")) echo " (".mex("3°",'personalizza.php')." $codice3)";
} # fine if ($mostra_cod)
echo "</option>";
} # fine for $num1
echo "</select>";
} # fine if ($num_rel_utente)
else echo "<input type=\"text\" name=\"$cmp\" id=\"$cmp\" size=\"$size\" maxlength=\"$maxlength\">";

echo "

";
} # fine function mostra_frame_rel

?>


text:
require 'test_helper'

class ImporterTest < Test::Unit::TestCase
  include SpriteHelper

  def setup
    create_sprite_temp
    file = StringIO.new("images_path = #{@images_src_path.inspect}\n")
    Compass.add_configuration(file, "sprite_config")
    @importer = Compass::SpriteImporter.new
  end

  def teardown
    Compass.reset_configuration!
  end

  def options
    {:foo => 'bar'}
  end

  test "should use search path to find sprites" do
    Compass.reset_configuration!
    uri = 'foo/*.png'
    other_folder = File.join(@images_tmp_path, '../other-temp')
    FileUtils.mkdir_p other_folder
    FileUtils.mkdir_p File.join(other_folder, 'foo')
    %w(my bar).each do |file|
      FileUtils.touch(File.join(other_folder, "foo/#{file}.png"))
    end
    config = Compass::Configuration::Data.new('config')
    config.images_path = @images_tmp_path
    config.sprite_load_path = [@images_tmp_path, other_folder]
    Compass.add_configuration(config, "sprite_config")
    importer = Compass::SpriteImporter.new
    assert_equal 2, Compass.configuration.sprite_load_path.compact.size
    assert Compass.configuration.sprite_load_path.include?(other_folder)
    assert_equal ["bar", "my"], Compass::SpriteImporter.sprite_names(uri)

    FileUtils.rm_rf other_folder
  end

  test "name should return the sprite name" do
    assert_equal 'selectors', Compass::SpriteImporter.sprite_name(URI)
  end

  test "path should return the sprite path" do
    assert_equal 'selectors',  Compass::SpriteImporter.path(URI)
  end

  test "should return all the sprite names" do
    assert_equal ["ten-by-ten", "ten-by-ten_active", "ten-by-ten_hover", "ten-by-ten_target"], Compass::SpriteImporter.sprite_names(URI)
  end

  test "should have correct mtime" do
    thirtydays = Time.now.to_i + (60*60*24*30)
    file = Dir[File.join(@images_src_path, URI)].sort.first
    File.utime(thirtydays, thirtydays, file)
    assert_equal thirtydays, File.mtime(file).to_i
    assert_equal thirtydays, @importer.mtime(URI, {}).to_i
  end

  test "should return sass engine on find" do
    assert @importer.find(URI, {}).is_a?(Sass::Engine)
  end

  test "sass options should contain options" do
    opts = Compass::SpriteImporter.sass_options('foo', @importer, options)
    assert_equal 'bar', opts[:foo]
  end

  test "verify that the sass_engine passes the correct filename" do
    importer = Compass::SpriteImporter.new
    engine = Compass::SpriteImporter.sass_engine(URI, 'foo', importer, options)
    assert_equal engine.options[:filename], URI
  end

  test "should fail given bad sprite extensions" do
    @images_src_path = File.join(File.dirname(__FILE__), '..', '..', 'fixtures', 'sprites', 'public', 'images')
    file = StringIO.new("images_path = #{@images_src_path.inspect}\n")
    Compass.add_configuration(file, "sprite_config")
    importer = Compass::SpriteImporter.new
    uri = "bad_extensions/*.jpg"
    begin
      Compass::SpriteImporter.sass_engine(uri, Compass::SpriteImporter.sprite_name(uri), importer, {})
      assert false, "An invalid sprite file made it past validation."
    rescue Compass::Error => e
      assert e.message.include?("invalid sprite path")
    end
  end

end