text:
package pump_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	pumpTest "github.com/tidepool-org/platform/data/types/settings/pump/test"

	dataBloodGlucoseTest "github.com/tidepool-org/platform/data/blood/glucose/test"
	dataNormalizer "github.com/tidepool-org/platform/data/normalizer"
	"github.com/tidepool-org/platform/data/types/settings/pump"
	dataTypesTest "github.com/tidepool-org/platform/data/types/test"
	errorsTest "github.com/tidepool-org/platform/errors/test"
	"github.com/tidepool-org/platform/pointer"
	"github.com/tidepool-org/platform/structure"
	structureValidator "github.com/tidepool-org/platform/structure/validator"
)

var _ = Describe("InsulinSensitivityStart", func() {
	It("InsulinSensitivityStartStartMaximum is expected", func() {
		Expect(pump.InsulinSensitivityStartStartMaximum).To(Equal(86400000))
	})

	It("InsulinSensitivityStartStartMinimum is expected", func() {
		Expect(pump.InsulinSensitivityStartStartMinimum).To(Equal(0))
	})

	Context("ParseInsulinSensitivityStart", func() {
		// TODO
	})

	Context("NewInsulinSensitivityStart", func() {
		It("is successful", func() {
			Expect(pump.NewInsulinSensitivityStart()).To(Equal(&pump.InsulinSensitivityStart{}))
		})
	})

	Context("InsulinSensitivityStart", func() {
		Context("Parse", func() {
			// TODO
		})

		Context("Validate", func() {
			DescribeTable("validates the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectedErrors ...error) {
					datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum)
					mutator(datum, units)
					dataTypesTest.ValidateWithExpectedOrigins(pumpTest.NewValidatableWithUnitsAndStartMinimumAdapter(datum, units, pointer.FromInt(pump.InsulinSensitivityStartStartMinimum)), structure.Origins(), expectedErrors...)
				},
				Entry("succeeds",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
				),
				Entry("units missing; amount missing",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units missing; amount out of range (lower)",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
				),
				Entry("units missing; amount in range (lower)",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units missing; amount in range (upper)",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.0) },
				),
				Entry("units missing; amount out of range (upper)",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.1) },
				),
				Entry("units invalid; amount missing",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units invalid; amount out of range (lower)",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
				),
				Entry("units invalid; amount in range (lower)",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units invalid; amount in range (upper)",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.0) },
				),
				Entry("units invalid; amount out of range (upper)",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.1) },
				),
				Entry("units mmol/L; amount missing",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units mmol/L; amount out of range (lower)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(-0.1, 0.0, 55.0), "/amount"),
				),
				Entry("units mmol/L; amount in range (lower)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units mmol/L; amount in range (upper)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(55.0) },
				),
				Entry("units mmol/L; amount out of range (upper)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(55.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(55.1, 0.0, 55.0), "/amount"),
				),
				Entry("units mmol/l; amount missing",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units mmol/l; amount out of range (lower)",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(-0.1, 0.0, 55.0), "/amount"),
				),
				Entry("units mmol/l; amount in range (lower)",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units mmol/l; amount in range (upper)",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(55.0) },
				),
				Entry("units mmol/l; amount out of range (upper)",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(55.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(55.1, 0.0, 55.0), "/amount"),
				),
				Entry("units mg/dL; amount missing",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units mg/dL; amount out of range (lower)",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(-0.1, 0.0, 1000.0), "/amount"),
				),
				Entry("units mg/dL; amount in range (lower)",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units mg/dL; amount in range (upper)",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.0) },
				),
				Entry("units mg/dL; amount out of range (upper)",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(1000.1, 0.0, 1000.0), "/amount"),
				),
				Entry("units mg/dl; amount missing",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
				),
				Entry("units mg/dl; amount out of range (lower)",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(-0.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(-0.1, 0.0, 1000.0), "/amount"),
				),
				Entry("units mg/dl; amount in range (lower)",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(0.0) },
				),
				Entry("units mg/dl; amount in range (upper)",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.0) },
				),
				Entry("units mg/dl; amount out of range (upper)",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Amount = pointer.FromFloat64(1000.1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(1000.1, 0.0, 1000.0), "/amount"),
				),
				Entry("start missing",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/start"),
				),
				Entry("multiple errors",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) {
						datum.Amount = nil
						datum.Start = nil
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/amount"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/start"),
				),
			)

			DescribeTable("validates the datum with minimum start",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectedErrors ...error) {
					datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum)
					mutator(datum, units)
					dataTypesTest.ValidateWithExpectedOrigins(pumpTest.NewValidatableWithUnitsAndStartMinimumAdapter(datum, units, pointer.FromInt(pump.InsulinSensitivityStartStartMinimum)), structure.Origins(), expectedErrors...)
				},
				Entry("start out of range (lower)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(-1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotEqualTo(-1, 0), "/start"),
				),
				Entry("start in range",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(0) },
				),
				Entry("start out of range (upper)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(1) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotEqualTo(1, 0), "/start"),
				),
			)

			DescribeTable("validates the datum with non-minimum start",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectedErrors ...error) {
					datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum+1)
					mutator(datum, units)
					dataTypesTest.ValidateWithExpectedOrigins(pumpTest.NewValidatableWithUnitsAndStartMinimumAdapter(datum, units, pointer.FromInt(pump.InsulinSensitivityStartStartMinimum+1)), structure.Origins(), expectedErrors...)
				},
				Entry("start out of range (lower)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(0) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(0, 1, 86400000), "/start"),
				),
				Entry("start in range (lower)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(1) },
				),
				Entry("start in range (upper)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(86400000) },
				),
				Entry("start out of range (upper)",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = pointer.FromInt(86400001) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(86400001, 1, 86400000), "/start"),
				),
			)
		})

		Context("Normalize", func() {
			DescribeTable("normalizes the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectator func(datum *pump.InsulinSensitivityStart, expectedDatum *pump.InsulinSensitivityStart, units *string)) {
					for _, origin := range structure.Origins() {
						datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum+1)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStart(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units missing",
					nil,
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units invalid",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; start missing",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) { datum.Start = nil },
					nil,
				),
			)

			DescribeTable("normalizes the datum with origin external",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectator func(datum *pump.InsulinSensitivityStart, expectedDatum *pump.InsulinSensitivityStart, units *string)) {
					datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum+1)
					mutator(datum, units)
					expectedDatum := pumpTest.CloneInsulinSensitivityStart(datum)
					normalizer := dataNormalizer.New()
					Expect(normalizer).ToNot(BeNil())
					datum.Normalize(normalizer.WithOrigin(structure.OriginExternal), units)
					Expect(normalizer.Error()).To(BeNil())
					Expect(normalizer.Data()).To(BeEmpty())
					if expectator != nil {
						expectator(datum, expectedDatum, units)
					}
					Expect(datum).To(Equal(expectedDatum))
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("modifies the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					func(datum *pump.InsulinSensitivityStart, expectedDatum *pump.InsulinSensitivityStart, units *string) {
						dataBloodGlucoseTest.ExpectNormalizedValue(datum.Amount, expectedDatum.Amount, units)
					},
				),
				Entry("modifies the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					func(datum *pump.InsulinSensitivityStart, expectedDatum *pump.InsulinSensitivityStart, units *string) {
						dataBloodGlucoseTest.ExpectNormalizedValue(datum.Amount, expectedDatum.Amount, units)
					},
				),
			)

			DescribeTable("normalizes the datum with origin internal/store",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStart, units *string), expectator func(datum *pump.InsulinSensitivityStart, expectedDatum *pump.InsulinSensitivityStart, units *string)) {
					for _, origin := range []structure.Origin{structure.OriginInternal, structure.OriginStore} {
						datum := pumpTest.NewInsulinSensitivityStart(units, pump.InsulinSensitivityStartStartMinimum+1)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStart(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStart, units *string) {},
					nil,
				),
			)
		})
	})

	Context("ParseInsulinSensitivityStartArray", func() {
		// TODO
	})

	Context("NewInsulinSensitivityStartArray", func() {
		It("is successful", func() {
			Expect(pump.NewInsulinSensitivityStartArray()).To(Equal(&pump.InsulinSensitivityStartArray{}))
		})
	})

	Context("InsulinSensitivityStartArray", func() {
		Context("Parse", func() {
			// TODO
		})

		Context("Validate", func() {
			DescribeTable("validates the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArray, units *string), expectedErrors ...error) {
					datum := pump.NewInsulinSensitivityStartArray()
					mutator(datum, units)
					dataTypesTest.ValidateWithExpectedOrigins(structureValidator.NewValidatableWithStringAdapter(datum, units), structure.Origins(), expectedErrors...)
				},
				Entry("succeeds",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
				),
				Entry("empty",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						*datum = *pump.NewInsulinSensitivityStartArray()
					},
				),
				Entry("nil",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) { *datum = append(*datum, nil) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/0"),
				),
				Entry("single invalid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						invalid := pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), pump.InsulinSensitivityStartStartMinimum)
						invalid.Amount = nil
						*datum = append(*datum, invalid)
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/0/amount"),
				),
				Entry("single valid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), pump.InsulinSensitivityStartStartMinimum))
					},
				),
				Entry("multiple invalid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), pump.InsulinSensitivityStartStartMinimum))
						invalid := pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), *datum.Last().Start+1)
						invalid.Amount = nil
						*datum = append(*datum, invalid)
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), *datum.Last().Start+1))
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/1/amount"),
				),
				Entry("multiple valid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), pump.InsulinSensitivityStartStartMinimum))
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), *datum.Last().Start+1))
						*datum = append(*datum, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), *datum.Last().Start+1))
					},
				),
				Entry("multiple errors",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {
						invalid := pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), pump.InsulinSensitivityStartStartMinimum)
						invalid.Amount = nil
						*datum = append(*datum, nil, invalid)
						*datum = append(*datum, nil, pumpTest.NewInsulinSensitivityStart(pointer.FromString("mmol/L"), *datum.Last().Start+1))
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/0"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/1/amount"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/2"),
				),
			)
		})

		Context("Normalize", func() {
			DescribeTable("normalizes the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArray, units *string), expectator func(datum *pump.InsulinSensitivityStartArray, expectedDatum *pump.InsulinSensitivityStartArray, units *string)) {
					for _, origin := range structure.Origins() {
						datum := pumpTest.NewInsulinSensitivityStartArray(units)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStartArray(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units missing",
					nil,
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units invalid",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; start missing",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) { (*datum)[0].Start = nil },
					nil,
				),
			)

			DescribeTable("normalizes the datum with origin external",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArray, units *string), expectator func(datum *pump.InsulinSensitivityStartArray, expectedDatum *pump.InsulinSensitivityStartArray, units *string)) {
					datum := pumpTest.NewInsulinSensitivityStartArray(units)
					mutator(datum, units)
					expectedDatum := pumpTest.CloneInsulinSensitivityStartArray(datum)
					normalizer := dataNormalizer.New()
					Expect(normalizer).ToNot(BeNil())
					datum.Normalize(normalizer.WithOrigin(structure.OriginExternal), units)
					Expect(normalizer.Error()).To(BeNil())
					Expect(normalizer.Data()).To(BeEmpty())
					if expectator != nil {
						expectator(datum, expectedDatum, units)
					}
					Expect(datum).To(Equal(expectedDatum))
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("modifies the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					func(datum *pump.InsulinSensitivityStartArray, expectedDatum *pump.InsulinSensitivityStartArray, units *string) {
						for index := range *datum {
							dataBloodGlucoseTest.ExpectNormalizedValue((*datum)[index].Amount, (*expectedDatum)[index].Amount, units)
						}
					},
				),
				Entry("modifies the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					func(datum *pump.InsulinSensitivityStartArray, expectedDatum *pump.InsulinSensitivityStartArray, units *string) {
						for index := range *datum {
							dataBloodGlucoseTest.ExpectNormalizedValue((*datum)[index].Amount, (*expectedDatum)[index].Amount, units)
						}
					},
				),
			)

			DescribeTable("normalizes the datum with origin internal/store",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArray, units *string), expectator func(datum *pump.InsulinSensitivityStartArray, expectedDatum *pump.InsulinSensitivityStartArray, units *string)) {
					for _, origin := range []structure.Origin{structure.OriginInternal, structure.OriginStore} {
						datum := pumpTest.NewInsulinSensitivityStartArray(units)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStartArray(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStartArray, units *string) {},
					nil,
				),
			)
		})
	})

	Context("ParseInsulinSensitivityStartArrayMap", func() {
		// TODO
	})

	Context("NewInsulinSensitivityStartArrayMap", func() {
		It("is successful", func() {
			Expect(pump.NewInsulinSensitivityStartArrayMap()).To(Equal(&pump.InsulinSensitivityStartArrayMap{}))
		})
	})

	Context("InsulinSensitivityStartArrayMap", func() {
		Context("Parse", func() {
			// TODO
		})

		Context("Validate", func() {
			DescribeTable("validates the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArrayMap, units *string), expectedErrors ...error) {
					datum := pump.NewInsulinSensitivityStartArrayMap()
					mutator(datum, units)
					dataTypesTest.ValidateWithExpectedOrigins(structureValidator.NewValidatableWithStringAdapter(datum, units), structure.Origins(), expectedErrors...)
				},
				Entry("succeeds",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
				),
				Entry("empty",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						*datum = *pump.NewInsulinSensitivityStartArrayMap()
					},
				),
				Entry("empty name",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						datum.Set("", pumpTest.NewInsulinSensitivityStartArray(units))
					},
				),
				Entry("nil value",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) { datum.Set("", nil) },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/"),
				),
				Entry("single invalid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						invalid := pumpTest.NewInsulinSensitivityStartArray(units)
						(*invalid)[0].Start = nil
						datum.Set("one", invalid)
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/one/0/start"),
				),
				Entry("single valid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						datum.Set("one", pumpTest.NewInsulinSensitivityStartArray(units))
					},
				),
				Entry("multiple invalid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						invalid := pumpTest.NewInsulinSensitivityStartArray(units)
						(*invalid)[0].Start = nil
						datum.Set("one", pumpTest.NewInsulinSensitivityStartArray(units))
						datum.Set("two", invalid)
						datum.Set("three", pumpTest.NewInsulinSensitivityStartArray(units))
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/two/0/start"),
				),
				Entry("multiple valid",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						datum.Set("one", pumpTest.NewInsulinSensitivityStartArray(units))
						datum.Set("two", pumpTest.NewInsulinSensitivityStartArray(units))
						datum.Set("three", pumpTest.NewInsulinSensitivityStartArray(units))
					},
				),
				Entry("multiple errors",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						invalid := pumpTest.NewInsulinSensitivityStartArray(units)
						(*invalid)[0].Start = nil
						datum.Set("one", nil)
						datum.Set("two", invalid)
						datum.Set("three", pumpTest.NewInsulinSensitivityStartArray(units))
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/one"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/two/0/start"),
				),
			)
		})

		Context("Normalize", func() {
			DescribeTable("normalizes the datum",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArrayMap, units *string), expectator func(datum *pump.InsulinSensitivityStartArrayMap, expectedDatum *pump.InsulinSensitivityStartArrayMap, units *string)) {
					for _, origin := range structure.Origins() {
						datum := pumpTest.NewInsulinSensitivityStartArrayMap(units)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStartArrayMap(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units missing",
					nil,
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units invalid",
					pointer.FromString("invalid"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("does not modify the datum; start missing",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {
						for name := range *datum {
							(*(*datum)[name])[0].Start = nil
						}
					},
					nil,
				),
			)

			DescribeTable("normalizes the datum with structure external",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArrayMap, units *string), expectator func(datum *pump.InsulinSensitivityStartArrayMap, expectedDatum *pump.InsulinSensitivityStartArrayMap, units *string)) {
					datum := pumpTest.NewInsulinSensitivityStartArrayMap(units)
					mutator(datum, units)
					expectedDatum := pumpTest.CloneInsulinSensitivityStartArrayMap(datum)
					normalizer := dataNormalizer.New()
					Expect(normalizer).ToNot(BeNil())
					datum.Normalize(normalizer.WithOrigin(structure.OriginExternal), units)
					Expect(normalizer.Error()).To(BeNil())
					Expect(normalizer.Data()).To(BeEmpty())
					if expectator != nil {
						expectator(datum, expectedDatum, units)
					}
					Expect(datum).To(Equal(expectedDatum))
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("modifies the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					func(datum *pump.InsulinSensitivityStartArrayMap, expectedDatum *pump.InsulinSensitivityStartArrayMap, units *string) {
						for name := range *datum {
							for index := range *(*datum)[name] {
								dataBloodGlucoseTest.ExpectNormalizedValue((*(*datum)[name])[index].Amount, (*(*expectedDatum)[name])[index].Amount, units)
							}
						}
					},
				),
				Entry("modifies the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					func(datum *pump.InsulinSensitivityStartArrayMap, expectedDatum *pump.InsulinSensitivityStartArrayMap, units *string) {
						for name := range *datum {
							for index := range *(*datum)[name] {
								dataBloodGlucoseTest.ExpectNormalizedValue((*(*datum)[name])[index].Amount, (*(*expectedDatum)[name])[index].Amount, units)
							}
						}
					},
				),
			)

			DescribeTable("normalizes the datum with origin internal/store",
				func(units *string, mutator func(datum *pump.InsulinSensitivityStartArrayMap, units *string), expectator func(datum *pump.InsulinSensitivityStartArrayMap, expectedDatum *pump.InsulinSensitivityStartArrayMap, units *string)) {
					for _, origin := range []structure.Origin{structure.OriginInternal, structure.OriginStore} {
						datum := pumpTest.NewInsulinSensitivityStartArrayMap(units)
						mutator(datum, units)
						expectedDatum := pumpTest.CloneInsulinSensitivityStartArrayMap(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin), units)
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						if expectator != nil {
							expectator(datum, expectedDatum, units)
						}
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum; units mmol/L",
					pointer.FromString("mmol/L"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("does not modify the datum; units mmol/l",
					pointer.FromString("mmol/l"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("modifies the datum; units mg/dL",
					pointer.FromString("mg/dL"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
				Entry("modifies the datum; units mg/dl",
					pointer.FromString("mg/dl"),
					func(datum *pump.InsulinSensitivityStartArrayMap, units *string) {},
					nil,
				),
			)
		})
	})
})


text:
package net.floodlightcontroller.devicemanager;

import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;

import net.floodlightcontroller.core.FloodlightContextStore;
import net.floodlightcontroller.core.module.IFloodlightService;

/**
 * Device manager allows interacting with devices on the network.  Note
 * that under normal circumstances, {@link Device} objects should be retrieved
 * from the {@link FloodlightContext} rather than from {@link IDeviceManager}.
 */
public interface IDeviceService extends IFloodlightService {
    /**
     * Fields used in devices for indexes and querying
     * @see IDeviceService#addIndex
     */
    enum DeviceField {
        MAC, IPV4, VLAN, SWITCH, PORT
    }

    /**
     * The source device for the current packet-in, if applicable.
     */
    public static final String CONTEXT_SRC_DEVICE =
            "net.floodlightcontroller.devicemanager.srcDevice";

    /**
     * The destination device for the current packet-in, if applicable.
     */
    public static final String CONTEXT_DST_DEVICE =
            "net.floodlightcontroller.devicemanager.dstDevice";

    /**
     * A FloodlightContextStore object that can be used to interact with the
     * FloodlightContext information created by BVS manager.
     */
    public static final FloodlightContextStore<IDevice> fcStore =
        new FloodlightContextStore<IDevice>();

    /**
     * Get the device with the given device key.
     *
     * @param deviceKey the key to search for
     * @return the device associated with the key, or null if no such device
     * @see IDevice#getDeviceKey()
     */
    public IDevice getDevice(Long deviceKey);

    /**
     * Search for a device using exactly matching the provided device fields.
     * Only the key fields as defined by the {@link IEntityClassifier} will
     * be important in this search.
     *
     * @param macAddress The MAC address
     * @param vlan the VLAN
     * @param ipv4Address the ipv4 address
     * @param switchDPID the switch DPID
     * @param switchPort the switch port
     * @return an {@link IDevice} or null if no device is found.
     * @see IDeviceManager#setEntityClassifier(IEntityClassifier)
     */
    public IDevice findDevice(long macAddress, Short vlan,
                              Integer ipv4Address, Long switchDPID,
                              Integer switchPort);

    /**
     * Get a destination device using entity fields that corresponds with
     * the given source device.  The source device is important since
     * there could be ambiguity in the destination device without the
     * attachment point information.
     *
     * @param source the source device.  The returned destination will be
     * in the same entity class as the source.
     * @param macAddress The MAC address for the destination
     * @param vlan the VLAN if available
     * @param ipv4Address The IP address if available.
     * @return an {@link IDevice} or null if no device is found.
     * @see IDeviceService#findDevice(long, Short, Integer, Long,
     * Integer)
     */
    public IDevice findDestDevice(IDevice source,
                                  long macAddress, Short vlan,
                                  Integer ipv4Address);

    /**
     * Get an unmodifiable collection view over all devices currently known.
     * @return the collection of all devices
     */
    public Collection<? extends IDevice> getAllDevices();

    /**
     * Create an index over a set of fields.  This allows efficient lookup
     * of devices when querying using the indexed set of specified fields.
     * The index must be registered before any device learning takes place,
     * or it may be incomplete.  It's OK if this is called multiple times with
     * the same fields; only one index will be created for each unique set of
     * fields.
     *
     * @param perClass set to true if the index should be maintained for each
     * entity class separately.
     * @param keyFields the set of fields on which to index
     */
    public void addIndex(boolean perClass,
                         EnumSet<DeviceField> keyFields);

    /**
     * Find devices that match the provided query.  Any fields that are
     * null will not be included in the query.  If there is an index for
     * the query, then it will be performed efficiently using the index.
     * Otherwise, there will be a full scan of the device list.
     *
     * @param macAddress The MAC address
     * @param vlan the VLAN
     * @param ipv4Address the ipv4 address
     * @param switchDPID the switch DPID
     * @param switchPort the switch port
     * @return an iterator over a set of devices matching the query
     * @see IDeviceService#queryClassDevices(IEntityClass, Long,
     * Short, Integer, Long, Integer)
     */
    public Iterator<? extends IDevice> queryDevices(Long macAddress,
                                                    Short vlan,
                                                    Integer ipv4Address,
                                                    Long switchDPID,
                                                    Integer switchPort);

    /**
     * Find devices that match the provided query.  Only the index for
     * the class of the specified reference device will be searched.
     * Any fields that are null will not be included in the query.  If
     * there is an index for the query, then it will be performed
     * efficiently using the index. Otherwise, there will be a full scan
     * of the device list.
     *
     * @param reference The reference device to refer to when finding
     * entity classes.
     * @param macAddress The MAC address
     * @param vlan the VLAN
     * @param ipv4Address the ipv4 address
     * @param switchDPID the switch DPID
     * @param switchPort the switch port
    * @return an iterator over a set of devices matching the query
     * @see IDeviceService#queryClassDevices(Long,
     * Short, Integer, Long, Integer)
     */
    public Iterator<? extends IDevice> queryClassDevices(IDevice reference,
                                                         Long macAddress,
                                                         Short vlan,
                                                         Integer ipv4Address,
                                                         Long switchDPID,
                                                         Integer switchPort);

    /**
     * Adds a listener to listen for IDeviceManagerServices notifications
     *
     * @param listener The listener that wants the notifications
     */
    public void addListener(IDeviceListener listener);

    /**
     * Set the entity classifier for the device manager to use to
     * differentiate devices on the network.  If no classifier is set,
     * the {@link DefaultEntityClassifer} will be used.  This should be
     * registered in the application initialization phase before startup.
     *
     * @param classifier the classifier to set.
     */
    public void setEntityClassifier(IEntityClassifier classifier);

    /**
     * Flush and/or reclassify all entities in a class
     *
     * @param entityClass the class to flush.  If null, flush all classes
     * @param reclassify if true, begin an asynchronous task to reclassify the
     * flushed entities
     */
    public void flushEntityCache(IEntityClass entityClass,
                                 boolean reclassify);

    /**
     * Specify points in the network where attachment points are not to
     * be learned.
     * @param sw
     * @param port
     */
	public void addSuppressAPs(long swId, short port);

	public void removeSuppressAPs(long swId, short port);

}

redpajama_set_name: RedPajamaGithub


text:
module Motion
  module Util
    VERSION = "0.2.0"
  end
end


text:
cask 'sonora' do
  version :latest
  sha256 :no_check

  # github.com is the official download host per the vendor homepage
  url 'https://github.com/downloads/sonoramac/Sonora/Sonora.zip'
  appcast 'https://getsonora.com/updates/sonora2.xml',
          :sha256 => '961a6fecdddf1f5e1dba7360a697a09781d202b61bc48369240bcef226f7f441'
  name 'Sonora'
  homepage 'https://getsonora.com/'
  license :gratis

  app 'Sonora.app'
end


text:
package main

import (
	"fmt"
	"github.com/docopt/docopt-go"
	compute "github.com/go-compute/mean/pkg"
	"os"
)

const usage = `
Usage:
	mean <file>
	mean -h | --help

Options:
	-h, --help 	  	output help information

`

func check(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	// Parse input arguments:
	args, err := docopt.Parse(usage, nil, true, ``, false)
	check(err)

	// Open the input file:
	path := args["<file>"].(string)
	file, err := os.Open(path)
	check(err)

	defer file.Close()

	// Read each line of the file and store in a data array...
	var (
		value float64
		n     int
		data  []float64
	)
	for {
		n, err = fmt.Fscanln(file, &value)
		if n == 0 || err != nil {
			break
		}
		data = append(data, value)
	}

	// Compute the mean:
	mu := compute.Mean(data)

	// Output to stdout:
	fmt.Println("Mean: ", mu)
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'solidus_image_multi_upload'

require 'minitest/autorun'


text:
package com.example.aditya.notesproject;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import static android.R.id.message;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private Button register;
    private Button tvLogin;
    private EditText Regemail, Regpassword;
    private DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        db = new DbHelper(this);
        register = (Button) findViewById(R.id.RegisterButton1);
        tvLogin = (Button) findViewById(R.id.backToLogin);
        Regemail = (EditText) findViewById(R.id.RegEmail);
        Regpassword = (EditText) findViewById(R.id.RegPass);

        register.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.RegisterButton1:
                register();
                break;
            case R.id.backToLogin:
                startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                finish();
                break;
            default:

        }

    }

    private void register() {
        String email = Regemail.getText().toString();
        String pass = Regpassword.getText().toString();
        if(email.isEmpty() && pass.isEmpty()){
            Toast.makeText(getApplicationContext(), "Username/password field empty", Toast.LENGTH_LONG).show();
        }
        else {
            db.addUser(email,pass);
            Toast.makeText(getApplicationContext(), "User Registered", Toast.LENGTH_LONG).show();
            finish();
        }
    }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.Net.Http.Headers;

public class ContentRangeHeaderValueTest
{
    [Fact]
    public void Ctor_LengthOnlyOverloadUseInvalidValues_Throw()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(-1));
    }

    [Fact]
    public void Ctor_LengthOnlyOverloadValidValues_ValuesCorrectlySet()
    {
        var range = new ContentRangeHeaderValue(5);

        Assert.False(range.HasRange, "HasRange");
        Assert.True(range.HasLength, "HasLength");
        Assert.Equal("bytes", range.Unit);
        Assert.Null(range.From);
        Assert.Null(range.To);
        Assert.Equal(5, range.Length);
    }

    [Fact]
    public void Ctor_FromAndToOverloadUseInvalidValues_Throw()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(-1, 1));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(0, -1));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(2, 1));
    }

    [Fact]
    public void Ctor_FromAndToOverloadValidValues_ValuesCorrectlySet()
    {
        var range = new ContentRangeHeaderValue(0, 1);

        Assert.True(range.HasRange, "HasRange");
        Assert.False(range.HasLength, "HasLength");
        Assert.Equal("bytes", range.Unit);
        Assert.Equal(0, range.From);
        Assert.Equal(1, range.To);
        Assert.Null(range.Length);
    }

    [Fact]
    public void Ctor_FromToAndLengthOverloadUseInvalidValues_Throw()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(-1, 1, 2));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(0, -1, 2));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(0, 1, -1));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(2, 1, 3));
        Assert.Throws<ArgumentOutOfRangeException>(() => new ContentRangeHeaderValue(1, 2, 1));
    }

    [Fact]
    public void Ctor_FromToAndLengthOverloadValidValues_ValuesCorrectlySet()
    {
        var range = new ContentRangeHeaderValue(0, 1, 2);

        Assert.True(range.HasRange, "HasRange");
        Assert.True(range.HasLength, "HasLength");
        Assert.Equal("bytes", range.Unit);
        Assert.Equal(0, range.From);
        Assert.Equal(1, range.To);
        Assert.Equal(2, range.Length);
    }

    [Fact]
    public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation()
    {
        var range = new ContentRangeHeaderValue(0);
        range.Unit = "myunit";
        Assert.Equal("myunit", range.Unit);

        Assert.Throws<ArgumentException>(() => range.Unit = null);
        Assert.Throws<ArgumentException>(() => range.Unit = "");
        Assert.Throws<FormatException>(() => range.Unit = " x");
        Assert.Throws<FormatException>(() => range.Unit = "x ");
        Assert.Throws<FormatException>(() => range.Unit = "x y");
    }

    [Fact]
    public void ToString_UseDifferentRanges_AllSerializedCorrectly()
    {
        var range = new ContentRangeHeaderValue(1, 2, 3);
        range.Unit = "myunit";
        Assert.Equal("myunit 1-2/3", range.ToString());

        range = new ContentRangeHeaderValue(123456789012345678, 123456789012345679);
        Assert.Equal("bytes 123456789012345678-123456789012345679/*", range.ToString());

        range = new ContentRangeHeaderValue(150);
        Assert.Equal("bytes */150", range.ToString());
    }

    [Fact]
    public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes()
    {
        var range1 = new ContentRangeHeaderValue(1, 2, 5);
        var range2 = new ContentRangeHeaderValue(1, 2);
        var range3 = new ContentRangeHeaderValue(5);
        var range4 = new ContentRangeHeaderValue(1, 2, 5);
        range4.Unit = "BYTES";
        var range5 = new ContentRangeHeaderValue(1, 2, 5);
        range5.Unit = "myunit";

        Assert.NotEqual(range1.GetHashCode(), range2.GetHashCode());
        Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode());
        Assert.NotEqual(range2.GetHashCode(), range3.GetHashCode());
        Assert.Equal(range1.GetHashCode(), range4.GetHashCode());
        Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode());
    }

    [Fact]
    public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions()
    {
        var range1 = new ContentRangeHeaderValue(1, 2, 5);
        var range2 = new ContentRangeHeaderValue(1, 2);
        var range3 = new ContentRangeHeaderValue(5);
        var range4 = new ContentRangeHeaderValue(1, 2, 5);
        range4.Unit = "BYTES";
        var range5 = new ContentRangeHeaderValue(1, 2, 5);
        range5.Unit = "myunit";
        var range6 = new ContentRangeHeaderValue(1, 3, 5);
        var range7 = new ContentRangeHeaderValue(2, 2, 5);
        var range8 = new ContentRangeHeaderValue(1, 2, 6);

        Assert.False(range1.Equals(null), "bytes 1-2/5 vs. <null>");
        Assert.False(range1!.Equals(range2), "bytes 1-2/5 vs. bytes 1-2/*");
        Assert.False(range1.Equals(range3), "bytes 1-2/5 vs. bytes */5");
        Assert.False(range2.Equals(range3), "bytes 1-2/* vs. bytes */5");
        Assert.True(range1.Equals(range4), "bytes 1-2/5 vs. BYTES 1-2/5");
        Assert.True(range4.Equals(range1), "BYTES 1-2/5 vs. bytes 1-2/5");
        Assert.False(range1.Equals(range5), "bytes 1-2/5 vs. myunit 1-2/5");
        Assert.False(range1.Equals(range6), "bytes 1-2/5 vs. bytes 1-3/5");
        Assert.False(range1.Equals(range7), "bytes 1-2/5 vs. bytes 2-2/5");
        Assert.False(range1.Equals(range8), "bytes 1-2/5 vs. bytes 1-2/6");
    }

    [Fact]
    public void Parse_SetOfValidValueStrings_ParsedCorrectly()
    {
        CheckValidParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3));
        CheckValidParse("bytes  *  /  3", new ContentRangeHeaderValue(3));

        CheckValidParse(" custom 1234567890123456789-1234567890123456799/*",
            new ContentRangeHeaderValue(1234567890123456789, 1234567890123456799) { Unit = "custom" });

        CheckValidParse(" custom * / 123 ",
            new ContentRangeHeaderValue(123) { Unit = "custom" });

        // Note that we don't have a public constructor for value 'bytes */*' since the RFC doesn't mention a
        // scenario for it. However, if a server returns this value, we're flexible and accept it.
        var result = ContentRangeHeaderValue.Parse("bytes */*");
        Assert.Equal("bytes", result.Unit);
        Assert.Null(result.From);
        Assert.Null(result.To);
        Assert.Null(result.Length);
        Assert.False(result.HasRange, "HasRange");
        Assert.False(result.HasLength, "HasLength");
    }

    [Theory]
    [InlineData("bytes 1-2/3,")] // no character after 'length' allowed
    [InlineData("x bytes 1-2/3")]
    [InlineData("bytes 1-2/3.4")]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("bytes 3-2/5")]
    [InlineData("bytes 6-6/5")]
    [InlineData("bytes 1-6/5")]
    [InlineData("bytes 1-2/")]
    [InlineData("bytes 1-2")]
    [InlineData("bytes 1-/")]
    [InlineData("bytes 1-")]
    [InlineData("bytes 1")]
    [InlineData("bytes ")]
    [InlineData("bytes a-2/3")]
    [InlineData("bytes 1-b/3")]
    [InlineData("bytes 1-2/c")]
    [InlineData("bytes1-2/3")]
    // More than 19 digits >>Int64.MaxValue
    [InlineData("bytes 1-12345678901234567890/3")]
    [InlineData("bytes 12345678901234567890-3/3")]
    [InlineData("bytes 1-2/12345678901234567890")]
    // Exceed Int64.MaxValue, but use 19 digits
    [InlineData("bytes 1-9999999999999999999/3")]
    [InlineData("bytes 9999999999999999999-3/3")]
    [InlineData("bytes 1-2/9999999999999999999")]
    public void Parse_SetOfInvalidValueStrings_Throws(string? input)
    {
        Assert.Throws<FormatException>(() => ContentRangeHeaderValue.Parse(input));
    }

    [Fact]
    public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
    {
        CheckValidTryParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3));
        CheckValidTryParse("bytes  *  /  3", new ContentRangeHeaderValue(3));

        CheckValidTryParse(" custom 1234567890123456789-1234567890123456799/*",
            new ContentRangeHeaderValue(1234567890123456789, 1234567890123456799) { Unit = "custom" });

        CheckValidTryParse(" custom * / 123 ",
            new ContentRangeHeaderValue(123) { Unit = "custom" });

        // Note that we don't have a public constructor for value 'bytes */*' since the RFC doesn't mention a
        // scenario for it. However, if a server returns this value, we're flexible and accept it.
        Assert.True(ContentRangeHeaderValue.TryParse("bytes */*", out var result));
        Assert.Equal("bytes", result.Unit);
        Assert.Null(result.From);
        Assert.Null(result.To);
        Assert.Null(result.Length);
        Assert.False(result.HasRange, "HasRange");
        Assert.False(result.HasLength, "HasLength");
    }

    [Theory]
    [InlineData("bytes 1-2/3,")] // no character after 'length' allowed
    [InlineData("x bytes 1-2/3")]
    [InlineData("bytes 1-2/3.4")]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("bytes 3-2/5")]
    [InlineData("bytes 6-6/5")]
    [InlineData("bytes 1-6/5")]
    [InlineData("bytes 1-2/")]
    [InlineData("bytes 1-2")]
    [InlineData("bytes 1-/")]
    [InlineData("bytes 1-")]
    [InlineData("bytes 1")]
    [InlineData("bytes ")]
    [InlineData("bytes a-2/3")]
    [InlineData("bytes 1-b/3")]
    [InlineData("bytes 1-2/c")]
    [InlineData("bytes1-2/3")]
    // More than 19 digits >>Int64.MaxValue
    [InlineData("bytes 1-12345678901234567890/3")]
    [InlineData("bytes 12345678901234567890-3/3")]
    [InlineData("bytes 1-2/12345678901234567890")]
    // Exceed Int64.MaxValue, but use 19 digits
    [InlineData("bytes 1-9999999999999999999/3")]
    [InlineData("bytes 9999999999999999999-3/3")]
    [InlineData("bytes 1-2/9999999999999999999")]
    public void TryParse_SetOfInvalidValueStrings_ReturnsFalse(string? input)
    {
        Assert.False(ContentRangeHeaderValue.TryParse(input, out var result));
        Assert.Null(result);
    }

    private void CheckValidParse(string? input, ContentRangeHeaderValue expectedResult)
    {
        var result = ContentRangeHeaderValue.Parse(input);
        Assert.Equal(expectedResult, result);
    }

    private void CheckValidTryParse(string? input, ContentRangeHeaderValue expectedResult)
    {
        Assert.True(ContentRangeHeaderValue.TryParse(input, out var result));
        Assert.Equal(expectedResult, result);
    }
}


text:
'use strict';

angular.module('myCityApp').controller('CityCtrl',
    function($scope, localAreaServices) {

    $scope.localareas = {};
    $scope.localareas = localAreaServices.getLocalAreaList();

});


text:
import { WebAppCreateStack } from '../models/available-stacks';
import { CommonConstants } from '../utils/CommonConstants';
import Url from '../utils/url';
import { sendHttpRequest } from './HttpClient';
import { HttpResponseObject } from '../ArmHelper.types';
import { AppOsType } from '../models/site/site';
import { WebAppStack } from '../models/stacks/web-app-stacks';
import { FunctionAppStack } from '../models/stacks/function-app-stacks';
import { AppStackOs } from '../models/stacks/app-stacks';

export default class RuntimeStackService {
  public static getWebAppConfigurationStacks = (stacksOs: AppStackOs) => {
    return sendHttpRequest<WebAppStack[]>({
      url: `${Url.serviceHost}stacks/webAppStacks?os=${stacksOs}&api-version=${CommonConstants.ApiVersions.stacksApiVersion20200601}`,
      method: 'GET',
    }).then(result => {
      const success = result.metadata.success && !!result.data;
      const mappedResult: HttpResponseObject<WebAppStack[]> = {
        ...result,
        metadata: {
          ...result.metadata,
          success,
        },
        data: success ? result.data : [],
      };
      return mappedResult;
    });
  };

  public static getFunctionAppConfigurationStacks = (stacksOs: AppStackOs) => {
    return sendHttpRequest<FunctionAppStack[]>({
      url: `${Url.serviceHost}stacks/functionAppStacks?os=${stacksOs}&api-version=${CommonConstants.ApiVersions.stacksApiVersion20200601}`,
      method: 'GET',
    }).then(result => {
      const success = result.metadata.success && !!result.data;
      const mappedResult: HttpResponseObject<FunctionAppStack[]> = {
        ...result,
        metadata: {
          ...result.metadata,
          success,
        },
        data: success ? result.data : [],
      };
      return mappedResult;
    });
  };

  public static getWebAppGitHubActionStacks = (stacksOs: AppOsType) => {
    return sendHttpRequest<WebAppCreateStack[]>({
      url: `${Url.serviceHost}stacks/webAppGitHubActionStacks?os=${stacksOs}&api-version=${
        CommonConstants.ApiVersions.stacksApiVersion20200501
      }`,
      method: 'POST',
    });
  };
}


text:
<?php

namespace Acme\FamilyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ParentageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('type')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\FamilyBundle\Entity\Parentage'
        ));
    }

    public function getName()
    {
        return 'acme_familybundle_parentagetype';
    }
}


text:
package org.jetbrains.plugins.scala.lang.scaladoc.psi.impl

import java.util

import com.intellij.psi.impl.source.tree.LazyParseablePsiElement
import com.intellij.psi.javadoc.PsiDocTag
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.tree.IElementType
import com.intellij.psi._
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement
import org.jetbrains.plugins.scala.lang.psi.api.ScalaElementVisitor
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScClass
import org.jetbrains.plugins.scala.lang.scaladoc.lexer.ScalaDocTokenType
import org.jetbrains.plugins.scala.lang.scaladoc.parser.ScalaDocElementTypes
import org.jetbrains.plugins.scala.lang.scaladoc.psi.api.{ScDocComment, ScDocTag}

import scala.collection.mutable

/**
 * User: Alexander Podkhalyuzin
 * Date: 22.07.2008
 */

class ScDocCommentImpl(text: CharSequence) extends LazyParseablePsiElement(ScalaDocElementTypes.SCALA_DOC_COMMENT, text) with ScDocComment {
  def version: Int = {
    val firstLineIsEmpty = getNode.getChildren(null).lift(2).exists(
      _.getElementType == ScalaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS)

    if (firstLineIsEmpty) 1 else 2
  }

  def getOwner: PsiDocCommentOwner = getParent match {
    case owner: PsiDocCommentOwner if owner.getDocComment eq this => owner
    case _ => null
  }

  override def processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement,
                                   place: PsiElement): Boolean = {
    super.processDeclarations(processor, state, lastParent, place) && !Option(getOwner).exists {
      case owner: ScClass =>
        owner.members.exists {
          case named: PsiNamedElement => !processor.execute(named, state)
          case _ => false
        }
      case _ => false
    }
  }

  def getTokenType: IElementType = ScalaDocElementTypes.SCALA_DOC_COMMENT

  override def toString: String = "DocComment"

  //todo: implement me
  def getTags: Array[PsiDocTag] = findTagsByName(_ => true)

  def getDescriptionElements: Array[PsiElement] = PsiElement.EMPTY_ARRAY

  def findTagByName(name: String): PsiDocTag = if (findTagsByName(name).length > 0) findTagsByName(name)(0) else null

  def findTagsByName(name: String): Array[PsiDocTag] = findTagsByName(a => a == name)

  def findTagsByName(filter: String => Boolean): Array[PsiDocTag] = {
    var currentChild = getFirstChild
    val answer = mutable.ArrayBuilder.make[PsiDocTag]()

    while (currentChild != null && currentChild.getNode.getElementType != ScalaDocTokenType.DOC_COMMENT_END) {
      currentChild match {
        case docTag: ScDocTag if docTag.getNode.getElementType == ScalaDocElementTypes.DOC_TAG  &&
          filter(docTag.name) => answer += currentChild.asInstanceOf[PsiDocTag]
        case _ =>

      }
      currentChild = currentChild.getNextSibling
    }

    answer.result()
  }

  protected def findChildrenByClassScala[T >: Null <: ScalaPsiElement](aClass: Class[T]): Array[T] = {
    val result: util.List[T] = new util.ArrayList[T]
    var cur: PsiElement = getFirstChild
    while (cur != null) {
      if (aClass.isInstance(cur)) result.add(cur.asInstanceOf[T])
      cur = cur.getNextSibling
    }
    result.toArray[T](java.lang.reflect.Array.newInstance(aClass, result.size).asInstanceOf[Array[T]])
  }

  protected def findChildByClassScala[T >: Null <: ScalaPsiElement](aClass: Class[T]): T = {
    var cur: PsiElement = getFirstChild
    while (cur != null) {
      if (aClass.isInstance(cur)) return cur.asInstanceOf[T]
      cur = cur.getNextSibling
    }
    null
  }

  override def accept(visitor: ScalaElementVisitor) {
    visitor.visitDocComment(this)
  }

  override def accept(visitor: PsiElementVisitor) {
    visitor match {
      case s: ScalaElementVisitor => accept(s)
      case _ => super.accept(visitor)
    }
  }
}


text:
layout: page
title: Frequent Answers & Questions
share: true
---

## FAQ

### Why can't you delete projects from within CSIDE?
CSIDE doesn't use physical project files. Rather, it creates and stores project information on the fly, with data derived from your files. The closest we could get to allowing deletion of a project is the deletion of a folder, which is a very dangerous thing to allow from within the application.

<hr>

### Can I use CSIDE alongside application x, y and/or z?
Of course! CSIDE in practice, as far as file editing is concerned at least, is nothing more than another snazzy text editor. You can use it as much or as little as you like, by itself or in conjuction with any other application you might fancy.


text:
class GURL;

namespace extensions {

class Extension;

// Represents a single feature accessible to an extension developer, such as a
// top-level manifest key, a permission, or a programmatic API. A feature can
// express requirements for where it can be accessed, and supports testing
// support for those requirements. If platforms are not specified, then feature
// is available on all platforms.
class Feature {
 public:
  // The JavaScript contexts the feature is supported in.
  enum Context {
    UNSPECIFIED_CONTEXT,

    // A context in a privileged extension process.
    BLESSED_EXTENSION_CONTEXT,

    // A context in an unprivileged extension process.
    UNBLESSED_EXTENSION_CONTEXT,

    // A context from a content script.
    CONTENT_SCRIPT_CONTEXT,

    // A normal web page. This should have an associated URL matching pattern.
    WEB_PAGE_CONTEXT,
  };

  // The location required of extensions the feature is supported in.
  enum Location {
    UNSPECIFIED_LOCATION,
    COMPONENT_LOCATION
  };

  // The platforms the feature is supported in.
  enum Platform {
    UNSPECIFIED_PLATFORM,
    CHROMEOS_PLATFORM,
    LINUX_PLATFORM,
    MACOSX_PLATFORM,
    WIN_PLATFORM
  };

  // Whether a feature is available in a given situation or not, and if not,
  // why not.
  enum AvailabilityResult {
    IS_AVAILABLE,
    NOT_FOUND_IN_WHITELIST,
    INVALID_URL,
    INVALID_TYPE,
    INVALID_CONTEXT,
    INVALID_LOCATION,
    INVALID_PLATFORM,
    INVALID_MIN_MANIFEST_VERSION,
    INVALID_MAX_MANIFEST_VERSION,
    NOT_PRESENT,
    UNSUPPORTED_CHANNEL,
  };

  // Container for AvailabiltyResult that also exposes a user-visible error
  // message in cases where the feature is not available.
  class Availability {
   public:
    AvailabilityResult result() const { return result_; }
    bool is_available() const { return result_ == IS_AVAILABLE; }
    const std::string& message() const { return message_; }

   private:
    friend class SimpleFeature;
    friend class Feature;

    // Instances should be created via Feature::CreateAvailability.
    Availability(AvailabilityResult result, const std::string& message)
        : result_(result), message_(message) { }

    const AvailabilityResult result_;
    const std::string message_;
  };

  Feature();
  virtual ~Feature();

  // Used by ChromeV8Context until the feature system is fully functional.
  static Availability CreateAvailability(AvailabilityResult result,
                                         const std::string& message);

  const std::string& name() const { return name_; }
  void set_name(const std::string& name) { name_ = name; }
  const std::set<std::string>& dependencies() { return dependencies_; }
  bool no_parent() const { return no_parent_; }

  // Gets the platform the code is currently running on.
  static Platform GetCurrentPlatform();

  // Gets the Feature::Location value for the specified Manifest::Location.
  static Location ConvertLocation(Manifest::Location extension_location);

  virtual std::set<Context>* GetContexts() = 0;

  // Tests whether this is an internal API or not.
  virtual bool IsInternal() const = 0;

  // Returns true if the feature is available to be parsed into a new extension
  // manifest.
  Availability IsAvailableToManifest(const std::string& extension_id,
                                     Manifest::Type type,
                                     Location location,
                                     int manifest_version) const {
    return IsAvailableToManifest(extension_id, type, location, manifest_version,
                                 GetCurrentPlatform());
  }
  virtual Availability IsAvailableToManifest(const std::string& extension_id,
                                             Manifest::Type type,
                                             Location location,
                                             int manifest_version,
                                             Platform platform) const = 0;

  // Returns true if the feature is available to be used in the specified
  // extension and context.
  Availability IsAvailableToContext(const Extension* extension,
                                    Context context,
                                    const GURL& url) const {
    return IsAvailableToContext(extension, context, url, GetCurrentPlatform());
  }
  virtual Availability IsAvailableToContext(const Extension* extension,
                                            Context context,
                                            const GURL& url,
                                            Platform platform) const = 0;

  virtual std::string GetAvailabilityMessage(AvailabilityResult result,
                                             Manifest::Type type,
                                             const GURL& url,
                                             Context context) const = 0;

  virtual bool IsIdInWhitelist(const std::string& extension_id) const = 0;

 protected:
  std::string name_;
  std::set<std::string> dependencies_;
  bool no_parent_;
};

}  // namespace extensions

#endif  // EXTENSIONS_COMMON_FEATURES_FEATURE_H_


text:
/**
 * AMD global
 * A module that grabs the current global for multiple environments
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

/** @modue: amd-global */
define(typeof global !== 'undefined' ? global : self);


text:
<?php namespace Faddle;

use Faddle\View\ViewEngine as ViewEngine;
use Faddle\Helper\FileCache as StorageHelper;

/**
 * 视图类
 * @author KYO
 * @since 2015-9-21
 */
class View {
	protected static $config = array();
	public static $extends = array();
	private $data = array();
	private $path;
	private $engine;
	private $engine_config = array();
	public $cache = false;
	public $storage;

	public function __construct($config=array()) {
		if (! self::$config or empty(self::$config)) {
			self::$config = array();
			self::$config['default'] = array(
					'suffix'  => ['.view.php', '.faddle.php', '.tpl.html'],
					'template_path'  =>  '/views', //模板文件夹路径
					'storage_path'  =>  'cache', //模板文件夹缓存路径
					'bucket' => 'templates',
					'engine'  =>  'default', //模板引擎名称
					'expire'  =>  5000, //过期时间(秒)
			);
			self::$config['nature'] = array(
					'suffix'  => '.php',
					'template_path'  =>  '/views',
					'storage_path'  =>  'cache',
					'bucket' => 'templates',
					'engine'  =>  false,
					'expire'  =>  0,
			);
		}
		$config = (array) $config;
		$isdis = false; //判断是否是二维数组
		foreach($config as $c) {
			if (is_array($c)) $isdis = true;
			break;
		}
		if (! $isdis) $_config['engine'] = $config;
		else $_config = $config;
		self::$config = array_merge(self::$config, $_config);

		$this->storage = StorageHelper::make();

	}

	protected function init_engine($engine) {
		if (! is_array($engine)) {
			$this->engine = null;
			return;
		}
		$this->engine_config = $engine;
		$bucket = (array_key_exists('bucket', $engine)) ? $engine['bucket'] : 'views';
		if ($this->storage) $this->storage->with($bucket, false);
		if ($engine['engine']) {
			$this->engine = strtolower($engine['engine']);
		} else {
			$this->engine = null;
		}
	}

	public function __get($name) {
		return $this->data[$name];
	}

	public function __set($name, $value) {
		$this->data[$name] = $value;
	}

	public static function make($template, $data=array(), $config=array()) {
		$view = new self($config);

		return $view->show($template, $data);
	}

	public function show($template, $data=array()) {
		list($engine, $file) = $this->path($template, false);
		if ($engine) $engine = self::$config[$engine];
		else $engine = null;
		$this->init_engine($engine);

		$this->data = array_merge($this->data, $data);
		$data = $this->data;
		$this->path = $file;
		//echo $template; var_dump($this->path);

		if ($this->path == false) {
			if (starts_with($template, ['http:', 'https:'])) {
				$this->path = $template;
				return file_get_contents($template);
			}

			trigger_error(sprintf('模板加载出错:%s', $template), E_USER_WARNING);
			return false;
		}

		$cache = (array_key_exists('cache', $this->engine_config)) ? $this->engine_config['cache'] : $this->cache;
		if ($cache) {
			$compiled_path = $this->compiled();
			if ($this->path and ! $this->expired()) {
				$output = $this->storage->get($compiled_path);
				if (! empty($output)) return $output;
			}
		}

		if (in_array($this->engine, array('default', 'faddle', 'view'))) {
			$view = ViewEngine::make( $this->path, $data );
			$view->config($engine);

			$output = $view->render();

		} else if (in_array($this->engine, array('text', 'html'))) {
			if (is_file($this->path)) {
				$output = file_get_contents($this->path);
			} else {
				$output = false;
			}
		} else if (array_key_exists(strtolower($this->engine), self::$extends)) {
			$func = self::$extends[strtolower($this->engine)];
			try {
				$output = call_user_func_array($func, array($this->path, $data));
			} catch(\Exception $e) {
				$output = false;
			}

		} else if ($this->engine) {

			var_dump(self);

		} else {
			ob_start() and ob_clean();

			include ($this->path);

			$output = ob_get_clean();
		}

		if ($cache and $output) $this->storage->put($compiled_path, $output);
		return $output;
	}

	public function display($template, $date=array()) {
		$content = $this->show($template, $date);
		if ($content === false) {
			exit();
		} else {
			echo $content;
			@ob_flush();
		}
	}

	public function path($path, $rte=true) {
		$_path = trim($path, DIRECTORY_SEPARATOR);
		if (strpos($_path, 'path: ') == 0) {
			$file = substr($_path, 6);
			if (file_exists($file)) {
				if ($rte) return $file;
				else return ['default', $file];
			}
		}
		foreach (self::$config as $name => $config) {
			$suffix = (array_key_exists('suffix', $config)) ? $config['suffix'] : '';
			$template_path = (array_key_exists('template_path', $config)) ? $config['template_path'] : '';
			$suffixs = (array) $suffix;
			foreach ($suffixs as $suffix) {
				if (! empty($ext = pathinfo($_path, PATHINFO_EXTENSION))) {
					$ext = '.'.$ext;
					if (starts_with($suffix, $ext))
						$suffix = str_ireplace($ext, '', $suffix);
				}
				$file = $template_path . DIRECTORY_SEPARATOR . $_path . $suffix;
				if (file_exists($file)) {
					if ($rte) return $file;
					else return [$name, $file];
				}
			}
		}

		return false;

	}

	public function compiled($path=null) {
		$storage_path = (array_key_exists('storage_path', $this->engine_config)) ? $this->engine_config['storage_path'] : 'views';
		if (! is_null($path))
			return $storage_path.'/'.md5($path);
		else
			return $storage_path.'/'.md5($_SERVER['REQUEST_URI']);
	}

	public function expired($path=null) {
		$expire = (array_key_exists('expire', $this->engine_config)) ? $this->engine_config['expire'] : '0';
		$expire = intval($expire);
		$time = $this->storage->time($this->compiled($path));
		//echo "\n{$time} : {$expire} : ".time();
		if ($expire > 0) {
			if (! $time) return true;
			if ($time + $expire < time()) return true;
			else if (is_null($path)) return false;
		}
		if (is_null($path)) {
			if ($expire <= 0) return false;
			else return true;
		}
		$ftime = filemtime($path);
		//echo " : {$ftime}\n";
		return $ftime > $time;
	}

	public static function extend($name, \Closure $func) {
		if (empty($name))
			return false;
		if (!is_callable($func))
			return false;
		$name = strtolower($name);
		self::$extends[$name] = $func;
		return true;
	}

}


text:
<?php

namespace SmartWiki\Http\Middleware;

use Closure;
use Route;

/**
 * 拦截系统是否安装的中间件
 * Class InstallMiddleware
 * @package SmartWiki\Http\Middleware
 */
class InstallMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $path = public_path('install.lock');

        $uri = $request->getRequestUri();

        if(stripos($uri,'/install') === 0){
            if( file_exists($path)) {
                return redirect(route('member.projects'));
            }

        }elseif(file_exists($path) === false){

            $url = substr($request->getUri(),0,-strlen($uri)) . '/install.php';

            return redirect($url);
        }

        return $next($request);
    }
}


text:
<!DOCTYPE HTML>

    <title>Flask-SocketIO Test</title>

            Create game

© kpi.mosquito


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=2004/02/22/ie-navigation-just-got-better/index.html"><TITLE>Page has moved</TITLE>

Click here...


text:
environment="centos_guest,dev"

if [ "$#" -ge 1 ]; then
    environment=$1
fi

find . -name "*.sh" -exec chmod 755 {} \;

su docs -c "./scripts/deployAsUser.sh ${environment}"

sh ./autogen/addConfig.sh

echo "sleeping because of linking shenanigans."
sleep 2


text:
package com.proteus.peach.server

import java.util.concurrent.TimeUnit

import akka.actor.ActorSelection
import akka.pattern.ask
import akka.util.Timeout
import com.proteus.peach.common.comm.PeachServerMessage.Get
import com.proteus.peach.common.comm.PeachServerMessage.GetResponse
import com.proteus.peach.common.comm.PeachServerMessage.Invalidate
import com.proteus.peach.common.comm.PeachServerMessage.InvalidateAll
import com.proteus.peach.common.comm.PeachServerMessage.Put
import com.proteus.peach.common.comm.PeachServerMessage.Size
import com.proteus.peach.common.comm.PeachServerMessage.SizeResponse
import org.hamcrest.CoreMatchers
import org.junit.After
import org.junit.AfterClass
import org.junit.Assert
import org.junit.BeforeClass
import org.junit.Test

import scala.concurrent.Await
import scala.concurrent.duration.FiniteDuration

object PeachServerTest {
  /**
   * Server instance.
   */
  lazy val Server: PeachServer = new PeachServer()

  /**
   * Init cache server.
   */
  @BeforeClass
  def beforeAll(): Unit = {
    Server.init()
    Server.run()
  }

  /**
   * Stop cache server.
   */
  @AfterClass
  def afterAll(): Unit = {
    Server.shutdown()
  }
}

class PeachServerTest {
  /**
   * Selector of the comm actor.
   */
  val commActor: ActorSelection = PeachServerTest.Server.system.actorSelection("/user/comm")
  /**
   * Timeout duration.
   */
  val duration: FiniteDuration = FiniteDuration(1, TimeUnit.SECONDS)

  /**
   * Remove all the entries in the cache.
   */
  @After
  def invalidateCache(): Unit = {
    val invalidateFuture = commActor ? InvalidateAll()
    Await.result(invalidateFuture, this.duration)

    val sizeFuture = commActor ? Size()
    val sizeResponse = Await.result(sizeFuture, this.duration).asInstanceOf[SizeResponse]
    Assert.assertEquals("The size must be 0", 0L, sizeResponse.value)
  }

  /**
   * Implicit timeout val.
   */
  implicit val timeout = Timeout(duration)

  /**
   * Simple test put and get key.
   */
  @Test
  def basicTest(): Unit = {
    val key = "basicTestKey"
    val value = "basicTestValue"

    val putResponseFuture = commActor ? Put(key, value)
    val putResponse = Await.result(putResponseFuture, this.duration)

    val getResponseFuture = commActor ? Get(key)
    val getResponse = Await.result(getResponseFuture, this.duration)

    Assert.assertNotNull("ResponsePut must no be null", putResponse)
    Assert.assertNotNull("ResponseGet must no be null", getResponse)
    Assert.assertThat("Must be a ResponseGet", getResponse, CoreMatchers.instanceOf[Any](classOf[GetResponse]))
    Assert.assertTrue("Response value must be defined.", getResponse.asInstanceOf[GetResponse].value.isDefined)
    Assert.assertEquals("Response value must be [value]", getResponse.asInstanceOf[GetResponse].value.get, value)
  }

  /**
   * Ask for a key that does not exist.
   */
  @Test
  def notExistKeyTest(): Unit = {
    val key = "notExistKeyTestKey"
    val getResponseFuture = commActor ? Get(key)
    val getResponse = Await.result(getResponseFuture, this.duration)

    Assert.assertNotNull("ResponseGet must no be null", getResponse)
    Assert.assertThat("Must be a ResponseGet", getResponse, CoreMatchers.instanceOf[Any](classOf[GetResponse]))
    Assert.assertTrue("Response value must be empty.", getResponse.asInstanceOf[GetResponse].value.isEmpty)
  }

  /**
   * Ask for a key that does not exist.
   */
  @Test
  def createAndInvalidateTest(): Unit = {
    val key = "createAndInvalidateKey"
    val value = "createAndInvalidateValue"
    val putResponseFuture = commActor ? Put(key, value)
    val putResponse = Await.result(putResponseFuture, this.duration)

    val getResponseFuture = commActor ? Get(key)
    val getResponse = Await.result(getResponseFuture, this.duration)

    Assert.assertNotNull("ResponsePut must no be null", putResponse)
    Assert.assertNotNull("ResponseGet must no be null", getResponse)
    Assert.assertThat("Must be a ResponseGet", getResponse, CoreMatchers.instanceOf[Any](classOf[GetResponse]))
    Assert.assertTrue("Response value must be defined.", getResponse.asInstanceOf[GetResponse].value.isDefined)
    Assert.assertEquals("Response value must be [value]", getResponse.asInstanceOf[GetResponse].value.get, value)

    val invalidateFuture = commActor ? Invalidate(key)
    val invalidateResponse = Await.result(invalidateFuture, this.duration)

    Assert.assertNotNull("Invalidate Response must not be null", invalidateResponse)

    val getResponseFuture2 = commActor ? Get(key)
    val getResponse2 = Await.result(getResponseFuture2, this.duration)
    Assert.assertNotNull("ResponseGet must no be null", getResponse2)
    Assert.assertThat("Must be a ResponseGet", getResponse2, CoreMatchers.instanceOf[Any](classOf[GetResponse]))
    Assert.assertTrue("Response value must be empty.", getResponse2.asInstanceOf[GetResponse].value.isEmpty)

  }

}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Space Coast JS - Presentation 1 - Introduction to Modern JavaScript</title>

		<meta name="description" content="An introduction to modern JavaScript.">
		<meta name="author" content="Steven Hunt">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/default.css" id="theme">

		<link rel="stylesheet" href="css/presentation.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

ES6 Modules with Bower and GulpJS

by Steven Hunt

						Presented by

						Space Coast JS

						Meeting space provided by

						TrepHub

Welcome!

						Happy "Talk like a Pirate" day!

About Space Coast JS

						Space Coast JS is a community of software developers interested in discussing JavaScript-based technologies. We present information on a wide range of JavaScript-related topics at our meetings such as Node.js, development tools, best practices, etc.

About Steven

						I'm a software developer specializing in JavaScript, C#, and database systems. I've worked on everything from cutting-edge Node.js apps to NASA mainframes.

What is ES6?

							ES6, also called Harmony, is the next version of JavaScript which adds new syntax and functionality to the language.

What's new with ES6?

						Let's explore the new features...

## Block Level Scoping
Unlike other C-based languages, JavaScript scopes variables by function instead of by block. For example:

    function isAwesome(user) {
		if (user == "Steven") {
			var awesome = true;
		}
		return !!awesome;
	}

With ES6, you can use the `let` keyword to scope a variable to the block it is defined in.

	if (user == "Steven") {
		let awesome = true;
	}
	return !!awesome; // ReferenceError

## Default Parameters

Before ES6, if you wanted a default value for a function parameter you had to do this:

	function myFunction (myParam) {
		myParam = myParam || "default value";
	}

With ES6, now you can do this:

    function myFunction (myParam = "default value") {
    }

Unlike default parameter values in some other languages, there is no requirement that the value be a constant.

## Lambda Expressions

If you know C# syntax for lambdas, then you know this:

	$(() => {
		let data = [1,2,4,5,6,7,8,9];

		let multiplesOfTwo = _(data)
			.filter(i => i % 2 === 0);
	});

Something else about lambdas is that they bind the value of `this` to the parent function scope automatically, so no more `that` or `self` variables required! Example:

	function MyClass (val, wait) {
		setTimeout(() => {
			this.value = val; // NOT set to the window object :)
		}, wait);
	}

## The "Triple Dot" Operator

It has several uses in ES6:

+ The "Rest" operator
+ The "Spread" operator

## Rest Operator

Used as the last parameter of a function to capture the "rest" of the parameters:

    function myFunc (param1, ...theRest) {
        // code...
    }

Unlike the `arguments` value, the "rest" operator produces a true array instead of an "array-like" object.

## Spread Operator

Used as a language-defined version of `Function.apply`:

    function sumOfThree (val1, val2, val3) {
        return val1 + val2 + val3;
    }

    let result = sumOfThree(...[1, 2, 3]);

## Classes!

It's been a long time coming, but JavaScript is finally getting the `class` keyword! You could implement "classes" before and use JavaScript's prototype inheritance model, but it was difficult for programmers more used to langauges like Java.

## What does it look like?

    class Car extends MotorVehicle {

        constructor (options) {
            this.areHeadlightsOn = options.areHeadlightsOn;
            super(options);
        }

        start () {
            ...
        }

        drive () {
            ...
        }
    }

Breaking it down

First off, we have a syntax convention (a keyword even!) for constructors!

Also, we have a way of reliably calling the parent constructor with the super keyword!

Finally, we have a clean instance method syntax which is free of excessive commas.

## Generator Functions

This new feature of JavaScript allows you to write functions which return values before the function has completed. While it is intended for sequences, this can also be used to replace callbacks.

    function* powersOfTwo() {
        var i = 2;
        while (true) {
            yield i;
            i = i * 2;
        }
    }

    var pow = powersOfTwo();
    pow.next(); // 2
    pow.next(); // 4
    pow.next(); // 8
    pow.next(); // 16...

## Generator Functions - Continued

Notice how the code inside of `powersOfTwo` won't continue executing until the next() function is called against the generator object returned. This allows you to write functions which can "pause" and then "resume" based on the actions of the caller.

## When can I use ES6?
It depends...

You'll have to wait until at least 2015 to use it natively in a browser.

If you can't wait, you can use a transpiler like [Google's Traceur](https://github.com/google/traceur-compiler).

					# Live Demo

					+ ES6 modules and other features.
					+ Use it today!

Thanks for coming!

					Questions?
Comments?


text:
package com.gamecodeschool.c5platformgame;

public class RectHitbox {
    float top;
    float left;
    float bottom;
    float right;
    float height;

    boolean intersects(RectHitbox rectHitbox){
        boolean hit = false;

        if(this.right > rectHitbox.left
                && this.left < rectHitbox.right ){
            // Intersecting on x axis

            if(this.top < rectHitbox.bottom
                    && this.bottom > rectHitbox.top ){
                // Intersecting on y as well
                // Collision
                hit = true;
            }
        }

        return hit;
    }

    public void setTop(float top) {
        this.top = top;
    }

    public float getLeft() {
        return left;
    }

    public void setLeft(float left) {
        this.left = left;
    }

    public void setBottom(float bottom) {
        this.bottom = bottom;
    }

    public float getRight() {
        return right;
    }

    public void setRight(float right) {
        this.right = right;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }
}


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\KhidmatPerubatanDanSainsSukanAtlet;

/**
 * KhidmatPerubatanDanSainsSukanAtletSearch represents the model behind the search form about `app\models\KhidmatPerubatanDanSainsSukanAtlet`.
 */
class KhidmatPerubatanDanSainsSukanAtletSearch extends KhidmatPerubatanDanSainsSukanAtlet
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['khidmat_perubatan_dan_sains_sukan_atlet_id', 'khidmat_perubatan_dan_sains_sukan_id', 'program', 'sukan', 'atlet', 'created_by', 'updated_by'], 'integer'],
            [['session_id', 'created', 'updated'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = KhidmatPerubatanDanSainsSukanAtlet::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'khidmat_perubatan_dan_sains_sukan_atlet_id' => $this->khidmat_perubatan_dan_sains_sukan_atlet_id,
            'khidmat_perubatan_dan_sains_sukan_id' => $this->khidmat_perubatan_dan_sains_sukan_id,
            'program' => $this->program,
            'sukan' => $this->sukan,
            'atlet' => $this->atlet,
            'created_by' => $this->created_by,
            'updated_by' => $this->updated_by,
            'created' => $this->created,
            'updated' => $this->updated,
        ]);

        $query->andFilterWhere(['like', 'session_id', $this->session_id]);

        return $dataProvider;
    }
}


text:
/**
 * @author Dimitry Kudrayvtsev
 * @version 2.1
 */

d3.gantt = function() {
    var FIT_TIME_DOMAIN_MODE = "fit";
    var FIXED_TIME_DOMAIN_MODE = "fixed";

    var margin = {
	top : 20,
	right : 40,
	bottom : 20,
	left : 150
    };
    var timeDomainStart = d3.time.day.offset(new Date(),-3);
    var timeDomainEnd = d3.time.hour.offset(new Date(),+3);
    var timeDomainMode = FIT_TIME_DOMAIN_MODE;// fixed or fit
    var taskTypes = [];
    var taskStatus = [];
    var height = document.body.clientHeight - margin.top - margin.bottom-5;
    var width = document.body.clientWidth - margin.right - margin.left-5;

    var tickFormat = "%H:%M";

    var keyFunction = function(d) {
	return d.startDate + d.taskName + d.endDate;
    };

    var rectTransform = function(d) {
	return "translate(" + x(d.startDate) + "," + y(d.taskName) + ")";
    };

    var x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true);

    var y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1);

    var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.time.format(tickFormat)).tickSubdivide(true)
	    .tickSize(8).tickPadding(8);

    var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);

    var initTimeDomain = function(tasks) {
	if (timeDomainMode === FIT_TIME_DOMAIN_MODE) {
	    if (tasks === undefined || tasks.length < 1) {
		timeDomainStart = d3.time.day.offset(new Date(), -3);
		timeDomainEnd = d3.time.hour.offset(new Date(), +3);
		return;
	    }
	    tasks.sort(function(a, b) {
		return a.endDate - b.endDate;
	    });
	    timeDomainEnd = tasks[tasks.length - 1].endDate;
	    tasks.sort(function(a, b) {
		return a.startDate - b.startDate;
	    });
	    timeDomainStart = tasks[0].startDate;
	}
    };

    var initAxis = function() {
    x = d3.time.scale().domain([ timeDomainStart, timeDomainEnd ]).range([ 0, width ]).clamp(true);
	y = d3.scale.ordinal().domain(taskTypes).rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1);
	xAxis = d3.svg.axis().scale(x).orient("top").tickFormat(d3.time.format(tickFormat)).tickSubdivide(false)
		.tickSize(10).tickPadding(0);
    //xAxis2 = d3.svg.axis().scale(x).orient("top").tickFormat(d3.time.format("%W")).tickSubdivide(false)
    //    .tickSize(8).tickPadding(8).ticks(d3.time.weeks,1);

	yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);
    };

    function gantt(tasks) {

	initTimeDomain(tasks);
	initAxis();

	var svg = d3.select("#container")
	.append("svg")
    .attr("class", "chart")
    .attr("id", "chart")
    .attr("viewBox", "0 0 " +  (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom) )
    .attr("preserveAspectRatio", "xMinYMid")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
	.append("g")
        .attr("class", "gantt-chart")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
	.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

      svg.selectAll(".chart")
	 .data(tasks, keyFunction).enter()
	 .append("rect")
	 .attr("rx", 5)
         .attr("ry", 5)
	 .attr("class", function(d){
	     if(taskStatus[d.status] == null){ return "bar";}
	     return taskStatus[d.status];
	     })
	 .attr("y", 0)
	 .attr("transform", rectTransform)
	 .attr("height", function(d) { return y.rangeBand(); })
	 .attr("width", function(d) {
	     return (x(d.endDate) - x(d.startDate));
	     });

	 svg.append("g")
	 .attr("class", "x axis")
	 .attr("transform", "translate(0, " + 0 + ")")
	 .transition()
	 .call(xAxis);

/*
    svg.append("g")
    .attr("class", "x2 axis")
    .attr("transform", "translate(0, " + 0 + ")")
    .transition()
    .call(xAxis2);
 */
	 svg.append("g").attr("class", "y axis").transition().call(yAxis);

     svg.selectAll('.x text').attr('transform', 'translate(60)');
     svg.selectAll('.x2 text').attr('transform', 'translate(15)');

      svg.selectAll("line.x")
  .data(x.ticks(53))
  .enter().append("line")
  .attr("class", "x")
  .attr("x1", x)
  .attr("x2", x)
  .attr("y1", 0)
  .attr("y2", 700)
  .style("stroke", "#ccc");

	 return gantt;

    };

    gantt.redraw = function(tasks) {

	initTimeDomain(tasks);
	initAxis();

        var svg = d3.select("svg");

        var ganttChartGroup = svg.select(".gantt-chart");
        var rect = ganttChartGroup.selectAll("rect").data(tasks, keyFunction);

        rect.enter()
         .insert("rect",":first-child")
         .attr("rx", 5)
         .attr("ry", 5)
	 .attr("class", function(d){
	     if(taskStatus[d.status] == null){ return "bar";}
	     return taskStatus[d.status];
	     })
	 .transition()
	 .attr("y", 0)
	 .attr("transform", rectTransform)
	 .attr("height", function(d) { return y.rangeBand(); })
	 .attr("width", function(d) {
	     return (x(d.endDate) - x(d.startDate));
	     });

        rect.transition()
          .attr("transform", rectTransform)
	 .attr("height", function(d) { return y.rangeBand(); })
	 .attr("width", function(d) {
	     return (x(d.endDate) - x(d.startDate));
	     });

	rect.exit().remove();

	svg.select(".x").transition().call(xAxis);
	svg.select(".y").transition().call(yAxis);

	return gantt;
    };

    gantt.margin = function(value) {
	if (!arguments.length)
	    return margin;
	margin = value;
	return gantt;
    };

    gantt.timeDomain = function(value) {
	if (!arguments.length)
	    return [ timeDomainStart, timeDomainEnd ];
	timeDomainStart = +value[0], timeDomainEnd = +value[1];
	return gantt;
    };

    /**
     * @param {string}
     *                vale The value can be "fit" - the domain fits the data or
     *                "fixed" - fixed domain.
     */
    gantt.timeDomainMode = function(value) {
	if (!arguments.length)
	    return timeDomainMode;
        timeDomainMode = value;
        return gantt;

    };

    gantt.taskTypes = function(value) {
	if (!arguments.length)
	    return taskTypes;
	taskTypes = value;
	return gantt;
    };

    gantt.taskStatus = function(value) {
	if (!arguments.length)
	    return taskStatus;
	taskStatus = value;
	return gantt;
    };

    gantt.width = function(value) {
	if (!arguments.length)
	    return width;
	width = +value;
	return gantt;
    };

    gantt.height = function(value) {
	if (!arguments.length)
	    return height;
	height = +value;
	return gantt;
    };

    gantt.tickFormat = function(value) {
	if (!arguments.length)
	    return tickFormat;
	tickFormat = value;
	return gantt;
    };

    return gantt;
};