text:
<?php

/* @var $this yii\web\View */

/* @var $model \yii\db\ActiveRecord */

?>

<?
$this->registerJs(<<<JS
(function(sx, $, _)
{
    sx.classes.SelectCmsElement = sx.classes.Component.extend({

        _onDomReady: function()
        {
            this.GetParams              = sx.helpers.Request.getParams();

            $('table tr').on('dblclick', function()
            {
                $(".sx-row-action", $(this)).click();
            });
        },

        submit: function(data)
        {
            if (this.GetParams['callbackEvent'])
            {
                if (window.opener)
                {
                    if (window.opener.sx)
                    {
                        window.opener.sx.EventManager.trigger(this.GetParams['callbackEvent'], data);
                        return this;
                    }
                } else if (window.parent)
                {
                    if (window.parent.sx)
                    {
                        window.parent.sx.EventManager.trigger(this.GetParams['callbackEvent'], data);
                        return this;
                    }
                }
            }

            return this;
        }
    });

    sx.SelectCmsElement = new sx.classes.SelectCmsElement();

})(sx, sx.$, sx._);
JS
);
?>

<?

$contentIds = \yii\helpers\ArrayHelper::map(\Yii::$app->shop->shopContents, 'id', 'id');
$content_id = \Yii::$app->request->get('content_id');

?>

<? if (!\Yii::$app->request->get('content_id')) : ?>
    <? if ($content = \skeeks\cms\models\CmsContent::find()->where(['id' => $contentIds])->orderBy("priority ASC")->one()) : ?>
        <? $content_id = $content->id; ?>
    <? endif; ?>
<? endif; ?>

<? if ($content_id) : ?>

    <?

    $dataProvider = new \yii\data\ActiveDataProvider([
        'query' => \skeeks\cms\models\CmsContentElement::find(),
    ]);

    $search = new \skeeks\cms\models\Search(\skeeks\cms\models\CmsContentElement::class);
    $dataProvider = $search->search(\Yii::$app->request->queryParams);
    $searchModel = $search->loadedModel;

    $dataProvider->query->andWhere(['content_id' => $contentIds]);

    $dataProvider->setSort(['defaultOrder' => ['published_at' => SORT_DESC]]);
    if ($content_id = \Yii::$app->request->get('content_id')) {
        $dataProvider->query->andWhere(['content_id' => $content_id]);
    }

    $autoColumns = [];
    $model = \skeeks\cms\models\CmsContentElement::find()->where(['content_id' => $content_id])->one();

    if (is_array($model) || is_object($model)) {
        //Добавление колонок по моделе элемента
        foreach ($model as $name => $value) {
            $autoColumns[] = [
                'attribute' => $name,
                'visible'   => false,
                'format'    => 'raw',
                'class'     => \yii\grid\DataColumn::class,
                'value'     => function ($model, $key, $index) use ($name) {
                    if (is_array($model->{$name})) {
                        return implode(",", $model->{$name});
                    } else {
                        return $model->{$name};
                    }
                },
            ];
        }

        $searchRelatedPropertiesModel = new \skeeks\cms\models\searchs\SearchRelatedPropertiesModel();
        $searchRelatedPropertiesModel->initCmsContent($model->cmsContent);
        $searchRelatedPropertiesModel->load(\Yii::$app->request->get());
        $searchRelatedPropertiesModel->search($dataProvider);

        /**
         * @var $model \skeeks\cms\models\CmsContentElement
         */
        if ($model->relatedPropertiesModel) {
            foreach ($model->relatedPropertiesModel->toArray($model->relatedPropertiesModel->attributes()) as $name => $value) {

                $property = $model->relatedPropertiesModel->getRelatedProperty($name);
                $filter = '';

                if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT) {
                    $propertyType = $property->handler;
                    $options = \skeeks\cms\models\CmsContentElement::find()->active()->andWhere([
                        'content_id' => $propertyType->content_id,
                    ])->all();

                    $items = \yii\helpers\ArrayHelper::merge(['' => ''], \yii\helpers\ArrayHelper::map(
                        $options, 'id', 'name'
                    ));

                    $filter = \yii\helpers\Html::activeDropDownList($searchRelatedPropertiesModel, $name, $items,
                        ['class' => 'form-control']);

                } else {
                    if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_LIST) {
                        $items = \yii\helpers\ArrayHelper::merge(['' => ''], \yii\helpers\ArrayHelper::map(
                            $property->enums, 'id', 'value'
                        ));

                        $filter = \yii\helpers\Html::activeDropDownList($searchRelatedPropertiesModel, $name, $items,
                            ['class' => 'form-control']);

                    } else {
                        if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_STRING) {
                            $filter = \yii\helpers\Html::activeTextInput($searchRelatedPropertiesModel, $name, [
                                'class' => 'form-control',
                            ]);
                        } else {
                            if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_NUMBER) {
                                $filter = "

".\yii\helpers\Html::activeTextInput($searchRelatedPropertiesModel,
                                        $searchRelatedPropertiesModel->getAttributeNameRangeFrom($name), [
                                            'class'       => 'form-control',
                                            'placeholder' => 'от',
                                        ])."

".
                                    \yii\helpers\Html::activeTextInput($searchRelatedPropertiesModel,
                                        $searchRelatedPropertiesModel->getAttributeNameRangeTo($name), [
                                            'class'       => 'form-control',
                                            'placeholder' => 'до',
                                        ])."

";
                            }
                        }
                    }
                }

                $autoColumns[] = [
                    'attribute' => $name,
                    'label'     => \yii\helpers\ArrayHelper::getValue($model->relatedPropertiesModel->attributeLabels(),
                        $name),
                    'visible'   => false,
                    'format'    => 'raw',
                    'filter'    => $filter,
                    'class'     => \yii\grid\DataColumn::class,
                    'value'     => function ($model, $key, $index) use ($name) {
                        /**
                         * @var $model \skeeks\cms\models\CmsContentElement
                         */
                        $value = $model->relatedPropertiesModel->getSmartAttribute($name);
                        if (is_array($value)) {
                            return implode(",", $value);
                        } else {
                            return $value;
                        }
                    },
                ];
            }
        }

    }
    $userColumns = include_once __DIR__."/_columns-select-cms-element.php";

    $columns = \yii\helpers\ArrayHelper::merge($userColumns, $autoColumns);

    ?>

    <?= \skeeks\cms\modules\admin\widgets\GridViewStandart::widget([
        'dataProvider'    => $dataProvider,
        'filterModel'     => $searchModel,
        'enabledCheckbox' => false,
        'autoColumns'     => false,
        'settingsData'    =>
            [
                'namespace' => \Yii::$app->controller->action->getUniqueId().$content_id,
            ],
        'columns'         => $columns,
    ]); ?>

<? endif; ?>


text:
title:  Misjonsfortelling
date:  24/07/2020
---

#### Bønn reddet ekteskapet

_Angelique Abeme (45), Gabon_

Angelique Abeme forelsket seg i Peter da hun var 15 og han 20 år. De flyttet sammen i Oyem i Nord-Gabon, og fikk to jenter. Livet var hardt, og Peter drakk og røykte, men Angelique elsket ham.

Da hun var 25 år, gikk hun på adventistmøter og ble adventist. Men livet ble komplisert etter dåpen. Hun ba Peter gifte seg med henne, men han nektet. Hun ba ham flytte ut, og han dro til Port-Gentil 40 mil lenger sør. Hver dag ba hun om at han måtte finne Jesus. Hun sendte også bibelstudier.

Peter endte opp i fengsel i Port-Gentil da en arbeidsgiver anklaget ham for et tyveri han ikke hadde gjort. I fengselet var det ingenting å ta seg til, så da en adventistkapellan tilbød bibelstudier, slo han til. Han ble døpt kort tid før han slapp ut.

Angelique visste om fengselet, men ikke bibelstudiene. Hun ba for ham morgen og kveld. Etter at han kom ut, ringte han til henne og fortalte om sin tro. "Nå forstår jeg at du ba meg flytte ut," sa han.

Angelique elsket ham ennå. Hun ba om at han måtte vise troens frukt og aldri røyke og drikke igjen. En gang de snakket på telefonen, fortalte hun at hun ville ta med yngstedatteren på speiderleir i Port-Gentil. De ble enige om å treffes. Det var seks år etter at han flyttet ut.

Peter kom og pratet med henne hver dag på speiderleiren. Angelique ble i byen en uke etter speiderleiren for å snakke med ham. Hun så at han var et nytt menneske. Han fridde, og hun sa ja.

Dette var for åtte år siden. I dag er Peter forstander i menigheten i hovedstaden Libreville, og Angelique er så glad. Hun siterer Matteus 6,33 og sier: "Vi må først og fremst søke Guds rike. Hvis du er en troende og din ektefelle ikke er det, så be og be, for Gud kan gjøre mirakler. Han svarte min bønn etter seks år."

For tre år siden bidro offeret 13. sabbat til å bygge en videregående skole for 280 elever i Libreville i Gabon. Takk for at du vil gi penger til å bygge to skoler i Guinea og Liberia dette kvartalet.

Se Angelique på YouTube: bit.ly/Angelique-Abeme

redpajama_set_name: RedPajamaGithub


text:
export default () => {
		let now = new Date();
		let hours = now.getHours();
		let minutes = now.getMinutes();
		minutes = (minutes < 10 ? '0' + minutes : minutes);
		let meridiem = (hours < 12 ? 'AM' : 'PM');
		hours = (hours >= 12 ? hours - 12 : hours);

		let time = hours + ':' + minutes + meridiem;

		return time;
}


text:
package signalfx

import (
	"bytes"
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"sort"
	"strconv"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/signalfx/golib/datapoint"
	"github.com/signalfx/golib/event"
	"github.com/signalfx/golib/sfxclient"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stripe/veneur/protocol/dogstatsd"
	"github.com/stripe/veneur/samplers"
	"github.com/stripe/veneur/ssf"
)

type FakeSink struct {
	mtx       sync.Mutex
	points    []*datapoint.Datapoint
	pointAdds int
	eventAdds int
	events    []*event.Event
}

func NewFakeSink() *FakeSink {
	return &FakeSink{
		points: []*datapoint.Datapoint{},
	}
}

func (fs *FakeSink) AddDatapoints(ctx context.Context, points []*datapoint.Datapoint) (err error) {
	fs.mtx.Lock()
	defer fs.mtx.Unlock()

	fs.points = append(fs.points, points...)
	fs.pointAdds += 1
	return nil
}

func (fs *FakeSink) AddEvents(ctx context.Context, events []*event.Event) (err error) {
	fs.mtx.Lock()
	defer fs.mtx.Unlock()

	fs.events = append(fs.events, events...)
	fs.eventAdds += 1
	return nil
}

type failSink struct{}

func (fs failSink) AddDatapoints(ctx context.Context, points []*datapoint.Datapoint) (err error) {
	return errors.New("simulated failure to send")
}

func (fs failSink) AddEvents(ctx context.Context, events []*event.Event) (err error) {
	return errors.New("simulated failure to send")
}

type testDerivedSink struct {
	samples []*ssf.SSFSample
}

func (d *testDerivedSink) SendSample(sample *ssf.SSFSample) error {
	d.samples = append(d.samples, sample)
	return nil
}

func newDerivedProcessor() *testDerivedSink {
	return &testDerivedSink{
		samples: []*ssf.SSFSample{},
	}
}

func TestNewSignalFxSink(t *testing.T) {
	// test the variables that have been renamed
	client := NewClient("http://www.example.com", "secret", http.DefaultClient)
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), client, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)
	if err != nil {
		t.Fatal(err)
	}
	err = sink.Start(nil)
	if err != nil {
		t.Fatal(err)
	}

	httpsink, ok := client.(*sfxclient.HTTPSink)
	if !ok {
		assert.Fail(t, "SignalFx sink isn't the correct type")
	}
	assert.Equal(t, "http://www.example.com/v2/datapoint", httpsink.DatapointEndpoint)
	assert.Equal(t, "http://www.example.com/v2/event", httpsink.EventEndpoint)

	assert.Equal(t, "signalfx", sink.Name())
	assert.Equal(t, "host", sink.hostnameTag)
	assert.Equal(t, "glooblestoots", sink.hostname)
	assert.Equal(t, map[string]string{"yay": "pie"}, sink.commonDimensions)
}

func TestSignalFxFlushRouting(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)

	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{samplers.InterMetric{
		Name:      "any",
		Timestamp: 1476119058,
		Value:     float64(100),
		Tags: []string{
			"foo:bar",
			"baz:quz",
		},
		Type: samplers.GaugeMetric,
	},
		samplers.InterMetric{
			Name:      "sfx",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"veneursinkonly:signalfx",
			},
			Type:  samplers.GaugeMetric,
			Sinks: samplers.RouteInformation{"signalfx": struct{}{}},
		},
		samplers.InterMetric{
			Name:      "not.us",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"veneursinkonly:anyone_else",
			},
			Type:  samplers.GaugeMetric,
			Sinks: samplers.RouteInformation{"anyone_else": struct{}{}},
		},
	}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 2, len(fakeSink.points))
	metrics := make([]string, 0, len(fakeSink.points))
	for _, pt := range fakeSink.points {
		metrics = append(metrics, pt.Metric)
	}
	sort.Strings(metrics)
	assert.Equal(t, []string{"any", "sfx"}, metrics)
}

func TestSignalFxFlushGauge(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)

	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{samplers.InterMetric{
		Name:      "a.b.c",
		Timestamp: 1476119058,
		Value:     float64(100),
		Tags: []string{
			"foo:bar",
			"baz:quz",
		},
		Type: samplers.GaugeMetric,
	}}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 1, len(fakeSink.points))
	point := fakeSink.points[0]
	assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
	assert.Equal(t, datapoint.Gauge, point.MetricType, "Metric has wrong type")
	val, err := strconv.Atoi(point.Value.String())
	assert.Nil(t, err, "Failed to parse value as integer")
	assert.Equal(t, int(interMetrics[0].Value), val, "Status translates to gauge Value")
	dims := point.Dimensions
	assert.Equal(t, 4, len(dims), "Metric has incorrect tag count")
	assert.Equal(t, "bar", dims["foo"], "Metric has a busted tag")
	assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Metric is missing common tag")
	assert.Equal(t, "glooblestoots", dims["host"], "Metric is missing host tag")
	assert.Empty(t, derived.samples, "Gauges should not generated derived metrics")
}

func TestSignalFxFlushCounter(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)
	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{samplers.InterMetric{
		Name:      "a.b.c",
		Timestamp: 1476119058,
		Value:     10,
		Tags: []string{
			"foo:bar",
			"baz:quz",
			"novalue",
		},
		Type: samplers.CounterMetric,
	}}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 1, len(fakeSink.points))
	point := fakeSink.points[0]
	assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
	assert.Equal(t, datapoint.Count, point.MetricType, "Metric has wrong type")
	val, err := strconv.Atoi(point.Value.String())
	assert.Nil(t, err, "Failed to parse value as integer")
	assert.Equal(t, int(interMetrics[0].Value), val, "Status translates to gauge Value")
	dims := point.Dimensions
	assert.Equal(t, 5, len(dims), "Metric has incorrect tag count")
	assert.Equal(t, "bar", dims["foo"], "Metric has a busted tag")
	assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
	assert.Equal(t, "", dims["novalue"], "Metric has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Metric is missing a common tag")
	assert.Equal(t, "glooblestoots", dims["host"], "Metric is missing host tag")
	assert.Empty(t, derived.samples, "Counters should not generated derived metrics")
}

func TestSignalFxFlushWithDrops(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, []string{"foo.bar"}, []string{"baz:gorch"}, derived, 0, "", false, time.Second, "", "", nil)
	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{
		samplers.InterMetric{
			Name:      "foo.bar.baz", // tag prefix drop
			Timestamp: 1476119058,
			Value:     10,
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"novalue",
			},
			Type: samplers.CounterMetric,
		},
		samplers.InterMetric{
			Name:      "fart.farts",
			Timestamp: 1476119058,
			Value:     10,
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"novalue",
			},
			Type: samplers.CounterMetric,
		},
		samplers.InterMetric{
			Name:      "fart.farts2",
			Timestamp: 1476119058,
			Value:     10,
			Tags: []string{
				"baz:gorch", // literal tag drop
				"baz:quz",
				"novalue",
			},
			Type: samplers.CounterMetric,
		},
	}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 1, len(fakeSink.points))
	point := fakeSink.points[0]
	assert.Equal(t, "fart.farts", point.Metric, "Metric has wrong name")
}

func TestSignalFxFlushStatus(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)
	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{samplers.InterMetric{
		Name:      "a.b.c",
		Timestamp: 1476119058,
		Value:     float64(ssf.SSFSample_UNKNOWN),
		Tags: []string{
			"foo:bar",
			"baz:quz",
			"novalue",
			"veneursinkonly:signalfx", // should not be present in the reported metric
		},
		Type: samplers.StatusMetric,
	}}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 1, len(fakeSink.points))
	point := fakeSink.points[0]
	assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
	assert.Equal(t, datapoint.Gauge, point.MetricType, "Metric has wrong type")
	val, err := strconv.Atoi(point.Value.String())
	assert.Nil(t, err, "Failed to parse value as integer")
	assert.Equal(t, int(ssf.SSFSample_UNKNOWN), val, "Status translates to gauge Value")
	dims := point.Dimensions
	assert.Equal(t, 5, len(dims), "Metric has incorrect tag count")
	assert.Equal(t, "bar", dims["foo"], "Metric has a busted tag")
	assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
	assert.Equal(t, "", dims["novalue"], "Metric has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Metric is missing a common tag")
	assert.Equal(t, "glooblestoots", dims["host"], "Metric is missing host tag")
	assert.Empty(t, derived.samples, "Counters should not generated derived metrics")
}

func TestSignalFxServiceCheckFlushOther(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)
	assert.NoError(t, err)

	serviceCheckMsg := "Service Farts starting[an example link](http://catchpoint.com/session_id \"Title\")"
	ev := ssf.SSFSample{
		Name: "Farts farts farts",
		// Include the markdown bits DD expects, we'll trim it out hopefully!
		Message:   "%%% \n " + serviceCheckMsg + " \n %%%",
		Timestamp: time.Now().Unix(),
		Tags:      map[string]string{"foo": "bar", "baz": "gorch", "novalue": ""},
		Status:    ssf.SSFSample_CRITICAL,
	}
	sink.FlushOtherSamples(context.TODO(), []ssf.SSFSample{ev})

	assert.Empty(t, fakeSink.events)
	assert.Empty(t, derived.samples, "Should ignore any service check")
}

func TestSignalFxEventFlush(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)
	assert.NoError(t, err)

	evMessage := "[an example link](http://catchpoint.com/session_id \"Title\")"
	ev := ssf.SSFSample{
		Name: "Farts farts farts",
		// Include the markdown bits DD expects, we'll trim it out hopefully!
		Message:   "%%% \n " + evMessage + " \n %%%",
		Timestamp: time.Now().Unix(),
		Tags:      map[string]string{"foo": "bar", "baz": "gorch", "novalue": "", dogstatsd.EventIdentifierKey: ""},
	}
	sink.FlushOtherSamples(context.TODO(), []ssf.SSFSample{ev})

	assert.Equal(t, 1, len(fakeSink.events))
	event := fakeSink.events[0]
	assert.Equal(t, ev.Name, event.EventType)
	// We're checking this to ensure the above markdown is also gone!
	assert.Equal(t, event.Properties["description"], evMessage)
	dims := event.Dimensions
	// 5 because 5 passed in, 1 eliminated (event identifier) and 1 added (host!)
	assert.Equal(t, 5, len(dims), "Event has incorrect tag count")
	assert.Equal(t, "bar", dims["foo"], "Event has a busted tag")
	assert.Equal(t, "gorch", dims["baz"], "Event has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Event missing a common tag")
	assert.Equal(t, "", dims["novalue"], "Event has a busted tag")
	assert.Equal(t, "glooblestoots", dims["host"], "Event is missing host tag")
}

func TestSignalFxSetExcludeTags(t *testing.T) {
	fakeSink := NewFakeSink()
	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie", "boo": "snakes"}, logrus.New(), fakeSink, "", nil, nil, nil, derived, 0, "", false, time.Second, "", "", nil)

	sink.SetExcludedTags([]string{"foo", "boo", "host"})
	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{samplers.InterMetric{
		Name:      "a.b.c",
		Timestamp: 1476119058,
		Value:     10,
		Tags: []string{
			"foo:bar",
			"baz:quz",
			"novalue",
		},
		Type: samplers.CounterMetric,
	}}
	sink.Flush(context.Background(), interMetrics)

	ev := ssf.SSFSample{
		Name:      "Test Event",
		Timestamp: time.Now().Unix(),
		Tags: map[string]string{
			dogstatsd.EventIdentifierKey: "",
			"foo":                        "bar",
			"baz":                        "gorch",
			"novalue":                    "",
		},
	}

	sink.FlushOtherSamples(context.Background(), []ssf.SSFSample{ev})

	assert.Equal(t, 1, len(fakeSink.points))
	point := fakeSink.points[0]
	assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
	assert.Equal(t, datapoint.Count, point.MetricType, "Metric has wrong type")
	val, err := strconv.Atoi(point.Value.String())
	assert.Nil(t, err, "Failed to parse value as integer")
	assert.Equal(t, int(interMetrics[0].Value), val, "Status translates to gauge Value")
	dims := point.Dimensions
	assert.Equal(t, 3, len(dims), "Metric has incorrect tag count")
	assert.Equal(t, "", dims["foo"], "Metric has a foo tag despite exclude rule")
	assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
	assert.Equal(t, "", dims["novalue"], "Metric has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Metric is missing a common tag")
	assert.Equal(t, "", dims["boo"], "Metric has host tag despite exclude rule")

	assert.Equal(t, 1, len(fakeSink.events))
	event := fakeSink.events[0]
	assert.Equal(t, ev.Name, event.EventType)
	dims = event.Dimensions
	assert.Equal(t, 3, len(dims), "Event has incorrect tag count")
	assert.Equal(t, "", dims["foo"], "Event has a foo tag despite exclude rule")
	assert.Equal(t, "gorch", dims["baz"], "Event has a busted tag")
	assert.Equal(t, "pie", dims["yay"], "Event missing a common tag")
	assert.Equal(t, "", dims["novalue"], "Event has a busted tag")
	assert.Equal(t, "", dims["boo"], "Event has host tag despite exclude rule")
	assert.Empty(t, derived.samples, "Events should not generated derived metrics")
}

func TestSignalFxFlushMultiKey(t *testing.T) {
	fallback := NewFakeSink()
	specialized := NewFakeSink()

	derived := newDerivedProcessor()
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fallback, "test_by", map[string]DPClient{"available": specialized}, nil, nil, derived, 0, "", false, time.Second, "", "", nil)

	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{
		samplers.InterMetric{
			Name:      "a.b.c",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:needs_fallback",
			},
			Type: samplers.GaugeMetric,
		},
		samplers.InterMetric{
			Name:      "a.b.c",
			Timestamp: 1476119058,
			Value:     float64(99),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:available",
			},
			Type: samplers.GaugeMetric,
		},
	}

	sink.Flush(context.TODO(), interMetrics)

	assert.Equal(t, 1, len(fallback.points))
	assert.Equal(t, 1, len(specialized.points))
	{
		point := fallback.points[0]
		assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
		assert.Equal(t, datapoint.Gauge, point.MetricType, "Metric has wrong type")
		val, err := strconv.Atoi(point.Value.String())
		assert.Nil(t, err, "Failed to parse value as integer")
		assert.Equal(t, int(interMetrics[0].Value), val, "Status translates to gauge Value")
		dims := point.Dimensions
		assert.Equal(t, 5, len(dims), "Metric has incorrect tag count")
		assert.Equal(t, "bar", dims["foo"], "Metric has a busted tag")
		assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
		assert.Equal(t, "pie", dims["yay"], "Metric is missing common tag")
		assert.Equal(t, "glooblestoots", dims["host"], "Metric is missing host tag")
		assert.Equal(t, "needs_fallback", dims["test_by"], "Metric should have the right test_by tag")
	}
	{
		point := specialized.points[0]
		assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
		assert.Equal(t, datapoint.Gauge, point.MetricType, "Metric has wrong type")
		val, err := strconv.Atoi(point.Value.String())
		assert.Nil(t, err, "Failed to parse value as integer")
		assert.Equal(t, int(interMetrics[1].Value), val, "Status translates to gauge Value")
		dims := point.Dimensions
		assert.Equal(t, 5, len(dims), "Metric has incorrect tag count")
		assert.Equal(t, "bar", dims["foo"], "Metric has a busted tag")
		assert.Equal(t, "quz", dims["baz"], "Metric has a busted tag")
		assert.Equal(t, "pie", dims["yay"], "Metric is missing common tag")
		assert.Equal(t, "glooblestoots", dims["host"], "Metric is missing host tag")
		assert.Equal(t, "available", dims["test_by"], "Metric should have the right test_by tag")
	}
	assert.Empty(t, derived.samples, "Gauges should not generated derived metrics")
}

func TestSignalFxFlushBatches(t *testing.T) {
	fallback := NewFakeSink()

	derived := newDerivedProcessor()
	perBatch := 1
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fallback, "test_by", map[string]DPClient{}, nil, nil, derived, perBatch, "", false, time.Second, "", "", nil)

	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{
		samplers.InterMetric{
			Name:      "a.b.c",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:first",
			},
			Type: samplers.GaugeMetric,
		},
		samplers.InterMetric{
			Name:      "a.b.c",
			Timestamp: 1476119058,
			Value:     float64(99),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:second",
			},
			Type: samplers.GaugeMetric,
		},
	}

	require.NoError(t, sink.Flush(context.TODO(), interMetrics))

	assert.Equal(t, 2, len(fallback.points))
	assert.Equal(t, 2, fallback.pointAdds)
	found := map[string]bool{}

	for _, point := range fallback.points {
		assert.Equal(t, "a.b.c", point.Metric, "Metric has wrong name")
		found[point.Dimensions["test_by"]] = true
	}
	assert.True(t, found["first"])
	assert.True(t, found["second"])
}

func TestSignalFxFlushBatchHang(t *testing.T) {
	fallback := failSink{}

	derived := newDerivedProcessor()
	perBatch := 1
	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fallback, "test_by", map[string]DPClient{}, nil, nil, derived, perBatch, "", false, time.Second, "", "", nil)

	assert.NoError(t, err)

	interMetrics := []samplers.InterMetric{
		samplers.InterMetric{
			Name:      "a.b.c",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:first",
			},
			Type: samplers.GaugeMetric,
		},
		samplers.InterMetric{
			Name:      "a.b.c.d",
			Timestamp: 1476119058,
			Value:     float64(100),
			Tags: []string{
				"foo:bar",
				"baz:quz",
				"test_by:first",
			},
			Type: samplers.GaugeMetric,
		},
	}

	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
	defer cancel()
	require.Error(t, sink.Flush(ctx, interMetrics))
}

func TestNewSinkDoubleSlashes(t *testing.T) {
	cl := NewClient("http://example.com/", "foo", nil).(*sfxclient.HTTPSink)
	assert.Equal(t, "http://example.com/v2/datapoint", cl.DatapointEndpoint)
	assert.Equal(t, "http://example.com/v2/event", cl.EventEndpoint)
}

const (
	response1 = `{
  "results": [
    {
      "name": "service",
      "secret": "accessToken"
    },
    {
      "name": "differentService",
      "secret": "differentAccessToken"
    }
  ]
}`
	response2 = `{
  "results": [
  ]
}`
	response3 = `{
  "results": [
    {
      "name": "thirdService",
      "secret": "thirdAccessToken"
    }
  ]
}`
)

func TestSignalFxExtractTokensFromResponse(t *testing.T) {
	tests := []struct {
		input         string
		output        map[string]string
		expectedCount int
	}{
		{
			input: response1,
			output: map[string]string{
				"service":          "accessToken",
				"differentService": "differentAccessToken",
			},
			expectedCount: 2,
		},
		{
			input:         response2,
			output:        map[string]string{},
			expectedCount: 0,
		},
	}

	for _, test := range tests {
		result := make(map[string]string)
		b := bytes.NewBufferString(test.input)

		count, err := extractTokensFromResponse(result, b)

		require.NoError(t, err)
		require.Equal(t, test.expectedCount, count)
		require.Equal(t, test.output, result)
	}
}

// mockHandler cycles through a slice of predefined HTTP responses
type mockHandler struct {
	responses []string
	index     int64
}

func (m *mockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	resp.WriteHeader(http.StatusOK)
	response := m.responses[atomic.LoadInt64(&m.index)%int64(len(m.responses))]
	resp.Write([]byte(response))
	atomic.AddInt64(&m.index, 1)
}

func TestSignalFxFetchAPITokens(t *testing.T) {
	m := &mockHandler{
		responses: []string{
			response1,
			response3,
			response2,
		},
	}

	server := httptest.NewServer(m)

	expected := map[string]string{
		"service":          "accessToken",
		"differentService": "differentAccessToken",
		"thirdService":     "thirdAccessToken",
	}

	result, err := fetchAPIKeys(server.Client(), server.URL, "")
	require.NoError(t, err)
	require.Equal(t, expected, result)
}

func TestSignalFxClientByTagUpdater(t *testing.T) {
	const dynamicKeyRefreshPeriod = 1 * time.Millisecond
	m := &mockHandler{
		responses: []string{
			response1,
			response3,
			response2,
		},
	}

	server := httptest.NewServer(m)

	fallback := NewFakeSink()

	derived := newDerivedProcessor()
	perBatch := 1

	sink, err := NewSignalFxSink("host", "glooblestoots", map[string]string{"yay": "pie"}, logrus.New(), fallback, "test_by", map[string]DPClient{}, nil, nil, derived, perBatch, "", true, dynamicKeyRefreshPeriod, "", server.URL, server.Client())
	require.NoError(t, err)

	err = sink.Start(nil)
	require.NoError(t, err)

	timeout := time.After(100 * dynamicKeyRefreshPeriod)
	interval := time.NewTicker(2 * dynamicKeyRefreshPeriod)

LOOP:
	for {
		select {
		case <-timeout:
			require.FailNow(t, "Timed out waiting for SignalFX sink to synchronize clients")
		case <-interval.C:
			// The sink polls and updates serially, so by the time it has made the fourth
			// request, it is guaranteed to have finished processing the third.
			if atomic.LoadInt64(&m.index) >= 4 {
				break LOOP
			}
		}
	}

	sink.clientsByTagValueMu.Lock()
	defer sink.clientsByTagValueMu.Unlock()

	expectedPerTagClients := []string{
		"service",
		"differentService",
		"thirdService",
	}

	actualPerTagClients := make([]string, 0)

	mindex := atomic.LoadInt64(&m.index)
	assert.True(t, mindex >= 3, "m.index should be at least 3, not %d", mindex)
	assert.Equal(t, len(expectedPerTagClients), len(sink.clientsByTagValue), "Sink should have %d clients", len(expectedPerTagClients))
	for tag, client := range sink.clientsByTagValue {
		actualPerTagClients = append(actualPerTagClients, tag)
		require.NotNil(t, client)
	}

	sort.Strings(expectedPerTagClients)
	sort.Strings(actualPerTagClients)

	// Check that both sets are equal (subsets of each other)
	// The order might be different due to modular division, but we should always receive the same
	// three responses
	assert.Subset(t, expectedPerTagClients, actualPerTagClients, "The actual values should be a subset of the expected values")
	assert.Subset(t, actualPerTagClients, expectedPerTagClients, "The expected values should be a subset of the actual values")

}


text:
/* -*- mode: C++; c-basic-offset: 4; -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
 * Copyright (c) 2015, Rice University
 * All rights reserved.
 *
 * Author(s): Neil T. Dantam <ntd@rice.edu>
 *
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of copyright holder the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "amino.h"
#include "amino/rx/rxerr.h"
#include "amino/rx/rxtype.h"
#include "amino/rx/scenegraph.h"
#include "amino/rx/scenegraph_internal.h"
#include "amino/rx/scene_geom.h"
#include "amino/rx/scene_ik_internal.h"
#include "amino/rx/scene_sub.h"
#include "amino/rx/scene_collision.h"
#include "amino/rx/scene_planning.h"

#include "amino/rx/ompl/scene_state_space.h"
#include "amino/rx/ompl/scene_state_validity_checker.h"
#include "amino/rx/ompl/scene_workspace_goal.h"
#include "amino/rx/ompl/scene_ompl_internal.h"

#include <ompl/base/Planner.h>
#include <ompl/base/SpaceInformation.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
#include <ompl/geometric/PathGeometric.h>
#include <ompl/geometric/PathSimplifier.h>
#include <ompl/base/goals/GoalLazySamples.h>

struct aa_rx_mp;

aa_rx_mp::aa_rx_mp( const struct aa_rx_sg_sub *sub_sg ) :
    config_start(NULL),
    space_information(
        new amino::sgSpaceInformation(
            amino::sgSpaceInformation::SpacePtr(
                new amino::sgStateSpace (sub_sg)))),
    problem_definition(new ompl::base::ProblemDefinition(space_information)),
    simplify(0),
    validity_checker(new amino::sgStateValidityChecker(space_information.get())),
    lazy_samples(NULL),
    collisions(NULL)
{

    space_information->setStateValidityChecker( ompl::base::StateValidityCheckerPtr(validity_checker) );
    space_information->setup();
}

AA_API struct aa_rx_mp*
aa_rx_mp_create( const struct aa_rx_sg_sub *sub_sg )
{
    return new aa_rx_mp(sub_sg);
}

AA_API void
aa_rx_mp_destroy( struct aa_rx_mp *mp )
{
    aa_checked_free(mp->config_start);
    delete mp;
}

aa_rx_mp::~aa_rx_mp()
{
    if( this->collisions ) aa_rx_cl_set_destroy(this->collisions);
}

AA_API void
aa_rx_mp_set_start( struct aa_rx_mp *mp,
                    size_t n_all,
                    double *q_all )
{
    /* Assume the start state is valid */
    aa_rx_mp_allow_config(mp, n_all, q_all);

    // FIXME: Seems that there are problems if this is called repeatedly
    amino::sgSpaceInformation::Ptr &si = mp->space_information;
    amino::sgStateSpace *ss = si->getTypedStateSpace();

    /* Add Start State */
    amino::sgSpaceInformation::ScopedStateType state(si);
    ss->extract_state( q_all, state.get() );
    mp->problem_definition->addStartState(state);

    /* Copy full start */
    aa_checked_free(mp->config_start);
    mp->config_start = AA_MEM_DUP(double, q_all, n_all);
}

AA_API void
aa_rx_mp_allow_config( struct aa_rx_mp *mp,
                       size_t n_all,
                       double *q_all )
{
    amino::sgSpaceInformation::Ptr &si = mp->space_information;
    amino::sgStateSpace *ss = si->getTypedStateSpace();
    ss->allow_config(q_all);

    mp->validity_checker->set_start(n_all, q_all);
}

AA_API void
aa_rx_mp_allow_collision( struct aa_rx_mp *mp,
                          aa_rx_frame_id id0, aa_rx_frame_id id1, int allowed )
{
    amino::sgSpaceInformation::Ptr &si = mp->space_information;
    amino::sgStateSpace *ss = si->getTypedStateSpace();
    aa_rx_cl_set_set( ss->allowed, id0, id1, allowed );
    mp->validity_checker->allow();
}

AA_API int
aa_rx_mp_set_goal( struct aa_rx_mp *mp,
                   size_t n_q,
                   double *q_subset)
{

    amino::sgSpaceInformation::Ptr &si = mp->space_information;
    amino::sgStateSpace *ss = si->getTypedStateSpace();
    const struct aa_rx_sg_sub *ssg = ss->sub_scene_graph;
    size_t n_s = aa_rx_sg_sub_config_count(ssg);
    assert( n_q == n_s );
    amino::sgSpaceInformation::ScopedStateType state(mp->space_information);
    ss->copy_state( q_subset, state.get() );

    mp->validity_checker->allow();
    if( si->isValid( state.get() ) ) {
        mp->problem_definition->setGoalState(state);
        return AA_RX_OK;
    } else {
        return AA_RX_INVALID_STATE;
    }
}

static void
path_cleanup( struct aa_rx_mp *mp, ompl::geometric::PathGeometric &path )
{
    amino::sgSpaceInformation::Ptr &si = mp->space_information;

    if( mp->simplify ) {
        ompl::geometric::PathSimplifier ps(si);
        int n = (int)path.getStateCount();
        path.interpolate(n*10);

        for( int i = 0; i < 10; i ++ ) {
            ps.reduceVertices(path);
            ps.collapseCloseVertices(path);
            ps.shortcutPath(path);
        }

        ps.smoothBSpline(path, 3, path.length()/100.0);
    }
}

AA_API int
aa_rx_mp_plan( struct aa_rx_mp *mp,
               double timeout,
               size_t *n_path,
               double **p_path_all )
{

    amino::sgSpaceInformation::Ptr &si = mp->space_information;
    amino::sgStateSpace *ss = si->getTypedStateSpace();

    /* Configure State Validity Checker */
    mp->validity_checker->allow();

    /* clear set */
    if( mp->collisions ) {
        aa_rx_cl_set_clear(mp->collisions);
    }

    /* Setup Space */

    *n_path = 0;
    *p_path_all = NULL;

    ompl::base::ProblemDefinitionPtr &pdef = mp->problem_definition;

    ompl::base::PlannerPtr planner = (NULL == mp->planner.get()) ?
        ompl::base::PlannerPtr(new ompl::geometric::RRTConnect(si)) :
        mp->planner;

    planner->setProblemDefinition(pdef);
    try {
        if( mp->lazy_samples ) {
            fprintf(stderr, "Starting sampling thread\n");
            mp->lazy_samples->clear();
            mp->lazy_samples->setStart(ss->config_count_all(), mp->config_start);
            mp->lazy_samples->startSampling();
        }
        planner->solve(timeout);
        if( mp->lazy_samples ) {
            fprintf(stderr, "Stopping sampling thread\n");
            mp->lazy_samples->stopSampling();
        }
    } catch(...) {
        return AA_RX_NO_SOLUTION;
    }
    if( pdef->hasExactSolution() ) {
        const ompl::base::PathPtr &path_ptr = pdef->getSolutionPath();
        ompl::geometric::PathGeometric &path = static_cast<ompl::geometric::PathGeometric&>(*path_ptr);
        path_cleanup(mp, path);

        /* Allocate a simple array */
        *n_path = path.getStateCount();
        *p_path_all = (double*)calloc( *n_path * ss->config_count_all(),
                                       sizeof(double) );

        /* Fill array */
        std::vector< ompl::base::State *> &states = path.getStates();
        double *ptr = *p_path_all;
        for( auto itr = states.begin(); itr != states.end(); itr++, ptr += ss->config_count_all() )
        {
            AA_MEM_CPY( ptr, mp->config_start, ss->config_count_all() );
            amino::sgSpaceInformation::StateType *state = amino::sgSpaceInformation::state_as(*itr);
            ss->insert_state( state, ptr );
        }
        return AA_RX_OK;
    } else {
        return AA_RX_NO_SOLUTION | AA_RX_NO_MP;
    }
}

AA_API void
aa_rx_mp_set_simplify( struct aa_rx_mp *mp,
                       int simplify )
{
    mp->simplify = simplify ? 1 : 0;
}

AA_API void
aa_rx_mp_set_track_collisions( struct aa_rx_mp *mp, int track )
{
    /* Destroy existing collision set */
    if( mp->collisions ) {
        aa_rx_cl_set_destroy(mp->collisions);
        mp->collisions = NULL;
    }

    /* Create new collision set */
    if( track ) {
        mp->track_collisions = 1;
        amino::sgStateSpace *ss = mp->space_information->getTypedStateSpace();
        mp->collisions = aa_rx_cl_set_create( ss->get_scene_graph() );
    } else {
        mp->track_collisions = 0;

    }

    /* Setup state validity checker tracking */
    mp->validity_checker->collisions = mp->collisions;
}

AA_API const struct aa_rx_cl_set *
aa_rx_mp_get_collisions( const struct aa_rx_mp *mp )
{
    return mp->collisions;
}

AA_API struct aa_rx_cl_set*
aa_rx_mp_get_allowed( const struct aa_rx_mp* mp)
{
    return mp->space_information->getTypedStateSpace()->allowed;
}

ompl::base::SpaceInformationPtr
aa_rx_mp_get_space_information( const struct aa_rx_mp *mp)
{
    return mp->space_information;
}

void
aa_rx_mp_set_planner( struct aa_rx_mp *mp, ::ompl::base::Planner *planner)
{
    mp->set_planner(planner);
}


text:
/* DHT library

MIT license
written by Adafruit Industries
*/
#ifndef DHT_H
#define DHT_H

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#include "./debug.h"

// Define types of sensors.
#define DHT11 11

class DHT {
  public:
   DHT(uint8_t pin, uint8_t type);
   void begin(void);
   float readTemperature(bool force=false);
   float readHumidity(bool force=false);
   boolean read(bool force=false);

 private:
  uint8_t data[5];
  uint8_t _pin, _type;
  #ifdef __AVR
    // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask
    // for the digital pin connected to the DHT.  Other platforms will use digitalRead.
    uint8_t _bit, _port;
  #endif
  uint32_t _lastreadtime, _maxcycles;
  bool _lastresult;

  uint32_t expectPulse(bool level);

};

class InterruptLock {
  public:
   InterruptLock() {
    noInterrupts();
   }
   ~InterruptLock() {
    interrupts();
   }

};

#endif


text:
package ar.edu.itba.it.sma.rigged;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Rigged {

	public static void main(String[] args) {
		SpringApplication.run(Rigged.class, args);
	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>

    <title>A4M36SEP semestral project by Filip Klimes</title>

Create Change Request - Suspend

        <form action="#" th:action="@{/change-requests/suspend}" th:object="${form}" method="post">

                Client ID
                <input id="clientId" type="number" th:field="*{clientId}" class="form-control"/>
                Client ID
                    Error

            <button type="submit" class="btn btn-default">Submit</button>
        </form>


text:
/* This class implements the Compression interface */
package myexternalsort;

import externallist.ExternalList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Nino
 */
public class CompressionUnit implements Compression {

    private String csvFilePath;
    private String fenwickTreeFilePath;
    private int rows;
    private int columns;
    private int[] columnOrdering;
    private HashMap<Integer, Integer> distinctValuesByColumn;
    private HashMap<Integer, ArrayList<Integer>> columnLimitIndexing;
    private FenwickTreeFile csvIndexing;
    private RandomAccessFile csvRaf;

    public CompressionUnit() {

        this.csvFilePath = null;
        this.fenwickTreeFilePath = null;
        this.rows = 0;
        this.columns = 0;
        this.columnOrdering = null;
        this.distinctValuesByColumn = null;
        this.columnLimitIndexing = null;
        this.csvIndexing = null;

    }

    public CompressionUnit(String csvFilePath, String fenwickTreeFilePath) throws FileNotFoundException {

        this.csvFilePath = csvFilePath;
        this.fenwickTreeFilePath = fenwickTreeFilePath;

        try {
            this.csvRaf = new RandomAccessFile(this.csvFilePath, "rw");
        } catch (FileNotFoundException e) {
            System.out.println("File does not exist!");
            System.exit(1);
        }

    }

    public String getCsvFilePath() {
        return csvFilePath;
    }

    public void setCsvFilePath(String csvFilePath) {
        this.csvFilePath = csvFilePath;
    }

    public String getFenwickTreeFilePath() {
        return fenwickTreeFilePath;
    }

    public void setFenwickTreeFilePath(String fenwickTreeFilePath) {
        this.fenwickTreeFilePath = fenwickTreeFilePath;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getColumns() {
        return columns;
    }

    public void setColumns(int columns) {
        this.columns = columns;
    }

    public int[] getColumnOrdering() {
        return columnOrdering;
    }

    public void setColumnOrdering(int[] columnOrdering) {
        this.columnOrdering = columnOrdering;
    }

    public HashMap<Integer, Integer> getDistinctValuesByColumn() {
        return distinctValuesByColumn;
    }

    public void setDistinctValuesByColumn(HashMap<Integer, Integer> distinctValuesByColumn) {
        this.distinctValuesByColumn = distinctValuesByColumn;
    }

    public HashMap<Integer, ArrayList<Integer>> getColumnLimitIndexing() {
        return columnLimitIndexing;
    }

    public void setColumnLimitIndexing(HashMap<Integer, ArrayList<Integer>> columnLimitIndexing) {
        this.columnLimitIndexing = columnLimitIndexing;
    }

    public FenwickTreeFile getCsvIndexing() {
        return csvIndexing;
    }

    public void setCsvIndexing(FenwickTreeFile csvIndexing) {
        this.csvIndexing = csvIndexing;
    }

    /* This method overrides the compressCSV method provided
     * by the Compression interface
     */
    @Override
    public String compressCSV(String csvFilePath, boolean containsHeader, boolean quoted) {

        try {

            // first we get the data necessary to begin sorting the file
            long s, e;

            String header = null;

            if (containsHeader || quoted) {
                FilePreProcessor fpp = new FilePreProcessor(csvFilePath);
                header = fpp.removeHeaders(containsHeader);
                if (quoted) {
                    fpp.escapeCommas();
                }
            }

            s = System.currentTimeMillis();

            IntegerArrayAndMapWrapper iamw = Analytics.analyzeDistinctValuesByColumn(csvFilePath);

            e = System.currentTimeMillis();
            System.out.println("Analytics took " + (e - s) + "ms.");

            if (iamw != null) {

                rows = iamw.getRows();
                columns = iamw.getColumns();
                columnOrdering = iamw.getOrder();
                System.out.println("rows = " + rows + " columns = " + columns);

                s = System.currentTimeMillis();

                MyExternalSort.externalSort(csvFilePath, rows, columns, columnOrdering);
                e = System.currentTimeMillis();
                System.out.println("Sorting took " + (e - s) + "ms.");

                IndexingUnit indexingUnit = new IndexingUnit(OS_Properties.TEMP_DIR_PATH + "test_output.dat", rows, columns);
                s = System.currentTimeMillis();

                FenwickTreeFile fwt = indexingUnit.getIndexedCommas();
                e = System.currentTimeMillis();
                System.out.println("Indexing and building Fenwick tree took " + (e - s) + "ms.");

                s = System.currentTimeMillis();
                HashMap<Integer, ExternalList> indexedColumns = indexingUnit.indexColumns(OS_Properties.TEMP_DIR_PATH
                        + OS_Properties.FILE_SEPARATOR + "test_output.dat", iamw.getOrder(), fwt);

                e = System.currentTimeMillis();
                System.out.println("Second indexing and building Fenwick tree took " + (e - s) + "ms.");

                System.out.println("FWT SIZE = " + fwt.N);

                String outPath = csvFilePath.replaceAll(".csv", ".csvcomp");

                String toSearchFor = null;
                StringBuilder sb = new StringBuilder(Byte.MAX_VALUE);
                ArrayList<Integer> indices;
                StringBuilder line = new StringBuilder(Byte.MAX_VALUE * (columns + 1));

                File file = new File(outPath);
                file.createNewFile();
                PrintWriter pw = new PrintWriter(new FileWriter(file));
                ExternalList list = null;

                /* Write the header to the compressed file if the original file contains one */
                if (header != null) {
                    pw.println(header);
                }

                /* Attach a RandomAccessFile utility to the sorted output */
                this.csvRaf = new RandomAccessFile(OS_Properties.TEMP_DIR_PATH + "test_output.dat", "rw");

                s = System.currentTimeMillis();

                try {

                    //the null list has already "finished"
                    int sortedColumnStart = 0, sortedColumnEnd, firstIndex, lastIndex, count;
                    int[] next = new int[indexedColumns.size()];
                    int[] pos = new int[indexedColumns.size()];
                    SimpleBitMap finished = new SimpleBitMap(next.length);

                    // Initialize the next index in the Binary Indexed Tree which is to be read from
                    for (int i = 0; i < next.length; i++) {
                        if (indexedColumns.get(i) != null) {
                            next[i] = indexedColumns.get(i).get(pos[i]);
                        } else {
                            next[i] = i;
                        }
                    }

                    // Get the infromation about the size of single-sorted columnar intervals
                    int[] listSize = new int[next.length];
                    for (int i = 0; i < next.length; i++) {
                        if (indexedColumns.get(i) != null) {
                            listSize[i] = indexedColumns.get(i).size();
                        } else {
                            listSize[i] = -1;
                        }
                    }

                    while (finished.getCardinality() < finished.getSize()) {

                        for (int j = 0; j < next.length; j++) {
                            if (next[j] >= fwt.N) {
                                finished.set(j);
                            }
                        }

                        for (int i = 0; i < next.length; i++) {

                            if (!finished.get(i)) {
                                if (indexedColumns.get(i) != null) {

                                    list = indexedColumns.get(i);

                                    if (pos[i] < listSize[i] - 1) {
                                        if (next[i] < list.get(pos[i] + 1)) {
                                            sortedColumnStart = list.get(pos[i]);
                                        } else {
                                            pos[i]++;
                                            next[i] = list.get(pos[i]);
                                            sortedColumnStart = next[i];
                                        }
                                        if (pos[i] == listSize[i] - 1) {
                                            int x = next[i];
                                            while ((x + columns) < fwt.N) {   //go to the bottom of the column
                                                x += columns;
                                            }
                                            sortedColumnEnd = x;

                                        } else {
                                            sortedColumnEnd = list.get(pos[i] + 1) - columns;
                                        }
                                    } else if (pos[i] == listSize[i] - 1) {

                                        sortedColumnStart = list.get(pos[i]);

                                        int x = next[i];
                                        while ((x + columns) < fwt.N) {   //go to the bottom of the column
                                            x += columns;
                                        }
                                        sortedColumnEnd = x;

                                    } else {
                                        sortedColumnEnd = i + (rows - 1) * columns;
                                    }
                                } else {
                                    sortedColumnStart = i;
                                    sortedColumnEnd = i + (rows - 1) * columns;
                                }

                                byte n;
                                csvRaf.seek(fwt.read(next[i]));

                                n = (byte) csvRaf.read();

                                while ((char) n != ',' && !OS_Properties.LINE_SEPARATOR.contains(String.valueOf((char) n)) && n != -1) {
                                    sb.append((char) n);
                                    n = (byte) csvRaf.read();
                                }

                                toSearchFor = sb.toString();
                                sb.setLength(0);                                //reset the string builder

                                /* The following method invocations are used to
                                 * find the first and last occurrence of the
                                 * toSearcFor cell in the CSV.
                                 * Implemented using Binary Search
                                 */
                                firstIndex = Utilities.binarySearchFirst(toSearchFor, csvRaf, fwt, i, sortedColumnStart, sortedColumnEnd, rows, columns);
                                lastIndex = Utilities.binarySearchLast(toSearchFor, csvRaf, fwt, i, sortedColumnStart, sortedColumnEnd, rows, columns, firstIndex);

                                count = (lastIndex - firstIndex) / columns + 1;
                                line.append(toSearchFor).append(' ').append(count);

                                if (i == next.length - 1) {
                                    pw.println(line.toString());
                                    pw.flush();                                 //flush the print writer
                                    line.setLength(0);                          //reset the string builder
                                } else {
                                    line.append(',');
                                }

                                int prev = next[i];
                                next[i] = lastIndex + columns;

                            } else {

                                if (i < next.length - 1) {
                                    line.append(',');
                                } else {
                                    line.append(OS_Properties.LINE_SEPARATOR);
                                    if (line.toString().length() > 100000) {
                                        pw.print(line.toString());
                                        line.setLength(0);                      //reset the string builder
                                        pw.flush();                             //flush the print writer
                                    }
                                }
                            }
                        }
                    }
                } finally {
                    fwt.disposeTree();
                    csvRaf.close();
                    fwt.fc.close();
                    fwt.raf.close();
                    pw.close();
                }

                e = System.currentTimeMillis();
                System.out.println("Compression took " + (e - s) + "ms.");

                //return the header to the original file if it contains one
                if (containsHeader) {
                    FilePreProcessor f = new FilePreProcessor(csvFilePath);
                    f.returnHeaderAndCommasToOriginalFile(header, quoted);
                }

                return outPath;
            }

        } catch (FileNotFoundException ex) {
            System.err.printf("File %s not found.\nCompression cannot proceed.\nSystem will now exit.\n", csvFilePath);
            System.out.println(ex.getMessage());
            System.exit(1);
        } catch (IOException ex) {
            System.err.printf("Unexpected I/O exception occurred at this point.\nCompression cannot proceed.\nSystem will now exit.\n");
            System.exit(1);
        } catch (Exception ex) {
        }

        return null;

    }

    /* This method overrides the decompressCSV method provided by the
     * Compression interface.
     */
    @Override
    public void decompressCSV(String compressedCsvFilePath, boolean containsHeader, boolean quoted) {

        int index, rowsN, columnsN, currentPositionInFile;
        long bufStart, bufSize, fileSize, byteCounter = 0;
        byte n;

        FileChannel fileChannel = null;
        MappedByteBuffer IO = null;
        FenwickTreeFile fwt = null;
        PrintWriter pw = null;
        Queue<DecompressionWrapper> queues[];

        try {

            String header = null;

            if (containsHeader) {
                FilePreProcessor f = new FilePreProcessor(compressedCsvFilePath);
                header = f.removeHeaders(containsHeader);
            }

            rowsN = Analytics.rows(compressedCsvFilePath);
            columnsN = Analytics.columns(compressedCsvFilePath);

            fileChannel = new RandomAccessFile(compressedCsvFilePath, "rw").getChannel();
            fileSize = Files.size(Paths.get(compressedCsvFilePath));
            bufStart = 0;
            bufSize = fileSize < 100 * 1024 * 1024 ? fileSize : 100 * 1024 * 1024;

            IO = fileChannel.map(FileChannel.MapMode.READ_ONLY, bufStart, bufSize);

            queues = new LinkedList[columnsN];
            for (int i = 0; i < queues.length; i++) {
                queues[i] = new LinkedList<>();
            }

            IO.rewind();

            StringBuilder sb = new StringBuilder(256);
            index = 0;
            currentPositionInFile = 0;

            while (IO.hasRemaining()) {

                n = IO.get();

                if ((char) n == ',') {

                    currentPositionInFile += sb.length();
                    queues[index].add(new DecompressionWrapper(sb.toString()));
                    sb.setLength(0);
                    index = (index + 1) % columnsN;

                } else if ((char) n == OS_Properties.LINE_SEPARATOR.charAt(OS_Properties.OS_LS_INDEX)) {

                    currentPositionInFile += sb.length();
                    queues[index].add(new DecompressionWrapper(sb.toString()));
                    sb.setLength(0);
                    index = (index + 1) % columnsN;
                    break;

                } else if (!OS_Properties.LINE_SEPARATOR.contains(String.valueOf((char) n))) {
                    sb.append((char) n);
                }
            }

            StringBuilder sb2 = new StringBuilder(50 * 1024);
            DecompressionWrapper reference;
            String decompressedOutputFile = compressedCsvFilePath.replaceAll(".csvcomp", "_d.csv");
            File a = new File(decompressedOutputFile);
            a.createNewFile();
            pw = new PrintWriter(new FileWriter(a));

            fwt = new IndexingUnit(compressedCsvFilePath, rowsN, columnsN).getIndexedCommas();

            int[] lastIndex = new int[queues.length];
            for (int i = 0; i < lastIndex.length; i++) {
                lastIndex[i] = i;
            }

            SimpleBitMap bitmap = new SimpleBitMap(columnsN);
            while (bitmap.getCardinality() < bitmap.getSize()) {

                int min = Integer.MAX_VALUE, minPos = -1;

                for (int i = 0; i < queues.length; i++) {
                    if (!queues[i].isEmpty()) {
                        int count = queues[i].peek().count;
                        if (count < min) {
                            min = count;
                            minPos = i;
                        }
                    }
                }

                if (minPos == -1) {
                    break;
                }

                reference = queues[minPos].peek();

                while (reference.count > 0) {

                    for (int i = 0; i < queues.length; i++) {
                        if (!queues[i].isEmpty()) {

                            sb2.append(queues[i].peek().getText());
                            queues[i].peek().count--;

                            if (i >= 0 && i < queues.length - 1) {
                                sb2.append(',');
                            } else if (i == queues.length - 1) {
                                pw.println(sb2.toString());
                                sb2.setLength(0);
                            } else {
                                // do nothing
                            }
                        }
                    }

                }

                // remove the written content from the min-queue
                for (int i = 0; i < queues.length; i++) {
                    if (!queues[i].isEmpty()) {
                        DecompressionWrapper d = queues[i].peek();
                        if (d.count == 0) {
                            queues[i].poll();
                        }
                    }
                }

                for (int i = 0; i < queues.length; i++) {

                    if (queues[i].isEmpty()) {

                        int newFwtIndex = lastIndex[i] + columnsN;
                        int newIndexInFile;
                        if (newFwtIndex < fwt.N) {

                            newIndexInFile = (int) fwt.read(newFwtIndex);
                            lastIndex[i] = newFwtIndex;

                            if (newIndexInFile < bufStart || newIndexInFile + 128 > bufStart + bufSize) {
                                bufStart = newIndexInFile;
                                bufSize = (fileSize - bufStart) < 100 * 1024 * 1024 ? (fileSize - bufStart) : 100 * 1024 * 1024;
                                IO = fileChannel.map(MapMode.READ_ONLY, bufStart, bufSize);
                                IO.rewind();
                            }

                            sb.setLength(0);                                    //reset the string builder

                            while (IO.hasRemaining()) {
                                n = IO.get(newIndexInFile - (int) bufStart);
                                if ((char) n == ',' || (char) n == OS_Properties.LINE_SEPARATOR.charAt(OS_Properties.OS_LS_INDEX)) {
                                    break;
                                } else if (!OS_Properties.LINE_SEPARATOR.contains(String.valueOf((char) n))) {
                                    sb.append((char) n);
                                }
                                newIndexInFile++;
                            }

                            String aux = sb.toString();

                            if (!aux.isEmpty() && !aux.equals(OS_Properties.LINE_SEPARATOR) && !aux.equals(",")) {

                                currentPositionInFile += aux.length();
                                try {
                                    queues[i].add(new DecompressionWrapper(aux));
                                } catch (ArrayIndexOutOfBoundsException e) {
                                    //do nothing, it won't be created nor added to the queue
                                    currentPositionInFile -= aux.length();
                                } catch (NumberFormatException ee) {
                                }
                            }
                            sb.setLength(0);                                    //reset the string builder

                        } else {
                            bitmap.set(i);                                      //mark the queue as "finished"
                        }
                    }
                }
            }

            /* Write the header if it exists and then convert the escaped commas back to their inital format */
            if (containsHeader) {
                FilePreProcessor f = new FilePreProcessor(decompressedOutputFile);
                f.returnHeaderAndCommasToOriginalFile(header, quoted);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(CompressionUnit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CompressionUnit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(CompressionUnit.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            if (pw != null) {
                pw.close();
            }
            try {
                if (fwt != null) {
                    fwt.raf.close();
                    fwt.fc.close();
                }

                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
            }
        }
    }
}


text:
//
// Go-FTL
//
// Copyright (C) Philip Schlump, 2014-2016
//
// Do not remove the following lines - used in auto-update.
// Version: 0.5.9
// BuildNo: 1811
// FileId: 1249
//

package Header

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/pschlump/Go-FTL/server/cfg"
	"github.com/pschlump/Go-FTL/server/goftlmux"
	"github.com/pschlump/Go-FTL/server/lib"
	"github.com/pschlump/Go-FTL/server/mid"
	"github.com/pschlump/Go-FTL/server/tr"
)

// -----------------------------------------------------------------------------------------------------------------------------------------------
// test that heqaders get created.

func Test_HeaderServer(t *testing.T) {

	if !cfg.SetupRedisForTest("../test_redis.json") {
		return
	}

	tests := []struct {
		url          string
		hdr          []lib.NameValue
		expectedCode int
		expectedBody string
		expectedNHdr int
		expectedHdr  []lib.NameValue
	}{
		{
			"http://example.com/foo?abc=def",
			[]lib.NameValue{lib.NameValue{Name: "X-Test", Value: "A-Value"}},
			http.StatusOK,
			"Hello World  *four*  CallNo:1",
			2,
			[]lib.NameValue{lib.NameValue{Name: "X-Test2", Value: "A-Value2"}},
		},
		{
			"http://example.com/def",
			[]lib.NameValue{lib.NameValue{Name: "X-Test", Value: "A-Value"}},
			http.StatusOK,
			"Hello World  *four*  CallNo:2",
			1,
			[]lib.NameValue{},
		},
	}
	// bot := NewBotHandler()
	bot := mid.NewServer()
	// return &MidServer{Info: " *four* ", callNo: 1}
	// wr.Write([]byte(fmt.Sprintf("Hello World %s CallNo:%d", ms.Info, ms.callNo)))
	bot.Info = "Hello World  *four*  CallNo:%d"
	ms := NewHeaderServer(bot, []string{"/foo"}, "X-Test2", "A-Value2")
	var err error
	lib.SetupTestCreateDirs()

	for ii, test := range tests {

		rec := httptest.NewRecorder()

		wr := goftlmux.NewMidBuffer(rec, nil) // var wr http.ResponseWriter

		id := "test-01-StatusHandler"
		trx := tr.NewTrx(cfg.ServerGlobal.RedisPool)
		trx.TrxIdSeen(id, test.url, "GET")
		wr.RequestTrxId = id

		wr.G_Trx = trx

		// lib.SetupTestCreateHeaders(wr, test.hdr)

		var req *http.Request

		req, err = http.NewRequest("GET", test.url, nil)
		if err != nil {
			t.Fatalf("Test %d: Could not create HTTP request: %v", ii, err)
		}
		lib.SetupTestMimicReq(req, "example.com")
		if db1 {
			fmt.Printf("{\"req\":%s,\n\"wr\":%s}\n", lib.SVarI(req), lib.SVarI(wr))
		}
		lib.SetupRequestHeaders(req, test.hdr)

		ms.ServeHTTP(wr, req)

		// Tests to perform on wr - first
		if wr.Error != nil {
			t.Errorf("Error %2d, Invalid error : %s\n", ii, wr.Error)
		}

		wr.FinalFlush()

		// Tests to perform on final recorder data.
		if rec.Code != test.expectedCode {
			t.Errorf("Error %2d, Invalid status code: %d, expected %d\n", ii, wr.StatusCode, test.expectedCode)
		}
		b := string(rec.Body.Bytes())
		if b != test.expectedBody {
			t.Errorf("Error %d, Invalid body, got >%s< expected >%s<\n", ii, b, test.expectedBody)
		}

		h := rec.Header()
		if len(h) != test.expectedNHdr {
			t.Errorf("Error %d, Invalid header, got incorrect number of headers\n", ii)
			fmt.Printf("rec.Header=%s\n", lib.SVarI(rec.Header()))
		}
		for jj, vv := range test.expectedHdr {
			g := h.Get(vv.Name)
			if g != vv.Value {
				t.Errorf("Error %d/%d, Invalid header, got >%s:%s< expected >%s<\n", ii, jj, vv.Name, g, vv.Value)
			}
		}

	}

}

const db1 = false

/* vim: set noai ts=4 sw=4: */


text:
#import "TestVC.h"
#import "RumblefishMobileSDK/RumblefishMobileSDK.h"

@implementation TestVC

- (void)viewDidLoad {
    ((UIScrollView *)self.view.subviews[0]).contentSize = CGSizeMake(320, 480);
}

- (void)emailLinkClicked {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@", [@"info@rumblefish.com" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [@"Friendly Music Info" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [[UIApplication sharedApplication] openURL:url];
}

- (void)viewWillAppear:(BOOL)animated {
    // PLEASE SPECIFY A VALID public key and password. Contact developers@rumblefish.com for more info.
    [RFAPI rumbleWithEnvironment:RFAPIEnvSandbox
                       publicKey:@"sandbox"
                        password:@"sandbox"
                        callback:^ { button.enabled = TRUE; }];
}

- (IBAction)start {
    FriendlyMusic *friendlyMusic = [[FriendlyMusic alloc] init];
    [friendlyMusic setOptions:friendlyMusic.FMMOODMAP | friendlyMusic.FMOCCASION | friendlyMusic.FMEDITORSPICKS];
    [self.navigationController pushViewController:friendlyMusic animated:YES];
    [friendlyMusic release];
}

@end


text:
#ifndef _LINUX_RXRPC_TYPES_H
#define _LINUX_RXRPC_TYPES_H

#include <linux/types.h>
#include <linux/list.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/spinlock.h>
#include <asm/atomic.h>

typedef uint32_t	rxrpc_seq_t;	/* Rx message sequence number */
typedef uint32_t	rxrpc_serial_t;	/* Rx message serial number */
typedef __be32	rxrpc_seq_net_t; /* on-the-wire Rx message sequence number */
typedef __be32	rxrpc_serial_net_t; /* on-the-wire Rx message serial number */

struct rxrpc_call;
struct rxrpc_connection;
struct rxrpc_header;
struct rxrpc_message;
struct rxrpc_operation;
struct rxrpc_peer;
struct rxrpc_service;
typedef struct rxrpc_timer rxrpc_timer_t;
struct rxrpc_transport;

typedef void (*rxrpc_call_attn_func_t)(struct rxrpc_call *call);
typedef void (*rxrpc_call_error_func_t)(struct rxrpc_call *call);
typedef void (*rxrpc_call_aemap_func_t)(struct rxrpc_call *call);

#endif /* _LINUX_RXRPC_TYPES_H */


text: sudo yum install python-backports-ssl_match_hostname.noarch-3.4.0.2 -y


text:
package proton.inject.state;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ FIELD })
@Retention(RUNTIME)
public @interface RetainState {
}


text:
 package com.indeed.lsmtree.recordcache;

import com.indeed.util.io.VIntUtils;
import com.indeed.util.serialization.Serializer;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import org.apache.log4j.Logger;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;

/**
 * @author jplaisance
 */
public final class DeltaEncodedIntegerCollectionSerializer implements Serializer<Collection<Integer>> {

    private static final Logger log = Logger.getLogger(DeltaEncodedIntegerCollectionSerializer.class);

    @Override
    public void write(final Collection<Integer> integers, final DataOutput out) throws IOException {
        out.writeInt(integers.size());
        int previous = 0;
        for (int i : integers) {
            final int delta = i-previous;
            VIntUtils.writeVInt(out, delta);
            previous = i;
        }
    }

    @Override
    public Collection<Integer> read(final DataInput in) throws IOException {
        final int length = in.readInt();
        IntArrayList ret = new IntArrayList(length);
        int previous = 0;
        for (int i = 0; i < length; i++) {
            final int delta = VIntUtils.readVInt(in);
            final int id = previous+delta;
            previous = id;
            ret.add(id);
        }
        return ret;
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const appolo = require("appolo");
const router_1 = require("../routes/router");
const app_1 = require("../app/app");
const view_1 = require("../app/view");
const path = require("path");
const http = require("http");
const https = require("https");
const fs = require("fs");
const Q = require("bluebird");
const _ = require("lodash");
class Launcher extends appolo.Launcher {
    constructor() {
        super(...arguments);
        this.Defaults = {
            startMessage: "Appolo Server listening on port: ${port} version:${version} environment: ${environment}",
            startServer: true,
            errorStack: false,
            errorMessage: true,
            maxRouteCache: 10000,
            qsParser: "qs",
            urlParser: "fast",
            viewExt: "html",
            viewEngine: null,
            viewFolder: "server/views",
            validatorOptions: {
                abortEarly: false,
                allowUnknown: true,
                stripUnknown: true
            }
        };
    }
    async launch(config, callback) {
        try {
            appolo.inject.addObject('appolo', require("../../index"));
            this._options = this.loadOptions(config);
            super.loadEnvironments();
            this.createServer();
            this.bindProcessEvents();
            await super.loadModules();
            super.loadFiles();
            super.loadInjector();
            this.setPort();
            this.loadCustomConfigurations();
            router_1.default.initialize(null, this._options.validatorOptions);
            app_1.default.initialize(this._options);
            view_1.default.initialize(this._options);
            await super.loadBootStrap();
            await this._startServer();
            callback && callback(null, app_1.default);
            this.fireEvent('appolo-launched');
            return app_1.default;
        }
        catch (e) {
            if (!callback) {
                throw e;
            }
            callback(e);
        }
    }
    get options() {
        return this._options;
    }
    loadOptions(config) {
        let dto = super.loadOptions(config);
        return _.merge(this.Defaults, dto || {});
    }
    bindProcessEvents() {
        process.on('uncaughtException', (err) => {
            if (err.code !== 'EADDRINUSE') {
                console.error(err.stack || err.toString());
                return;
            }
            console.error(`EADDRINUSE!!!! address in use port: ${this._port}`);
            process.exit(1);
        });
    }
    createServer() {
        let server;
        let ssl = this._options.ssl || appolo.environment.ssl;
        if (ssl && ssl.key && ssl.cert) {
            let options = {
                key: fs.readFileSync(ssl.key),
                cert: fs.readFileSync(ssl.cert)
            };
            server = https.createServer(options, (req, res) => app_1.default.handleRequest(req, res));
        }
        else {
            server = http.createServer((req, res) => app_1.default.handleRequest(req, res));
        }
        this._server = server;
        appolo.inject.addObject('app', app_1.default);
        appolo.inject.addObject('injector', appolo.inject);
        appolo.inject.addObject('router', router_1.default);
        appolo.inject.addObject('httpServer', server);
    }
    setPort() {
        this._port = process.env.APP_PORT || process.env.PORT || this._options.port || appolo.environment.port || 8080;
    }
    loadCustomConfigurations() {
        let allPath = path.join(this._options.root, 'config/express/all.js'), environmentPath = path.join(this._options.root, 'config/express/', this._options.environment + '.js');
        _.forEach([allPath, environmentPath], (filePath) => {
            if (!fs.existsSync(filePath)) {
                return;
            }
            this.cachedRequire.push(filePath);
            let func = require(filePath);
            let args = appolo.Util.getFunctionArgs(func);
            let dependencies = _.map(args, (arg) => appolo.inject.getObject(arg));
            func.apply(func, dependencies);
        });
    }
    async _startServer() {
        if (!this._options.startServer) {
            return;
        }
        return this.startServer();
    }
    async startServer() {
        await Q.fromCallback((callback) => this._server.listen(this._port, callback));
        let msg = _.template(this._options.startMessage, { interpolate: /\${([\s\S]+?)}/g })({
            port: this._port,
            version: appolo.environment.version,
            environment: appolo.environment.type
        });
        console.log(msg);
        this.fireEvent('appolo-server-started');
    }
    get app() {
        return app_1.default;
    }
    handleRequest(req, res) {
        app_1.default.handleRequest(req, res);
    }
    get server() {
        return this._server;
    }
    get port() {
        return this._port;
    }
    reset(isSoftReset) {
        super.reset(isSoftReset);
        if (!isSoftReset) {
            _.forEach(this.cachedRequire, (filePath) => delete require.cache[filePath]);
            router_1.default.reset();
        }
        this.cachedRequire.length = 0;
        this._options = null;
        try {
            this._server.close();
        }
        catch (e) {
            console.log("failed to close server", e);
        }
        process.removeAllListeners();
    }
    softReset() {
        this.reset(true);
    }
}
exports.Launcher = Launcher;
exports.default = new Launcher();
//# sourceMappingURL=launcher.js.map


text:
require 'spec_helper'

describe Brewby::Steps::DSL::Step do
  before do
    @outputs = [
      { adapter: :test, name: :hlt, pin: 3 },
      { adapter: :test, name: :mlt, pin: 2 },
      { adapter: :test, name: :bk, pin: 1 }
    ]

    @inputs = [
      { adapter: :test, name: :bk },
      { adapter: :test, name: :mlt },
      { adapter: :test, name: :hlt }
    ]

    @application = Brewby::Application.new outputs: @outputs, inputs: @inputs
    @step = Brewby::Steps::DSL::Step.new 'Test Step', @application
  end

  it 'accepts a type' do
    @step.type :temp_control
    expect(@step.step_class).to be Brewby::Steps::TempControl
  end

  it 'accepts options on the type' do
    @step.type :temp_control, mode: :auto, target: 155.0, duration: 60
    expect(@step.options[:mode]).to eql :auto
    expect(@step.options[:target]).to eql 155.0
    expect(@step.options[:duration]).to eql 60
  end

  it 'accepts a mode' do
    @step.mode :manual
    expect(@step.options[:mode]).to eql :manual
  end

  it 'accepts a target' do
    @step.target 155.0
    expect(@step.options[:target]).to eql 155.0
  end

  context 'creation' do
    before do
      @step.type :temp_control, mode: :manual, power_level: 1.0
      @step.input :mlt
      @step.output :bk
      @created_step = @step.create!
    end

    it 'should translate the input correctly' do
      expect(@created_step.input.name).to eql :mlt
    end

    it 'should translate the output correctly' do
      expect(@created_step.output.name).to eql :bk
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Payment_status extends CUSTOMER_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->model('customer_model');
    $this->load->model('login_model');
    $this->load->model('payments_model');
  }

  public function index(){
    $user_row = $this->login_model->get_row('users', 'user_id', $this->session->userdata('user_id'));
    $customer_row = $this->customer_model->get_row('customers', 'customer_id', $this->session->userdata('customer_id'));  /* Method in parent model class */
    $payment_row = $this->payments_model->get_row('payments', 'payment_id', $this->session->userdata('payment_id'));
    $this->load->view('templates/header');
    /* If there is a card error, a code is provided. This can be checked against this array to provide specific details */
    $card_error_codes = array(
      'invalid_number',
      'invalid_expiry_month',
      'invalid_expiry_year',
      'invalid_cvc',
      'invalid_swipe_data',
      'incorrect_number',
      'expired_card',
      'incorrect_cvc',
      'incorrect_zip'
    );
    /* Payment Error Handling */
    $error = $this->session->userdata();

    if ($error['success'] == false){
      $error['heading'] = "Unable to process your request";
      /* Card Errors */
      if ($error['type'] == 'card_error'){
        /* Generic Decline */
        if (($error['code'] == 'card_declined') && ($error['decline_code'] != 'fraudulent')){
          $error['partial'] = $this->load->view('templates/generic_decline', '', true);
        }
        /* Decline with fraudulent reason */
        else if (($error['code'] == 'card_declined') && ($error['decline_code'] == 'fraudulent')){
          $error['partial'] = $this->load->view('templates/fraudulent', '', true);
        }
        /* Other possible user related card errors */
        else if (in_array($error['code'], $card_error_codes)){
          $error['partial'] = $this->load->view('templates/generic_decline', '', true);
        }
        /* Any other card errors */
        else{
          $error['partial'] = $this->load->view('templates/other_decline', '', true);
        }
      }
      else if (($error['type'] == 'authentication_error') || ($error['type'] == 'invalid_request_error')){
        log_message('error', 'Payment Error -> Code: '.$error['code'].', Message: '.$error['message']);
        /*
         * Errors that are likely to be system related - eg. Invalid parameters, invalid API key
         */
        $this->load->library('email');
        /* WHen there are multiple users, details will need to be pulled from DB */
        $this -> email
              ->from('james@jkamradcliffe.net', 'VMS Secure Payments')
              ->to($user_row->user_email)
              ->subject('Payment Error')
              ->message("Dear ".$user_row->user_first_name.",\r\n\r\nMessage: ".$error['message']."\r\n\r\nPlease ensure your account details are correct.");
        $this->email->send();
        $error['partial'] = $this->load->view('templates/non_card_error', '', true);
      }
      else{
        /*
         * For any other error, display a generic message
         * Log the error
         */
        log_message('error', 'Payment Error -> Code: '.$error['code'].', Message: '.$error['message']);
        $error['partial'] = $this->load->view('templates/non_card_error', '', true);
      }
      /* Afford customer opportunity to retry payment */
      $error['retry'] = "Click HERE or use your browser's back button to try again.";
      $error['exit'] = "To exit without completing your payment, click HERE.";
      $this->load->view('payment_status', $error);
    }
    else{
      $charge = $this->session->userdata();

      $charge['heading'] = "Your payment was successful.";
      $charge['message'] = null;
      $payment_details = array('amount'=>($charge['amount_due']/100), 'email'=>$charge['email'], 'reference'=>$charge['reference'] );
      $charge['partial'] = $this->load->view('templates/payment_successful', $payment_details, true);
      $charge['code'] = null;
      $charge['retry'] = null;
      $charge['exit'] = null;
      $this->load->view('payment_status', $charge);

      /* Notification of successful payment for User */
      $this->load->library('email');
      /* WHen there are multiple users, details will need to be pulled from DB */
      $this -> email
            ->from('james@jkamradcliffe.net', 'VMS Secure Payments')
            ->to($user_row->user_email)
            ->subject('Payment Received')
            ->message("Dear ".$user_row->user_first_name.",\r\n\r\nYou've received a payment from ".$customer_row->customer_forename." ".$customer_row->customer_surname."\r\n\r\nReference: ".$payment_row->reference);
      $this->email->send();
/*
 * Preferred method of notifying customer of successful payment will be Stripe email receipt.
 *
 * This needs to be configured when a charge is created in Payment_form controller.
 * This can only be done in live mode
 */

//      $this -> email
//            ->from('james@jkamradcliffe.net', 'VMS')
//            ->to($payment_details['email'])
//            ->subject('Payment Successful')
//            ->message('Dear Fred, You\'re payment has been successful');
//      $this->email->send();
    }

    $this->load->view('templates/footer');
  }

  public function non_payment(){
    $user_row = $this->login_model->get_row('users', 'user_id', $this->session->userdata('user_id'));
    $customer_row = $this->customer_model->get_row('customers', 'customer_id', $this->session->userdata('customer_id'));  /* Method in parent model class */
    $payment_row = $this->payments_model->get_row('payments', 'payment_id', $this->session->userdata('payment_id'));
    /* Notification of non-payment for User */
    $this->load->library('email');
    /* WHen there are multiple users, details will need to be pulled from DB */
    $this -> email
          ->from('james@jkamradcliffe.net', 'VMS Secure Payments')
          ->to($user_row->user_email)
          ->subject('Notification of non-payment')
          ->message("Dear ".$user_row->user_first_name.",\r\n\r\nThe following payment has not been completed: \r\n\r\nCustomer ID: ".$customer_row->customer_id."\r\nName: ".$customer_row->customer_forename." ".$customer_row->customer_surname."\r\nEmail: ".$customer_row->email."\r\nPayment Ref: ".$payment_row->reference."\r\n\r\nYou may need to contact this customer to arrange alternative payment." );
    $this->email->send();
    header('Location: https://jkamradcliffe.net/vmssecurepay');
  }
}

?>


text:
package com.openDams.relations.configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.DocumentException;
import org.springframework.web.context.ServletContextAware;
import org.xml.sax.SAXException;

import com.openDams.configuration.ConfigurationException;
import com.openDams.configuration.ConfigurationXMLReader;

public class ConfigurationReader implements ServletContextAware{
	private ServletContext servletContext;
	private ArrayList<Object> elements_list = null;
	private Map<String,Element> elements_map = null;
	private RelationsConfiguration relationsConfiguration ;
	public ConfigurationReader() throws FileNotFoundException, DocumentException{
     }
    public void loadElementsList() throws ConfigurationException {
    	try {
    		if(elements_list==null){
	    		ConfigurationXMLReader configurationXMLReader = null;
	    		String path="";
				if(!relationsConfiguration.isUse_external_conf_location()){
					path+=servletContext.getRealPath("");
				}
				path+=relationsConfiguration.getConfiguration_location()+"/"+relationsConfiguration.getFile_name();
				File fileConf = new File(path);
		    	configurationXMLReader  = new ConfigurationXMLReader(new FileInputStream(fileConf),Element.class,true);
		    	elements_list = configurationXMLReader.getObjects();
    		}
  		} catch (ParserConfigurationException e) {
  			e.printStackTrace();
  		} catch (SAXException e) {
  			e.printStackTrace();
  		} catch (IOException e) {
  			e.printStackTrace();
  		} catch (SecurityException e) {
  			e.printStackTrace();
  		} catch (IllegalArgumentException e) {
  			e.printStackTrace();
  		} catch (ClassNotFoundException e) {
  			e.printStackTrace();
  		} catch (NoSuchMethodException e) {
  			e.printStackTrace();
  		} catch (InstantiationException e) {
  			e.printStackTrace();
  		} catch (IllegalAccessException e) {
  			e.printStackTrace();
  		} catch (InvocationTargetException e) {
  			e.printStackTrace();
  		} catch (NullPointerException e) {
  			e.printStackTrace();
  		}
 	}
    public void loadElements_map() throws ConfigurationException {
    	if(elements_map==null){
    		loadElementsList();
    		elements_map = new HashMap<String, Element>();
			for (int i = 0; i < elements_list.size(); i++) {
				Element element = (Element)elements_list.get(i);
				elements_map.put(element.getId_relation()+"_"+element.getGet_from()+"_"+element.getInsert_to(), element);
			}
    	}
	}
    public Element getElement(int ref_id_relation_type,int ref_id_archive_from,int ref_id_archive_to) throws ConfigurationException{
    	if(elements_map==null){
    		loadElements_map();
    	}
    	System.out.println("ConfigurationReader.getElement() "+ref_id_relation_type+"_"+ref_id_archive_from+"_"+ref_id_archive_to);
    	return elements_map.get(ref_id_relation_type+"_"+ref_id_archive_from+"_"+ref_id_archive_to);
    }
    public void setServletContext(ServletContext arg0) {
 		servletContext = arg0;
 	}
	public ServletContext getServletContext() {
		return servletContext;
	}
	public RelationsConfiguration getRelationsConfiguration() {
		return relationsConfiguration;
	}
	public void setRelationsConfiguration(
			RelationsConfiguration relationsConfiguration) {
		this.relationsConfiguration = relationsConfiguration;
	}

}


text:
/*  THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 */

using System;
using GLib;
using Gtk;
using Tasque;

namespace Gtk.Extras
{
	public class DateButton : ToggleButton
	{
		private Window popup;
		private DateTime date;
		private Calendar cal;
		private bool show_time;

		private const uint CURRENT_TIME = 0;

		// FIXME: If this is ever moved to its own library
		// this reference to Tomboy will obviously have to
		// be removed.
		public DateButton(DateTime date_time, bool show_time)
: base(Utilities.GetPrettyPrintDate (date_time, show_time))
		{
			Toggled += OnToggled;
			popup = null;
			date = date_time;
			this.show_time = show_time;
		}

		private void ShowCalendar()
		{
			popup = new Window(WindowType.Popup);
			popup.Screen = this.Screen;

			Frame frame = new Frame();
			frame.Shadow = ShadowType.Out;
			frame.Show();

			popup.Add(frame);

			VBox box = new VBox(false, 0);
			box.Show();
			frame.Add(box);

			cal = new Calendar();
			cal.DisplayOptions = CalendarDisplayOptions.ShowHeading
			                     | CalendarDisplayOptions.ShowDayNames
			                     | CalendarDisplayOptions.ShowWeekNumbers;

			cal.KeyPressEvent += OnCalendarKeyPressed;
			popup.ButtonPressEvent += OnButtonPressed;

			cal.Show();

			Alignment calAlignment = new Alignment(0.0f, 0.0f, 1.0f, 1.0f);
			calAlignment.Show();
			calAlignment.SetPadding(4, 4, 4, 4);
			calAlignment.Add(cal);

			box.PackStart(calAlignment, false, false, 0);

			Requisition req = SizeRequest();
			int x = 0, y = 0;
			GdkWindow.GetOrigin(out x, out y);
			popup.Move(x + Allocation.X, y + Allocation.Y + req.Height + 3);
			popup.Show();
			popup.GrabFocus();

			Grab.Add(popup);

			Gdk.GrabStatus grabbed = Gdk.Pointer.Grab(popup.GdkWindow, true,
			                         Gdk.EventMask.ButtonPressMask
			                         | Gdk.EventMask.ButtonReleaseMask
			                         | Gdk.EventMask.PointerMotionMask, null, null, CURRENT_TIME);

			if (grabbed == Gdk.GrabStatus.Success) {
				grabbed = Gdk.Keyboard.Grab(popup.GdkWindow,
				                            true, CURRENT_TIME);

				if (grabbed != Gdk.GrabStatus.Success) {
					Grab.Remove(popup);
					popup.Destroy();
					popup = null;
				}
			} else {
				Grab.Remove(popup);
				popup.Destroy();
				popup = null;
			}

			cal.DaySelectedDoubleClick += OnCalendarDaySelected;
			cal.ButtonPressEvent += OnCalendarButtonPressed;

			cal.Date = date;
		}

		public void HideCalendar(bool update)
		{
			if (popup != null) {
				Grab.Remove(popup);
				Gdk.Pointer.Ungrab(CURRENT_TIME);
				Gdk.Keyboard.Ungrab(CURRENT_TIME);

				popup.Destroy();
				popup = null;
			}

			if (update) {
				date = cal.GetDate();
				// FIXME: If this is ever moved to its own library
				// this reference to Tomboy will obviously have to
				// be removed.
				Label = Utilities.GetPrettyPrintDate (date, show_time);
			}

			Active = false;
		}

		private void OnToggled(object o, EventArgs args)
		{
			if (Active) {
				ShowCalendar();
			} else {
				HideCalendar(false);
			}
		}

		private void OnButtonPressed(object o, ButtonPressEventArgs args)
		{
			if (popup != null)
				HideCalendar(false);
		}

		private void OnCalendarDaySelected(object o, EventArgs args)
		{
			HideCalendar(true);
		}

		private void OnCalendarButtonPressed(object o,
		                                     ButtonPressEventArgs args)
		{
			args.RetVal = true;
		}

		private void OnCalendarKeyPressed(object o, KeyPressEventArgs args)
		{
			switch (args.Event.Key) {
			case Gdk.Key.Escape:
				HideCalendar(false);
				break;
			case Gdk.Key.KP_Enter:
			case Gdk.Key.ISO_Enter:
			case Gdk.Key.Key_3270_Enter:
			case Gdk.Key.Return:
			case Gdk.Key.space:
			case Gdk.Key.KP_Space:
				HideCalendar(true);
				break;
			default:
				break;
			}
		}

		public DateTime Date
		{
			get {
				return date;
			}
			set {
				date = value;
				Label = Utilities.GetPrettyPrintDate (date, show_time);
			}
		}

		/// <summary>
		/// If true, both the date and time will be shown.  If false, the time
		/// will be omitted.
		/// </summary>
		public bool ShowTime
		{
			get {
				return show_time;
			}
			set {
				show_time = value;
			}
		}
	}
}