text:
/*
Schema population script for $(METRICSDBNAME)

Use this script in sqlcmd mode, setting the environment variables like this:
set METRICSDBNAME=HadoopMetrics

sqlcmd -S localhost\SQLEXPRESS -i C:\app\ambari-server-1.3.0-SNAPSHOT\resources\Hadoop-Metrics-SQLServer-CREATE.sql
*/

USE [$(METRICSDBNAME)]
GO

SET QUOTED_IDENTIFIER ON;
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'CompletedJob' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[CompletedJob]...';
	CREATE TABLE [dbo].[CompletedJob] (
		[ClusterNodeID]          INT      NOT NULL,
		[TagSetID]               INT      NOT NULL,
		[MapProgressPercent]     INT      NOT NULL,
		[CleanupProgressPercent] INT      NOT NULL,
		[SetupProgressPercent]   INT      NOT NULL,
		[ReduceProgressPercent]  INT      NOT NULL,
		[RunState]               INT      NOT NULL,
		[StartTime]              DATETIME NOT NULL,
		[EndTime]                DATETIME NOT NULL
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'PK_CompletedJob_ClusterNodeID_TagSetID' AND type_desc = N'CLUSTERED' AND IS_PRIMARY_KEY=N'1')
BEGIN
	PRINT N'Creating [dbo].[CompletedJob].[PK_CompletedJob_ClusterNodeID_TagSetID]...';
	ALTER TABLE [dbo].[CompletedJob]
		ADD CONSTRAINT [PK_CompletedJob_ClusterNodeID_TagSetID] PRIMARY KEY CLUSTERED ([ClusterNodeID] ASC, [TagSetID] ASC);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_CompletedJob_EndTime' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[CompletedJob].[IX_CompletedJob_EndTime]...';
	CREATE NONCLUSTERED INDEX [IX_CompletedJob_EndTime]
		ON [dbo].[CompletedJob]([EndTime] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_CompletedJob_TagSetID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[CompletedJob].[IX_CompletedJob_TagSetID]...';
	CREATE NONCLUSTERED INDEX [IX_CompletedJob_TagSetID]
		ON [dbo].[CompletedJob]([TagSetID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'Configuration' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[Configuration]...';
	CREATE TABLE [dbo].[Configuration] (
		[RequestedRefreshRate] INT NOT NULL
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'DatabaseVersion' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[DatabaseVersion]...';
	CREATE TABLE [dbo].[DatabaseVersion] (
		[Major]    INT NOT NULL,
		[Minor]    INT NOT NULL,
		[Build]    INT NOT NULL,
		[Revision] INT NOT NULL
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'MetricName' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[MetricName]...';
	CREATE TABLE [dbo].[MetricName] (
		[MetricID] INT            IDENTITY (1, 1) NOT NULL,
		[Name]     NVARCHAR (256) NOT NULL,
		PRIMARY KEY CLUSTERED ([MetricID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricName_Name' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricName].[IX_MetricName_Name]...';
	CREATE UNIQUE NONCLUSTERED INDEX [IX_MetricName_Name]
		ON [dbo].[MetricName]([Name] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'MetricPair' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[MetricPair]...';
	CREATE TABLE [dbo].[MetricPair] (
		[RecordID]    BIGINT         NOT NULL,
		[MetricID]    INT            NOT NULL,
		[MetricValue] NVARCHAR (512) NOT NULL
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'UX_MetricPair_RecordID_MetricID' AND type_desc = N'CLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricPair].[UX_MetricPair_RecordID_MetricID]...';
	CREATE UNIQUE CLUSTERED INDEX [UX_MetricPair_RecordID_MetricID]
		ON [dbo].[MetricPair]([RecordID] ASC, [MetricID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'MetricRecord' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord]...';
	CREATE TABLE [dbo].[MetricRecord] (
		[RecordID]        BIGINT         IDENTITY (1, 1) NOT NULL,
		[RecordTypeID]    INT            NOT NULL,
		[NodeID]          INT            NOT NULL,
		[SourceIP]        NVARCHAR (256) NULL,
		[ClusterNodeID]   INT            NOT NULL,
		[ServiceID]       INT            NOT NULL,
		[TagSetID]        INT            NOT NULL,
		[RecordTimestamp] BIGINT         NOT NULL,
		[RecordDate]      AS             DATEADD(second, CONVERT (INT, RecordTimestamp / 1000), CONVERT (DATETIME, '1970-01-01T00:00:00.000', 126)) PERSISTED,
		PRIMARY KEY CLUSTERED ([RecordID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_ClusterNodeID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_ClusterNodeID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_ClusterNodeID]
		ON [dbo].[MetricRecord]([ClusterNodeID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_NodeID_RecordID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_NodeID_RecordID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_NodeID_RecordID]
		ON [dbo].[MetricRecord]([NodeID] ASC, [RecordID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_NodeID_RecordTypeID_ClusterNodeID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_NodeID_RecordTypeID_ClusterNodeID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_NodeID_RecordTypeID_ClusterNodeID]
		ON [dbo].[MetricRecord]([NodeID] ASC, [RecordTypeID] ASC, [ClusterNodeID] ASC)
		INCLUDE([RecordDate]) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_NodeID_TagSetID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_NodeID_TagSetID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_NodeID_TagSetID]
		ON [dbo].[MetricRecord]([NodeID] ASC, [TagSetID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_RecordDate' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_RecordDate]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_RecordDate]
		ON [dbo].[MetricRecord]([RecordDate] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_RecordTimestamp_NodeID_RecordTypeID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_RecordTimestamp_NodeID_RecordTypeID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_RecordTimestamp_NodeID_RecordTypeID]
		ON [dbo].[MetricRecord]([RecordTimestamp] DESC, [NodeID] ASC, [RecordTypeID] ASC)
		INCLUDE([RecordID]) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_RecordTypeID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_RecordTypeID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_RecordTypeID]
		ON [dbo].[MetricRecord]([RecordTypeID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_RecordTypeID_ClusterNodeID_ServiceID_TagSetID_RecordTimestamp' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_RecordTypeID_ClusterNodeID_ServiceID_TagSetID_RecordTimestamp]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_RecordTypeID_ClusterNodeID_ServiceID_TagSetID_RecordTimestamp]
		ON [dbo].[MetricRecord]([RecordTypeID] ASC, [ClusterNodeID] ASC, [ServiceID] ASC, [TagSetID] ASC, [RecordTimestamp] DESC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_MetricRecord_TagSetID' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[IX_MetricRecord_TagSetID]...';
	CREATE NONCLUSTERED INDEX [IX_MetricRecord_TagSetID]
		ON [dbo].[MetricRecord]([TagSetID] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'UX_MetricRecord_RecordTypeID_NodeID_TagSetID_RecordTimestamp' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[MetricRecord].[UX_MetricRecord_RecordTypeID_NodeID_TagSetID_RecordTimestamp]...';
	CREATE UNIQUE NONCLUSTERED INDEX [UX_MetricRecord_RecordTypeID_NodeID_TagSetID_RecordTimestamp]
		ON [dbo].[MetricRecord]([RecordTypeID] ASC, [NodeID] ASC, [TagSetID] ASC, [RecordTimestamp] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'Service' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[Service]...';
	CREATE TABLE [dbo].[Service] (
		[ServiceID]        BIGINT         IDENTITY (1, 1) NOT NULL,
		[Name]             NVARCHAR (256),
		PRIMARY KEY CLUSTERED ([ServiceID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'Node' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[Node]...';
	CREATE TABLE [dbo].[Node] (
		[NodeID]                   INT            IDENTITY (1, 1) NOT NULL,
		[Name]                     NVARCHAR (256) NOT NULL,
		[LastKnownIP]              NVARCHAR (256) NULL,
		[LastNameNodeHeartBeat]    DATETIME       NULL,
		[LastJobTrackerHeartBeat]  DATETIME       NULL,
		[LastDataNodeHeartBeat]    DATETIME       NULL,
		[LastTaskTrackerHeartBeat] DATETIME       NULL,
		PRIMARY KEY CLUSTERED ([NodeID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_Node_Name' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[Node].[IX_Node_Name]...';
	CREATE UNIQUE NONCLUSTERED INDEX [IX_Node_Name]
		ON [dbo].[Node]([Name] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'RecordType' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[RecordType]...';
	CREATE TABLE [dbo].[RecordType] (
		[RecordTypeID] INT            IDENTITY (1, 1) NOT NULL,
		[Name]         NVARCHAR (225) NOT NULL,
		[Context]      NVARCHAR (225) NOT NULL,
		PRIMARY KEY CLUSTERED ([RecordTypeID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_RecordType_Context_Name' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[RecordType].[IX_RecordType_Context_Name]...';
	CREATE UNIQUE NONCLUSTERED INDEX [IX_RecordType_Context_Name]
		ON [dbo].[RecordType]([Context] ASC, [Name] ASC) ;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'TagSet' and type_desc = N'USER_TABLE')
BEGIN
	PRINT N'Creating [dbo].[TagSet]...';
	CREATE TABLE [dbo].[TagSet] (
		[TagSetID] INT            IDENTITY (1, 1) NOT NULL,
		[TagPairs] NVARCHAR (450) NOT NULL,
		PRIMARY KEY CLUSTERED ([TagSetID] ASC)
	);
END
GO

IF NOT EXISTS(SELECT name FROM sys.indexes WHERE name = N'IX_TagSet_TagPairs' AND type_desc = N'NONCLUSTERED')
BEGIN
	PRINT N'Creating [dbo].[TagSet].[IX_TagSet_TagPairs]...';
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TagSet_TagPairs]
		ON [dbo].[TagSet]([TagPairs] ASC) ;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_CompletedJob_TagSet_TagSetID')
BEGIN
	PRINT N'Creating FK_CompletedJob_TagSet_TagSetID...';
	ALTER TABLE [dbo].[CompletedJob] WITH NOCHECK
		ADD CONSTRAINT [FK_CompletedJob_TagSet_TagSetID] FOREIGN KEY ([TagSetID]) REFERENCES [dbo].[TagSet] ([TagSetID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_MetricPair_MetricName_MetricID')
BEGIN
	PRINT N'Creating FK_MetricPair_MetricName_MetricID...';
	ALTER TABLE [dbo].[MetricPair] WITH NOCHECK
		ADD CONSTRAINT [FK_MetricPair_MetricName_MetricID] FOREIGN KEY ([MetricID]) REFERENCES [dbo].[MetricName] ([MetricID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_MetricPair_MetricRecord_RecordID')
BEGIN
	PRINT N'Creating FK_MetricPair_MetricRecord_RecordID...';
	ALTER TABLE [dbo].[MetricPair] WITH NOCHECK
		ADD CONSTRAINT [FK_MetricPair_MetricRecord_RecordID] FOREIGN KEY ([RecordID]) REFERENCES [dbo].[MetricRecord] ([RecordID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_MetricRecord_Node_NodeID')
BEGIN
	PRINT N'Creating FK_MetricRecord_Node_NodeID...';
	ALTER TABLE [dbo].[MetricRecord] WITH NOCHECK
		ADD CONSTRAINT [FK_MetricRecord_Node_NodeID] FOREIGN KEY ([NodeID]) REFERENCES [dbo].[Node] ([NodeID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_MetricRecord_RecordType_RecordTypeID')
BEGIN
	PRINT N'Creating FK_MetricRecord_RecordType_RecordTypeID...';
	ALTER TABLE [dbo].[MetricRecord] WITH NOCHECK
		ADD CONSTRAINT [FK_MetricRecord_RecordType_RecordTypeID] FOREIGN KEY ([RecordTypeID]) REFERENCES [dbo].[RecordType] ([RecordTypeID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = N'FK_MetricRecord_TagSet_TagSetID')
BEGIN
	PRINT N'Creating FK_MetricRecord_TagSet_TagSetID...';
	ALTER TABLE [dbo].[MetricRecord] WITH NOCHECK
		ADD CONSTRAINT [FK_MetricRecord_TagSet_TagSetID] FOREIGN KEY ([TagSetID]) REFERENCES [dbo].[TagSet] ([TagSetID]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'uspInsertMetricValue' and type_desc = N'SQL_STORED_PROCEDURE')
BEGIN
	PRINT N'Creating [dbo].[uspInsertMetricValue]...';
	exec('CREATE PROCEDURE [dbo].[uspInsertMetricValue]
		@recordID bigint,
		@metricName nvarchar(256),
		@metricValue nvarchar(512)
	AS
	BEGIN
		SET NOCOUNT ON;

		DECLARE @metricID int;
		DECLARE @err int;

		IF @recordID IS NULL OR @metricName IS NULL RETURN;

		BEGIN TRANSACTION;
		SELECT @metricID = MetricID FROM MetricName WHERE Name = @metricName;
		IF @metricID IS NULL
		BEGIN
			INSERT INTO MetricName (Name) VALUES (@metricName);
			SELECT @err = @@ERROR, @metricID = SCOPE_IDENTITY();
			IF @err <> 0 GOTO Abort;
		END
		COMMIT TRANSACTION;

		INSERT INTO MetricPair (RecordID, MetricID, MetricValue) VALUES (@recordID, @metricID, @metricValue);
		RETURN;

	Abort:
		ROLLBACK TRANSACTION;
		RETURN;
	END')
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'uspUpdateHeartBeats' and type_desc = N'SQL_STORED_PROCEDURE')
BEGIN
	PRINT N'Creating [dbo].[uspUpdateHeartBeats]...';
	exec('CREATE PROCEDURE [dbo].[uspUpdateHeartBeats]
		@NodeID int,
		@SourceIP nvarchar(256),
		@NameNodeLast datetime,
		@JobTrackerLast datetime,
		@DataNodeLast datetime,
		@TaskTrackerLast datetime,
		@LastKnownIP nvarchar(256)
	AS
	BEGIN
		IF @NodeID IS NOT NULL
		BEGIN
			IF @NameNodeLast IS NOT NULL
			BEGIN
				UPDATE Node SET LastNameNodeHeartBeat = @NameNodeLast WHERE NodeID = @NodeID;
			END
			IF @JobTrackerLast IS NOT NULL
			BEGIN
				UPDATE Node SET LastJobTrackerHeartBeat = @JobTrackerLast WHERE NodeID = @NodeID;
			END
			IF @DataNodeLast IS NOT NULL
			BEGIN
				UPDATE Node SET LastDataNodeHeartBeat = @DataNodeLast WHERE NodeID = @NodeID;
			END
			IF @TaskTrackerLast IS NOT NULL
			BEGIN
				UPDATE Node SET LastTaskTrackerHeartBeat = @TaskTrackerLast WHERE NodeID = @NodeID;
			END
			IF @LastKnownIP IS NULL OR @SourceIP <> @LastKnownIP
			BEGIN
				UPDATE Node SET LastKnownIP = @SourceIP WHERE NodeID = @NodeID;
			END
		END
	END')
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'uspGetMetricRecord' and type_desc = N'SQL_STORED_PROCEDURE')
BEGIN
	PRINT N'Creating [dbo].[uspGetMetricRecord]...';
	exec('CREATE PROCEDURE [dbo].[uspGetMetricRecord]
		@recordTypeContext nvarchar(256),
		@recordTypeName nvarchar(256),
		@nodeName nvarchar(256),
		@sourceIP nvarchar(256),
		@clusterNodeName nvarchar(256),
		@serviceName nvarchar(256),
		@tagPairs nvarchar(512),
		@recordTimestamp bigint,
		@metricRecordID bigint OUTPUT
	AS
	BEGIN
		SET NOCOUNT ON;

		DECLARE @recordTypeID int
		DECLARE @nodeID int
		DECLARE @clusterNodeID int
		DECLARE @tagSetID int
		DECLARE @serviceID int
		DECLARE @err int
		DECLARE @recordIDCutoff bigint

		BEGIN TRANSACTION;
		SELECT @recordTypeID = RecordTypeID FROM RecordType WHERE Context = @recordTypeContext AND Name = @recordTypeName;
		IF @recordTypeID IS NULL
			BEGIN
				INSERT INTO RecordType (Context, Name) VALUES (@recordTypeContext, @recordTypeName);
				SELECT @err = @@ERROR, @recordTypeID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END
		COMMIT TRANSACTION;

		BEGIN TRANSACTION;
		SELECT @serviceID = serviceID FROM Service WHERE Name = @serviceName;
		IF @serviceID IS NULL
			BEGIN
				INSERT INTO Service (Name) VALUES (@serviceName);
				SELECT @err = @@ERROR, @serviceID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END
		COMMIT TRANSACTION;

		BEGIN TRANSACTION;
		SELECT @nodeID = NodeID FROM Node WHERE Name = @nodeName;

		IF @nodeID IS NULL
			BEGIN

			/* Start with a node type of uninitialized.  HealthNode will determine node type based on metrics delivered over time. */
				INSERT INTO Node (Name, LastKnownIP) VALUES (@nodeName, @sourceIP);
				SELECT @err = @@ERROR, @nodeID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END

		COMMIT TRANSACTION;

		-- Do our best to determine the cluster node ID based on completely flakey input from user which might be an IP address, a non-FQDN,
		-- or an FQDN.  Note that worker nodes may have a completely different idea about the name of the namenode (which is the node
		-- which represents the cluster) compared with the namenode itself

		BEGIN TRANSACTION;
		IF ((SELECT [dbo].[ufnIsIPAddress](@clusterNodeName)) = 1)
		BEGIN
			SELECT TOP 1 @clusterNodeID = NodeID from Node WHERE LastKnownIP = @clusterNodeName ORDER BY LastNameNodeHeartBeat DESC;
			IF @clusterNodeID IS NULL
			BEGIN
				INSERT INTO Node (Name, LastKnownIP) VALUES (@clusterNodeName, @sourceIP);
				SELECT @err = @@ERROR, @clusterNodeID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END
		END
		ELSE
		IF ((SELECT CHARINDEX(@clusterNodeName, ''.'', 1)) > 0)
		BEGIN
			-- IF this is not an IP address, but there is a dot in the name we assume we are looking at an FQDN
		SELECT @clusterNodeID = NodeID FROM Node WHERE Name = @clusterNodeName;
		IF @clusterNodeID IS NULL
			BEGIN
				INSERT INTO Node (Name, LastKnownIP) VALUES (@clusterNodeName, @sourceIP);
				SELECT @err = @@ERROR, @clusterNodeID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END
		END
		ELSE
		BEGIN
			-- We have got a non-FQDN, but the NameNode might know its FQDN, so be careful! We must prefer the FQDN if we can find one.
			-- Sadly, yes, this could break things if we are monitoring clusters from different domains.  This is now by design!
			SELECT TOP 1 @clusterNodeID = NodeID FROM Node WHERE Name LIKE @clusterNodeName + ''.%'' ORDER BY LastNameNodeHeartBeat DESC;
			IF @clusterNodeID IS NULL
				BEGIN
					SELECT @clusterNodeID = NodeID FROM Node WHERE Name = @clusterNodeName;
					if @clusterNodeID IS NULL
					BEGIN
						INSERT INTO Node (Name, LastKnownIP) VALUES (@clusterNodeName, @sourceIP);
						SELECT @err = @@ERROR, @clusterNodeID = SCOPE_IDENTITY();
						IF @err <> 0 GOTO Abort;
					END
				END
		END
		COMMIT TRANSACTION;

		-- Cleanup older metric records and pairs if necessary
		-- Policy is to keep between 60000 and 90000 metric records and associated metric pairs per node.
		IF (SELECT COUNT(*) FROM MetricRecord WHERE NodeID = @nodeID) > 90000
		BEGIN
			SELECT @recordIDCutoff = MIN(RecordID) FROM MetricRecord WHERE RecordID IN (SELECT TOP 60000 RecordID FROM MetricRecord WHERE NodeID = @nodeID ORDER BY RecordDate DESC);
			IF @recordIDCutoff IS NOT NULL
			BEGIN
				DELETE FROM MetricPair
				FROM MetricPair as mp
				JOIN MetricRecord as mr ON mp.RecordID = mr.RecordID
				WHERE mr.RecordID < @recordIDCutoff AND mr.NodeID = @nodeID;

				DELETE FROM MetricRecord
				WHERE RecordID < @recordIDCutoff AND NodeID = @nodeID;
			END;
		END;

		BEGIN TRANSACTION;
		SELECT @tagSetID = TagSetID FROM TagSet WHERE TagPairs = @tagPairs;
		IF @tagSetID IS NULL
			BEGIN
				INSERT INTO TagSet (TagPairs) VALUES (@tagPairs);
				SELECT @err = @@ERROR, @tagSetID = SCOPE_IDENTITY();
				IF @err <> 0 GOTO Abort;
			END
		COMMIT TRANSACTION;

		BEGIN TRANSACTION;
		SELECT @metricRecordID = RecordID FROM MetricRecord WHERE RecordTypeID = @recordTypeID AND NodeID = @nodeID AND ServiceID = @serviceID AND TagSetID = @tagSetID AND RecordTimestamp = @recordTimestamp;
		IF @metricRecordID IS NULL
		BEGIN
			INSERT INTO MetricRecord (RecordTypeID, NodeID, SourceIP, ClusterNodeID, ServiceID, TagSetID, RecordTimestamp) VALUES (@recordTypeID, @nodeID, @sourceIP, @clusterNodeID, @serviceID, @tagSetID, @recordTimestamp);
			SELECT @err = @@ERROR, @metricRecordID = SCOPE_IDENTITY();
			IF @err <> 0 GOTO Abort;
		END
		COMMIT TRANSACTION;

		GOTO Success;

	Abort:
		ROLLBACK TRANSACTION;
		SET @metricRecordID = NULL;
		RETURN;

	Success:
		RETURN;

	END')
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'ufnIsIPAddress' and type_desc = N'SQL_SCALAR_FUNCTION')
BEGIN
	PRINT N'Creating [dbo].[ufnIsIPAddress]...';
	exec('CREATE FUNCTION [dbo].[ufnIsIPAddress]
	(
		@inputString nvarchar(max)
	)
	RETURNS BIT
	AS
	BEGIN
		DECLARE @currentPos bigint = 1;
		DECLARE @nextPos bigint = 0;
		DECLARE @count int = 0;

		if (LEN(@inputString) = 0) RETURN 0;

		SELECT @nextPos = CHARINDEX(''.'', @inputString, @currentPos);

		WHILE (@nextPos < LEN(@inputString) AND @count < 4)
		BEGIN
			IF (@nextPos = 0) SET @nextPos = LEN(@inputString);
			IF ((SELECT ISNUMERIC(SUBSTRING(@inputString, @currentPos, @nextPos - @currentPos))) = 1)
			BEGIN
				SET @count = @count + 1;
				SET @currentPos = @nextPos
				SELECT @nextPos = CHARINDEX(''.'', @inputString, @currentPos + 1);
			END
			ELSE BREAK;
		END

		IF (@count = 4) RETURN 1;

		SET @currentPos = 1;
		SET @nextPos = 0;
		SET @count = 0;

		WHILE (@currentPos <= LEN(@inputString))
		BEGIN
			IF EXISTS (SELECT 1 WHERE SUBSTRING(@inputString, @currentPos, 1) LIKE ''[0-9A-Fa-f:]'')
			BEGIN
				IF (SUBSTRING(@inputString, @currentPos, 1) = N'':'') SET @count = @count + 1;
				SET @currentPos = @currentPos + 1;
			END
			ELSE RETURN 0;
		END
		IF @count >= 4 return 1;

		RETURN 0;
	END')
END
GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'RethrowError' and type_desc = N'SQL_STORED_PROCEDURE')
BEGIN
	PRINT N'Creating Stored Proc: [dbo].[RethrowError]...';
	exec('CREATE PROCEDURE [dbo].[RethrowError]
	AS
	BEGIN
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, -- Message text.
				   @ErrorSeverity, -- Severity.
				   @ErrorState -- State.
				   );
	END
	')
END

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'uspPurgeMetrics' and type_desc = N'SQL_STORED_PROCEDURE')
BEGIN
    -- purge metrics older than @noOfDays
	PRINT N'Creating [dbo].[uspPurgeMetrics]...';
	exec('CREATE PROCEDURE [dbo].[uspPurgeMetrics]
			@noOfDays bigint
	AS
	BEGIN

		IF @noOfDays IS NULL OR @noOfDays < 1
		BEGIN
			RAISERROR(''INVALID_ARGUMENT'', 15, 1)
			RETURN
		END;

		DECLARE @recordIDCutOff BIGINT
		SELECT @recordIDCutoff = MAX(RecordID) FROM MetricRecord WHERE DateDiff(day, RecordDate, CURRENT_TIMESTAMP) >= @noOfDays

		IF @recordIDCutoff IS NOT NULL
		BEGIN
			BEGIN TRY
				BEGIN TRANSACTION

				DELETE FROM MetricPair WHERE RecordID <= @recordIDCutoff

				DELETE FROM MetricRecord WHERE RecordID <= @recordIDCutoff

				IF @@TRANCOUNT > 0
				BEGIN
					COMMIT TRANSACTION
				END

			END TRY
			BEGIN CATCH
				IF @@TRANCOUNT > 0
				BEGIN
					ROLLBACK TRANSACTION;
				END

				 -- get error infromation and raise error
				EXECUTE [dbo].[RethrowError]
				RETURN

			END CATCH
		END;
	END');
END

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'ufGetMetrics' and type_desc = N'SQL_TABLE_VALUED_FUNCTION')
BEGIN
	PRINT N'Creating [dbo].[ufGetMetrics]...';
    exec('CREATE FUNCTION dbo.ufGetMetrics
		(@startTimeStamp bigint,
		 @endTimeStamp bigint,
		 @recordTypeContext NVARCHAR(256),
		 @recordTypeName NVARCHAR(256),
		 @metricName NVARCHAR(256),
		 @serviceComponentName NVARCHAR(256),
		 @nodeName NVARCHAR(256)
		)
		RETURNS TABLE --(MetricTimeStamp bigint, MetricValue NVARCHAR(512))
		AS
		RETURN
		(
			SELECT  s.RecordTimeStamp AS RecordTimeStamp,
					mp.MetricValue AS MetricValue
			FROM MetricPair mp
			INNER JOIN (SELECT	mr.RecordID AS RecordID,
								mr.RecordTimeStamp AS RecordTimeStamp
						FROM MetricRecord mr
						INNER JOIN RecordType rt ON (mr.RecordTypeId = rt.RecordTypeId)
						INNER JOIN Node nd ON (mr.NodeID = nd.NodeID)
						INNER JOIN Service sr ON (mr.ServiceID = sr.ServiceID)
						WHERE rt.Context = @recordTypeContext
						AND rt.Name = @recordTypeName
						AND (nd.Name = @nodeName)
						AND (sr.Name = @serviceComponentName)
						AND mr.RecordTimestamp >= @startTimeStamp
						AND mr.RecordTimestamp <= @endTimeStamp
						) s ON (mp.RecordID = s.RecordID)
			INNER JOIN MetricName mn ON (mp.MetricID = mn.MetricID)
			WHERE (mn.Name = @metricName)
		)'
)
END

GO

IF NOT EXISTS(SELECT name FROM sys.objects WHERE name = N'ufGetAggregatedServiceMetrics' and type_desc = N'SQL_TABLE_VALUED_FUNCTION')
BEGIN
	PRINT N'Creating [dbo].[ufGetAggregatedServiceMetrics]...';
    exec( 'CREATE FUNCTION [dbo].[ufGetAggregatedServiceMetrics]
		(@startTimeStamp bigint,
		 @endTimeStamp bigint,
		 @recordTypeContext NVARCHAR(256),
		 @recordTypeName NVARCHAR(256),
		 @metricName NVARCHAR(256),
		 @serviceComponentName NVARCHAR(256),
		 @period integer
		)
		RETURNS TABLE ----(TimeStampBlock integer, MetricTimeStamp bigint, MetricValue NVARCHAR(512))
		AS
		RETURN
		(
			SELECT FLOOR ((mr.RecordTimeStamp - @startTimeStamp) / @period) TimeStampBlock, MAX(mr.RecordTimeStamp) RecordTimeStamp,  SUM(CONVERT(NUMERIC(18,4), MetricValue)) AggMetricValue
			FROM MetricPair mp
			INNER JOIN MetricRecord mr ON (mp.RecordID = mr.RecordID)
			INNER JOIN RecordType rt ON (rt.RecordTypeID = mr.RecordTypeID)
			INNER JOIN MetricName mn ON (mn.MetricID = mp.MetricID)
			INNER JOIN Service sr ON (sr.ServiceID = mr.ServiceID)
			WHERE mr.RecordTimestamp >= @startTimeStamp
			AND mr.RecordTimestamp <= @endTimeStamp
			AND mn.Name = @metricName
			AND rt.Context = @recordTypeContext
			AND rt.Name = @recordTypeName
			AND sr.Name = @serviceComponentName
			GROUP BY FLOOR ((mr.RecordTimeStamp - @startTimeStamp) / @period)
		)'
	    )
END
GO


text:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Threading;

namespace EarTrumpet.DataModel
{
    public class FilteredCollectionChain<T>
    {
        ObservableCollection<T> _items;

        public ObservableCollection<T> Items { get; }

        public FilteredCollectionChain(ObservableCollection<T> items, Dispatcher foregroundDispatcher)
        {
            Items = new ObservableCollection<T>();

            _items = items;

            foregroundDispatcher.BeginInvoke((Action)(() => {
                Listen();
                Populate();
            }));
        }

        void Listen()
        {
            _items.CollectionChanged += Sessions_CollectionChanged;
        }

        void Free()
        {
            _items.CollectionChanged -= Sessions_CollectionChanged;
        }

        private void Sessions_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    Items.Add((T)e.NewItems[0]);
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    Items.Remove((T)e.OldItems[0]);
                    break;
                default: throw new NotImplementedException();
            }
        }

        public void AddFilter(Func<ObservableCollection<T>, ObservableCollection<T>> filter)
        {
            Free();
            _items = filter(_items);
            Listen();
            Populate();
        }

        private void Populate()
        {
            foreach(var s in _items)
            {
                if (!Items.Contains(s))
                {
                    Items.Add(s);
                }
            }

            var filtered = Items.Where(i => !_items.Contains(i)).ToArray();
            foreach(var item in filtered)
            {
                Items.Remove(item);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<package>
  <description brief="turtlebot2i_navigation">

     turtlebot2i_navigation

  </description>
  <author>Alberto</author>
  <license>BSD</license>
  <review status="unreviewed" notes=""/>
  <url>http://ros.org/wiki/turtlebot2i_navigation</url>

</package>


text:
if config.respond_to?(:gems)
  config.gem 'ruby-openid', :lib => 'openid', :version => '>=2.0.4'
else
  begin
    require 'openid'
  rescue LoadError
    begin
      gem 'ruby-openid', '>=2.0.4'
    rescue Gem::LoadError
      puts "Install the ruby-openid gem to enable OpenID support"
    end
  end
end

config.to_prepare do
  ActionController::Base.send :include, OpenIdAuthentication
end


text:
// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__526E3320_2AFF_4751_A65B_F5FE14E3B851__INCLUDED_)
#define AFX_STDAFX_H__526E3320_2AFF_4751_A65B_F5FE14E3B851__INCLUDED_

#pragma once

// Change these values to use different versions
#define WINVER          0x0501
#define _WIN32_WINNT    0x0501
#define _WIN32_IE       0x0400
#define _RICHEDIT_VER   0x0100
#define _CRT_SECURE_NO_WARNINGS

// #define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN          // Exclude rarely-used stuff from Windows headers

// #define _WTL_USE_CSTRING
#define _WTL_NO_CSTRING

// #include <atlbase.h>
#include <atlstr.h>

#include <atlapp.h>
//~ extern CAppModule _Module;

#include <vector>

// output a debug message to windows debug channel
void __cdecl odprintf(const char *format, ...) {
    TCHAR    buf[4096], *p = buf;
    va_list args;
    int     n;

    va_start(args, format);
    // n = _vstprintf(p, format, args);
    n = _vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL
    va_end(args);

    p += (n < 0) ? sizeof buf - 3 : n;

    while ( p > buf  &&  isspace(p[-1]) )
            *--p = '\0';

    *p++ = '\r';
    *p++ = '\n';
    *p   = '\0';

    OutputDebugString(buf);
}

// split a string into a 1d vector
// this function will strip leading and consecutive separators
std::vector<CString> CString_split(CString strInput, CString strDelim = _T(";")) {
    std::vector<CString> aRet;
    int nTokenPos = 0;
    CString strToken = strInput.Tokenize(strDelim, nTokenPos);
    while (!strToken.IsEmpty()) {
        aRet.push_back(strToken);
        strToken = strInput.Tokenize(strDelim, nTokenPos);
    }
    return(aRet);
}

// Split a 2d table
// uses a default of ; for record separator and , for field separator
std::vector<std::vector<CString>> CString_split(std::vector<CString> aInput, CString strDelim = _T(",")) {
    std::vector<std::vector<CString>> aRet;
    for(size_t i=0;i < aInput.size();i++) {
        aRet.push_back(CString_split(aInput[i], strDelim));
    }
    return(aRet);
}

// filter a list of file names
// returns only those which extension is in a hardcoded list
template <class T>
std::vector<T> VectorFilterSufix(std::vector<T> vInput, std::vector<T> vExt) {
    std::vector<T> vRet;

    // use the the extensions as the priority list
    for(auto j = vExt.begin(); j != vExt.end();++j) {
        for (auto i = vInput.begin(); i != vInput.end();++i) {
            // compare the extension of the name with the current test
            if(i->Right(j->GetLength()).CompareNoCase(*j) == 0) {
                vRet.push_back(*i);
            }
        }
    }
    return(vRet);
};

// return a list of all client script files
template <class T>
T GetClientScriptPath() {
    std::vector<T> vExt;
    // to add a new supported file, insert a new line here with the file extension
    // the order is important. the first matched file will be used
    // Python
    vExt.push_back(T("PY"));
    // Perl
    vExt.push_back(T("LAVA"));
    vExt.push_back(T("PL"));
    // Windows Batch
    vExt.push_back(T("BAT"));
    vExt.push_back(T("CMD"));
    // Unix C Shell
    vExt.push_back(T("CSH"));
    // Custom DLL with a run function
    vExt.push_back(T("DLL"));
    // HTML application
    vExt.push_back(T("HTA"));
    // Windows Script Host
    vExt.push_back(T("VBS"));
    vExt.push_back(T("JS"));
    auto vFilter = VectorFilterSufix(FileSearch<T>(NULL, GetModuleName()), vExt);
    if(vFilter.size() > 0) {
        // pick the first matched file
        return(vFilter.front());
    }
    return(T());
}

// return a list of all help files
template <class T>
T GetHelpFilePath() {
    std::vector<T> vExt;
    vExt.push_back(T("CHM"));
    vExt.push_back(T("HLP"));
    vExt.push_back(T("PDF"));
    auto vFilter = VectorFilterSufix(FileSearch<T>(NULL, GetModuleName()), vExt);
    if(vFilter.size() > 0) {
        return(vFilter.front());
    }
    return(T());
}

// return the base name of the current running process
CString GetModuleName() {
    TCHAR szPath[MAX_PATH];
    GetModuleFileName(NULL, szPath, MAX_PATH );
    //~ LPTSTR szName = (LPTSTR) LocalAlloc(LMEM_ZEROINIT, MAX_PATH * sizeof(TCHAR));
    TCHAR szName[MAX_PATH];
    // split the path from the file name
    _tsplitpath(szPath, NULL, NULL, szName, NULL);
    return CString(szName);
}

/* return the directory where this executable resides
CString GetModuleDirectory() {
    // create the temporary buffers on the stack
    TCHAR szResult[MAX_PATH];
    TCHAR szPath[MAX_PATH];
    TCHAR szDir[MAX_PATH];

    // get the full path to this module
    GetModuleFileName(NULL, szPath, MAX_PATH );

    // use the CRT to split the path to the executable into individual components
    _tsplitpath(szPath, szResult, szDir, NULL, NULL);
    // concatenate the drive with the dir to obtain the complete path to dir
    lstrcat(szResult, szDir);

    return CString(szResult);
}
*/

// when a file resides in the current directory or above
// strip the current directory portion from the file path
CString MakePathRelative(LPCTSTR szPath) {
    CString strText(szPath);
    TCHAR szCurrentDir[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, szCurrentDir);
    if(PathIsPrefix(szCurrentDir, szPath)) {
        strText.Delete(0, lstrlen(szCurrentDir) + 1);

    }
    return(strText);
}

// convert a extension into a File Dialog buffer
// the return buffer is not a standard string since it
// will contain null bytes separating each extension
// the calling routine should to free the allocated memory
// or it will create a small leak, which may be aceptable
LPTSTR CreateFileFilter(CString sExt) {
    //~ TCHAR strFilter[BUFSIZ];
    LPTSTR strFilter = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, BUFSIZ);
    // we cant use str functions to generate the filters because of the null bytes in the data
    // so we have to resort to pointers and buffers
    TCHAR* lpstrFilter = strFilter;

    // create the specified wildcard filter using the user supplied extensions
    if(sExt.GetLength() > 0) {
        auto vExt = CString_split(sExt, _T(","));
        // the wildcard filter can be two equal zero terminated strings
        // one is the description, other is the actual filter
        for(int j=0;j<2;j++) {
            for(auto i = vExt.begin();i != vExt.end();++i) {
                // multiple extensions can be separated by semicollon
                if(i != vExt.begin()) {
                    CopyMemory(lpstrFilter, _T(";"), 1);
                    lpstrFilter++;
                }
                CopyMemory(lpstrFilter, _T("*."), 2);
                lpstrFilter += 2;
                CopyMemory(lpstrFilter, *i, i->GetLength() + 1);
                lpstrFilter += i->GetLength();
            }
            lpstrFilter++;
        }
    }
    // always have the all files option on the wildcards
    CopyMemory(lpstrFilter, _T("All Files (*.*)\0*.*\0\0"), sizeof(TCHAR) * 21);
    return(strFilter);
}

// Format a readable error message, display a message box,
// and exit from the application.
void ErrorExit(LPCTSTR lpszFunction = _T("Function"), WORD nIcon = MB_ICONERROR) {
    LPVOID lpMsgBuf;
    //~ LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    LPTSTR lpDisplayBuf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
    //~ _sntprintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), lpszFunction, dw, lpMsgBuf);
    wsprintf((LPTSTR)lpDisplayBuf, TEXT("%s failed with error %d: %s"), lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), nIcon);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    if(nIcon == MB_ICONERROR) ExitProcess(1);
}

// if the expression evaluates to FALSE, terminate the program with a error message
void CheckExit(BOOL bCheck) {
    if(!bCheck) {
        ErrorExit(GetModuleName());
    }
}
// if the expression evaluates to FALSE, show a message to the user but dont exit
void CheckWarn(BOOL bCheck) {
    if(!bCheck) {
        ErrorExit(GetModuleName(), MB_ICONEXCLAMATION);
    }
}

#include <atlfile.h>
// read a entire file into a buffer
LPSTR ReadFile(LPCTSTR szFilename) {
    CAtlFile oFile;
    CheckWarn(SUCCEEDED(oFile.Create(szFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING)));

    ULONGLONG nFileSize;
    CheckWarn(SUCCEEDED(oFile.GetSize(nFileSize)));
    // allocate a buffer that will hold the entire file plus a zero byte to terminate the string
    LPSTR pBuffer = (LPSTR)LocalAlloc(LMEM_ZEROINIT, static_cast<ULONG>(nFileSize) + 1);
    ULONG nBytesRead = 0;
    ULONG nTotalRead = 0;
    // read chunks from the file up to the file size
    while(SUCCEEDED(oFile.Read(pBuffer + nTotalRead, static_cast<DWORD>(nFileSize - nTotalRead), nBytesRead)) && nTotalRead < nFileSize) {
        nTotalRead += nBytesRead;
    }
    return(pBuffer);
}

// check if two rectangles overlap
//~ if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
    //~ RectA.Y1 < RectB.Y2 && RectA.Y2 > RectB.Y1)
template <class T>
bool rectOverlap(T RectA, T RectB) {
    if (RectA.left > RectB.right || RectA.right < RectB.left ||
        RectA.top > RectB.bottom || RectA.bottom < RectB.top)
        return(FALSE);
    return(TRUE);
}

// for a directory, return a list of files that match the given file prefix
// input:
// diretory to search (Ex.: C:\\data
// string with prefix of files to search (Ex.: backup_data_)
// boolean value indicating if the search should recurse to subfolders
template <class T>
std::vector<T> FileSearch( LPCTSTR lpszWorkdir = NULL, LPCTSTR lpszPattern = NULL, BOOL bRecursive = FALSE ) {
    std::vector<T> vRet;
    CString strWorkdir = lpszWorkdir;
    if( !strWorkdir.IsEmpty() && (strWorkdir.Right(1) != '\\')  )
        strWorkdir += "\\";

    WIN32_FIND_DATA file_data = {0};
    HANDLE hFile = FindFirstFile( strWorkdir + "*", &file_data );

    if( hFile != INVALID_HANDLE_VALUE ) {
        TCHAR sBuffer[MAX_PATH];

        do {
            // concatenate the base folder with the current file
            lstrcpy(sBuffer, strWorkdir);
            lstrcat(sBuffer, file_data.cFileName);
            if( bRecursive && file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                // recurse to subfolders
                if( lstrcmp(file_data.cFileName, _T(".")) != 0 && lstrcmp(file_data.cFileName, _T("..")) != 0 ) {
                    auto vRec = FileSearch<T>( sBuffer, lpszPattern, bRecursive );
                    vRet.insert(vRet.end(), vRec.begin(), vRec.end());
                }
            } else {
                if( (file_data.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) == 0 ) {
                    // check if the current file matches the pattern, if any was given
                    if(lpszPattern == NULL || _strnicmp(file_data.cFileName, lpszPattern, lstrlen(lpszPattern)) == 0) {
                        //lstrcmpi
                        vRet.push_back(T(sBuffer));
                    }
                }
            }
        } while( FindNextFile( hFile, &file_data ) );
        FindClose( hFile );
    }

    return(vRet);
}

// if a string contains a space or is empty, quote it with double quotes
template <class T>
T QuoteString(T strText) {
    if(strText.IsEmpty() || strText.FindOneOf(_T(" ;&|*<>\\")) > 0) {
        strText.Insert(0, '"');
        strText += '"';
    }
    return strText;
}

// set the windows clipboard to a given string
// return non-zero on error
WORD SetClipboardCString(HWND hWnd, CString strData) {
    // lock the clipboard to our thread
    if(! ::OpenClipboard(hWnd))
        return(EXIT_FAILURE);

    // we only really get ownership of the clipboard when we empty it
    if(! EmptyClipboard())
        return(EXIT_FAILURE);

    // copy the CString data into a global buffer
    HGLOBAL hGlobal = GlobalAlloc(GMEM_ZEROINIT|GMEM_MOVEABLE|GMEM_DDESHARE, (strData.GetLength()+1)*sizeof(TCHAR));
    //HGLOBAL hGlobal = GlobalAlloc(GMEM_NODISCARD | GMEM_ZEROINIT, (strData.GetLength()+1)*sizeof(TCHAR));

    LPTSTR lpszBuf = static_cast<LPTSTR>(::GlobalLock(hGlobal));
    // lstrcpy((LPTSTR)hClipboardData,strData);
    lstrcpy(lpszBuf, strData);
    // set the clipboard to the value on the burffer
    SetClipboardData(CF_TEXT, hGlobal);
    // clean up
    GlobalUnlock(hGlobal);
    GlobalFree(hGlobal);
    CloseClipboard();

    return(EXIT_SUCCESS);
}

// return the FileUsage property of a DLL
template <class T>
T GetFileVersion( T pFilePath ) {
    DWORD               dwSize              = 0;
    BYTE                *pVersionInfo       = NULL;
    VS_FIXEDFILEINFO    *pFileInfo          = NULL;
    UINT                pLenFileInfo        = 0;

    /*getting the file version info size */
    dwSize = GetFileVersionInfoSize( pFilePath, NULL );
    if ( dwSize != 0 ) {
        // odprintf( "Error in GetFileVersionInfoSize: %d\n", GetLastError() );
        pVersionInfo = new BYTE[ dwSize ]; /*allocation of space for the verison size */

        /*entering all info     data to pbVersionInfo*/
        if ( GetFileVersionInfo( pFilePath, 0, dwSize, pVersionInfo )
        && VerQueryValue( pVersionInfo, _T("\\StringFileInfo\\040904b0\\FileDescription"), (LPVOID*) &pFileInfo, &pLenFileInfo ) ) {
            // odprintf("pFileInfo %s", pFileInfo);
            // success! pFileInfo now contains the result
        } else {
            // EXIT_FAILURE! clean up buffer
            delete[] pVersionInfo;
            pFileInfo = NULL;
        }
    }

    return (T)pFileInfo;
}

// worker function pattern
typedef DWORD(CALLBACK *prun)(LPCSTR);

// calls a compatible worker dll
// the dll must have as its first exported function
// a prototype that accepts a single LPCSTR and returns a DWORD
template <class T>
T RunDLL(LPCSTR lpszPath, LPCSTR lpszArg) {
  HINSTANCE hGetProcIDDLL = LoadLibrary(lpszPath);
  // odprintf("RunDLL lpszPath %s lpszArg %s", lpszPath, lpszArg);

  if (!hGetProcIDDLL) {
    // odprintf("could not load the dynamic library");
    return EXIT_FAILURE;
  }

  // resolve function address here
  // GetProcAddress usualy receives a LPCSTR with function name
  // but it can also receive a DWORD with a index
  auto fptr = GetProcAddress(hGetProcIDDLL, reinterpret_cast<LPCSTR>(1));
  if (!fptr) {
    // odprintf("could not locate the function");
    return EXIT_FAILURE;
  }
  // cast the generic functino pointer to the standard worker function call defined in worker.h
  auto pRun = reinterpret_cast<prun>(fptr);

  return(pRun(_T(lpszArg)));
}

#endif // !defined(AFX_STDAFX_H__526E3320_2AFF_4751_A65B_F5FE14E3B851__INCLUDED_)


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **string** | Unique identifier prefixed with `sfm_`. | [optional]
**deleted** | **bool** | Only returned if the resource has been successfully deleted. | [optional]
**object** | **string** | Value is type of resource. | [optional] [default to OBJECT_SELF_MAILER_DELETED]

[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md)


text:
So that this doesn't become repetitive: for the reasons behind the answers
below, see the [Architecture](architecture.md) page. The goal of the answers here is to be as
helpful and concise as possible.

## Where is stack installed and will it interfere with `ghc` (etc) I already have installed?

Stack itself is installed in normal system locations based on the mechanism you used (see the [Install and upgrade](install_and_upgrade.md) page). Stack installs the Stackage libraries in `~/.stack` and any project libraries or extra dependencies in a `.stack-work` directory within each project's directory. None of this should affect any existing Haskell tools at all.

## What is the relationship between stack and cabal?

* Cabal-the-library is used by stack to build your Haskell code.
* cabal-install (the executable) is used by stack for its dependency solver functionality.
* A .cabal file is provided for each package, and defines all package-level metadata just like it does in the cabal-install world: modules, executables, test suites, etc. No change at all on this front.
* A stack.yaml file references 1 or more packages, and provides information on where dependencies come from.
* `stack build` currently initializes a stack.yaml from the existing .cabal file. Project initialization is something that is still being discussed and there may be more options here for new projects in the future (see issue [253](https://github.com/commercialhaskell/stack/issues/253))

## I need to use a different version of a package than what is provided by the LTS Haskell snapshot I'm using, what should I do?

You can make tweaks to a snapshot by modifying the `extra-deps` configuration value in your `stack.yaml` file, e.g.:

```yaml
resolver: lts-2.9
packages:
- '.'
extra-deps:
- text-1.2.1.1
```

## I need to use a package (or version of a package) that is not available on hackage, what should I do?

Add it to the `packages` list in your project's `stack.yaml`, specifying the package's source code location relative to the directory where your `stack.yaml` file lives, e.g.

```yaml
resolver: lts-2.10
packages:
- '.'
- third-party/proprietary-dep
- github-version-of/conduit
- patched/diagrams
extra-deps: []
```

The above example specifies that it should include the package at the root directory (`'.'`), that the `proprietary-dep` package is found in the project's `third-party` folder, that the `conduit` package is found in the project's `github-version-of` folder, and that the `diagrams` package is found in the project's `patched` folder. This autodetects changes and reinstalls the package.

To install packages directly from a Git repository, use e.g.:

```yaml
resolver: lts-2.10
packages:
- location:
    git: https://github.com/githubuser/reponame.git
    commit: somecommitID
```

Note that the `- '.'` line has been omitted, so the package in the root directory will not be used.

## What is the meaning of the arguments given to stack build, test, etc?

Those are the targets of the build, and can have one of three formats:

* A package name (e.g., `my-package`) will mean that the `my-package` package must be built
* A package identifier (e.g., `my-package-1.2.3`), which includes a specific version. This is useful for passing to `stack install` for getting a specific version from upstream
* A directory (e.g., `./my-package`) for including a local directory's package, including any packages in subdirectories

## I need to modify an upstream package, how should I do it?

Typically, you will want to get the source for the package and then add it to
your `packages` list in stack.yaml. (See the previous question.)
`stack unpack` is one approach for getting the source.
Another would be to add the upstream package as a submodule to your
project.

## Am I required to use a Stackage snapshot to use stack?

No, not at all. If you prefer dependency solving to curation, you can continue with that workflow. Instead of describing the details of how that works here, it's probably easiest to just say: run `stack init --solver` and look at the generated stack.yaml.

## How do I use this with sandboxes?

Explicit sandboxing on the part of the user is not required by stack. All
builds are automatically isolated into separate package databases without any
user interaction. This ensures that you won't accidentally corrupt your
installed packages with actions taken in other projects.

## Can I run `cabal` commands inside `stack exec`?

With a recent enough version of cabal-install (>= 1.22), you can. For older versions, due to [haskell/cabal#1800](https://github.com/haskell/cabal/issues/1800), this does not work. Note that even with recent versions, for some commands you may need this extra level of indirection:
```
$ stack exec -- cabal exec -- cabal <command>
```

However, virtually all `cabal` commands have an equivalent in stack, so this should not be necessary. In particular, `cabal` users may be accustomed to the `cabal run` command. In stack:
```
$ stack build && stack exec <program-name>
```
Or, if you want to install the binaries in a shared location:
```
$ stack install
$ <program-name>
```
assuming your `$PATH` has been set appropriately.

## Using custom preprocessors

If you have a custom preprocessor, for example, Ruby, you may have a
file like:

***B.erb***

``` haskell
module B where

<% (1..5).each do |i| %>
test<%= i %> :: Int
test<%= i %> = <%= i %>
<% end %>
```

To ensure that Stack picks up changes to this file for rebuilds, add
the following line to your .cabal file:

    extra-source-files:   B.erb

## I already have GHC installed, can I still use stack?

Yes. stack will default to using whatever GHC is on your `PATH`. If that GHC is a
compatible version with the snapshot you're using, it will simply use it.
Otherwise, it will prompt you to run `stack setup`. Note that `stack setup` installs GHC into `~/.stack/programs/$platform/ghc-$version/` and not a global location.

Note that GHC installation doesn't work for all OSes, so in some cases the
first option will need to install GHC yourself.

## How does stack determine what GHC to use?

It uses the first GHC that it finds on the `PATH`. If that GHC does not comply with the various requirements (version, architecture) that your project needs, it will prompt you to run `stack setup` to get it. `stack` is fully aware of all GHCs that it has installed itself.

See [this issue](https://github.com/commercialhaskell/stack/issues/420) for a detailed discussion.

## How do I upgrade to GHC 7.10.2 with stack?

If you already have a prior version of GHC use `stack --resolver ghc-7.10 setup --reinstall`. If you don't have any GHC installed, you can skip the `--reinstall`.

## How do I get extra build tools?

stack will automatically install build tools required by your packages or their
dependencies, in particular alex and happy.

__NOTE__: This works when using lts or nightly resolvers, not with ghc or custom resolvers. You can manually install build tools by running, e.g., `stack build alex happy`.

## How does stack choose which snapshot to use when creating a new config file?

It checks the two most recent LTS Haskell major versions and the most recent
Stackage Nightly for a snapshot that is compatible with all of the version
bounds in your .cabal file, favoring the most recent LTS. For more information,
see the snapshot auto-detection section in the architecture document.

## I'd like to use my installed packages in a different directory. How do I tell stack where to find my packages?

Set the `STACK_YAML` environment variable to point to the `stack.yaml` config
file for your project. Then you can run `stack exec`, `stack ghc`, etc., from
any directory and still use your packages.

## My tests are failing. What should I do?

Like all other targets, `stack test` runs test suites in parallel by default. This can cause problems with test suites that depend on global resources such as a database or binding to a fixed port number. A quick hack is to force stack to run all test suites in sequence, using `stack test --jobs=1`. For test suites to run in parallel developers should ensure that their test suites do not depend on global resources (e.g. by asking the OS for a random port to bind to) and where unavoidable, add a lock in order to serialize access to shared resources.

## Can I get bash autocompletion?

Yes, see the [shell-autocompletion documentation](shell_autocompletion.md)

## How do I update my package index?

Users of cabal are used to running `cabal update` regularly. You can do the
same with stack by running `stack update`. But generally, it's not necessary:
if the package index is missing, or if a snapshot refers to package/version
that isn't available, stack will automatically update and then try again. If
you run into a situation where stack doesn't automatically do the update for
you, please report it as a bug.

## Isn't it dangerous to automatically update the index? Can't that corrupt build plans?

No, stack is very explicit about which packages it's going to build for you.
There are three sources of information to tell it which packages to install:
the selected snapshot, the `extra-deps` configuration value, and your local
packages. The only way to get stack to change its build plan is to modify one
of those three. Updating the index will have no impact on stack's behavior.

## I have a custom package index I'd like to use, how do I do so?

You can configure this in your stack.yaml. See [YAML configuration](yaml_configuration.md).

## How can I make sure my project builds against multiple ghc versions?

You can create multiple yaml files for your project,
one for each build plan. For example, you might set up your project directory like so:

```
myproject/
  stack-7.8.yaml
  stack-7.10.yaml
  stack.yaml --> symlink to stack-7.8.yaml
  myproject.cabal
  src/
    ...
```

When you run `stack build`, you can set the
`STACK_YAML` environment variable to indicate which build plan to use.

```
$ stack build                             # builds using the default stack.yaml
$ STACK_YAML=stack-7.10.yaml stack build  # builds using the given yaml file
```

## I heard you can use this with Docker?

Yes, stack supports using Docker with images that contain preinstalled Stackage
packages and the tools. See [Docker integration](docker_integration.md) for details.

## How do I use this with Travis CI?

See the [Travis section in the GUIDE](GUIDE.md#travis-with-caching)

## What is licensing restrictions on Windows?

Currently on Windows GHC produces binaries linked statically with [GNU Multiple Precision Arithmetic Library](https://gmplib.org/) (GMP), which is used by [integer-gmp](https://hackage.haskell.org/package/integer-gmp) library to provide big integer implementation for Haskell. Contrary to the majority of Haskell code licensed under permissive BSD3 license, GMP library is licensed under LGPL, which means resulting binaries [have to be provided with source code or object files](http://www.gnu.org/licenses/gpl-faq.html#LGPLStaticVsDynamic). That may or may not be acceptable for your situation. Current workaround is to use GHC built with alternative big integer implementation called integer-simple, which is free from LGPL limitations as it's pure Haskell and does not use GMP. Unfortunately it has yet to be available out of the box with stack. See [issue #399](https://github.com/commercialhaskell/stack/issues/399) for the ongoing effort and information on workarounds.

## How to get a working executable on Windows?

When executing a binary after building with `stack build` (e.g. for target "foo"), the command `foo.exe` might complain about missing runtime libraries (whereas `stack exec foo` works).

Windows is not able to find the necessary C++ libraries from the standard prompt because they're not in the PATH environment variable. `stack exec` works because it's modifying PATH to include extra things.

Those libraries are shipped with GHC (and, theoretically in some cases, MSYS). The easiest way to find them is `stack exec which`. E.g.

    >stack exec which libstdc++-6.dll
    /c/Users/Michael/AppData/Local/Programs/stack/i386-windows/ghc-7.8.4/mingw/bin/libstdc++-6.dll

A quick workaround is adding this path to the PATH environment variable or copying the files somewhere Windows finds them (cf. https://msdn.microsoft.com/de-de/library/7d83bc18.aspx).

Cf. issue [#425](https://github.com/commercialhaskell/stack/issues/425).

## Can I change stack's default temporary directory?

Stack makes use of a temporary directory for some commands (/tmp by default on linux). If there is not enough free space in this directory, stack may fail (see issue [#429](https://github.com/commercialhaskell/stack/issues/429) ). For instance `stack setup` with a GHC installation requires roughly 1GB free.

A custom temporary directory can be forced:

* on Linux by setting the environment variable TMPDIR (eg `$ TMPDIR=path-to-tmp stack setup`)
* on Windows by setting one of the environment variable (given in priority order), TMP, TEMP, USERPROFILE

If you use Stack with Nix integration, be aware that Nix _also_ uses that TMPDIR
variable, and if it is not set Nix sets it to some subdirectory of `/run`, which
on most Linuxes is a Ramdir. Nix will run the builds in TMPDIR, therefore if you
don't have enough RAM you will get errors about disk space.  If this happens to
you, please _manually_ set TMPDIR before launching Stack to some directory on the
disk.

## Why doesn't stack rebuild my project when I specify `--ghc-options` on the command line?

Because GHC options often only affect optimization levels and warning behavior, stack doesn't recompile
when it detects an option change by default. This behavior can be changed though by setting the
[`rebuild-ghc-options` option](yaml_configuration.md#rebuild-ghc-options) to `true`.

To force recompilation manually, use the `--force-dirty` flag. If this still doesn't lead to a rebuild,
add the `-fforce-recomp` flag to your `--ghc-options`.

## Why doesn't stack apply my `--ghc-options` to my dependencies?

By default, stack applies command line GHC options only to local packages (these are all
the packages that are specified in the `packages` section of your `stack.yaml`).
For an explanation of this choice see [this discussion on the issue tracker](https://github.com/commercialhaskell/stack/issues/827#issuecomment-133263678).

If you still want to set specific GHC options for a dependency, use the [`ghc-options` option](yaml_configuration.md#ghc-options) in your
`stack.yaml` or global `~/.stack/config.yaml`.

To change the set of packages that command line GHC options apply to, use the [`apply-ghc-options` option](yaml_configuration.md#apply-ghc-options).

## stack setup on a windows system only tells me to add certain paths to the PATH variable instead of doing it

If you are using a powershell session, it is easy to automate even that step:

    $env:Path = ( stack setup | %{ $_ -replace '[^ ]+ ', ''} ), $env:Path -join ";"

## How do I reset / remove Stack (such as to to do a completely fresh build)?

The first thing to remove is project-specific `.stack-work` directory within the project's directory. Next, remove `~/.stack` directory overall. You may have errors if you remove the latter but leave the former. Removing Stack itself will relate to how it was installed, and if you used GHC installed outside of Stack, that would need to be removed separately.

## How does stack handle parallel builds? What exactly does it run in parallel?

See [issue #644](https://github.com/commercialhaskell/stack/issues/644) for more details.

## I get strange `ld` errors about recompiling with "-fPIC"

Some users (myself included!) have come across a linker errors (example below) that seem to be dependent on the local environment, i.e. the package may compile on a different machine. The issue has been reported to be [non-deterministic](https://github.com/commercialhaskell/stack/issues/614) in some cases. I've had success using the docker functionality to build the project on a machine that would not compile it otherwise.

```
tmp-0.1.0.0: build
Building tmp-0.1.0.0...
Preprocessing executable 'tmp' for tmp-0.1.0.0...
Linking dist-stack/x86_64-linux/Cabal-1.22.2.0/build/tmp/tmp ...
/usr/bin/ld: dist-stack/x86_64-linux/Cabal-1.22.2.0/build/tmp/tmp-tmp/Main.o: relocation R_X86_64_32S against `stg_bh_upd_frame_info' can not be used when making a shared object; recompile with -fPIC
dist-stack/x86_64-linux/Cabal-1.22.2.0/build/tmp/tmp-tmp/Main.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

--  While building package tmp-0.1.0.0 using:
      /home/philip/.stack/programs/x86_64-linux/ghc-7.10.1/bin/runghc-7.10.1 -package=Cabal-1.22.2.0 -clear-package-db -global-package-db /home/philip/tmp/Setup.hs --builddir=dist-stack/x86_64-linux/Cabal-1.22.2.0/ build
    Process exited with code: ExitFailure 1
```

The issue may be related to the use of hardening flags in some cases, specifically those related to producing position independent executables (PIE). This is tracked upstream in the [following ticket](https://ghc.haskell.org/trac/ghc/ticket/9007). Some distributions add such hardening flags by default which may be the cause of some instances of the problem. Therefore, a possible workaround might be to turn off PIE related flags.

In Arch Linux, the support for this is provided by the `hardening-wrapper` package. Some possible workarounds:

* Selectively disabling its PIE forcing by setting `HARDENING_PIE=0` in `/etc/hardening-wrapper.conf`.
* Uninstalling the `hardening-wrapper` package and logging out then into your account again.

If you manage to work around this in other distributions, please include instructions here.

## Where does the output from `--ghc-options=-ddump-splices` (and other `-ddump*` options) go?

These are written to `*.dump-*` files inside the package's `.stack-work` directory.

## Why is DYLD_LIBRARY_PATH ignored?

If you are on Mac OS X 10.11 ("El Capitan") or later, there is an
[upstream GHC issue](https://ghc.haskell.org/trac/ghc/ticket/11617)
which
[prevents the `DYLD_LIBRARY_PATH` environment variable from being passed to GHC](https://github.com/commercialhaskell/stack/issues/1161)
when System Integrity Protection (a.k.a. "rootless") is enabled. There are two
known workarounds:

 1. Known to work in all cases: [disable System Integrity Protection](http://osxdaily.com/2015/10/05/disable-rootless-system-integrity-protection-mac-os-x/).  **WARNING: Disabling SIP will severely reduce the security of your system, so only do this if absolutely necessary!**
 2. Experimental: [modify GHC's shell script wrappers to use a shell outside the protected directories](https://github.com/commercialhaskell/stack/issues/1161#issuecomment-186690904).

## Why do I get a `/usr/bin/ar: permission denied` error?

If you are on OS X 10.11 ("El Capitan") or
later, GHC 7.8.4 is
[incompatible with System Integrity Protection (a.k.a. "rootless")](https://github.com/commercialhaskell/stack/issues/563).
GHC 7.10.2 includes a fix, so this only affects users of GHC 7.8.4. If you
cannot upgrade to GHC 7.10.2, you can work around it by
[disabling System Integrity Protection](http://osxdaily.com/2015/10/05/disable-rootless-system-integrity-protection-mac-os-x/).  **WARNING: Disabling SIP will severely reduce the security of your system, so only do this if absolutely necessary!**

## Why is the `--` argument separator ignored in Windows PowerShell

Some versions of Windows PowerShell
[don't pass the `--` to programs](https://github.com/commercialhaskell/stack/issues/813).
The workaround is to quote the `"--"`, e.g.:

    stack exec "--" cabal --version

This is known to be a problem on Windows 7, but seems to be fixed on Windows 10.

## Does stack also install the system/C libraries that some Cabal packages depend on?

No, this is currently out of the scope of stack's target set of features.
Instead of attempting to automate the installation of 3rd party dependencies, we
have the following approaches for handling system dependencies:

* Nix and docker help make your build and execution environment deterministic
  and predictable. This way, you can install system dependencies into a
  container, and share this container with all developers.

* If you have installed some libraries into a non-standard location,
  [`extra-lib-dirs` / `extra-include-dirs`](yaml_configuration.md#extra-include-dirsextra-lib-dirs)
  to specify it.

In the future, stack might give OS specific suggestions for how to install
system libraries.

## How can I make `stack` aware of my custom SSL certificates?

### OS X

In principle, you can use the following command to add a certificate to your system certificate keychain:

    sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain <certificate>

Some users have reported issues with this approach, see [#907](https://github.com/commercialhaskell/stack/issues/907) for more information.

### Other *NIX OSs

Use the `SYSTEM_CERTIFICATE_PATH` environment variable to point at the directory
where you keep your SSL certificates.


text:
package cf

import (
	"fmt"
	"sort"
	"strings"

	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/urfave/cli"

	"github.com/sam701/awstools/printer"
	"github.com/sam701/tcolor"
)

type stackPrintOptions struct {
	printParameters bool
	printOutputs    bool
	printResources  bool
	printTags       bool

	resourceTypes []string
}

func createPrintOptions(ctx *cli.Context) *stackPrintOptions {
	return &stackPrintOptions{
		printParameters: ctx.Bool("print-parameters"),
		printOutputs:    ctx.Bool("print-outputs"),
		printTags:       ctx.Bool("print-tags"),
		printResources:  ctx.Bool("print-resources"),

		resourceTypes: ctx.StringSlice("resource-type"),
	}
}

var (
	colorStack        = tcolor.New().Foreground(tcolor.BrightWhite).Bold()
	colorStackRef     = tcolor.New().Foreground(tcolor.Cyan).Italic()
	colorSection      = tcolor.New().Foreground(tcolor.Yellow).Underline()
	colorResourceType = tcolor.New().Foreground(tcolor.Magenta)
)

func printStacks(stacks []*cloudformation.Stack, options *stackPrintOptions) {
	if len(options.resourceTypes) > 0 {
		printResourceTypes(stacks, options.resourceTypes)
		return
	}

	for i, stack := range stacks {
		fmt.Println(tcolor.Colorize(*stack.StackName, colorStack))

		if options.printTags {
			fmt.Println(" ", tcolor.Colorize("Tags", colorSection))
			pairs := []string{}
			for _, tag := range stack.Tags {
				pairs = append(pairs, *tag.Key, *tag.Value)
			}
			printer.PrintProperties(4, pairs...)
		}

		if options.printParameters {
			fmt.Println(" ", tcolor.Colorize("Parameters", colorSection))
			pairs := []string{}
			for _, par := range stack.Parameters {
				pairs = append(pairs, *par.ParameterKey, *par.ParameterValue)
			}
			printer.PrintProperties(4, pairs...)
		}

		if options.printOutputs {
			fmt.Println(" ", tcolor.Colorize("Outputs", colorSection))
			pairs := []string{}
			for _, output := range stack.Outputs {
				pairs = append(pairs, *output.OutputKey, *output.OutputValue)
			}
			printer.PrintProperties(4, pairs...)
		}

		if options.printResources {
			fmt.Println(" ", tcolor.Colorize("Resources", colorSection))
			res := getStackResources(*stack.StackName, []string{})
			lastType := ""
			for _, r := range res {
				if lastType != *r.ResourceType {
					fmt.Println("   ", tcolor.Colorize(*r.ResourceType, colorResourceType))
				}
				printStackResource(6, r)
				lastType = *r.ResourceType
			}
		}

		if i < len(stacks)-1 {
			if options.printOutputs || options.printParameters || options.printTags || options.printResources {
				fmt.Println("")
			}
		}
	}
}

func printStackResource(indent int, resource *cloudformation.StackResourceSummary) {
	fmt.Print(strings.Repeat(" ", indent))
	fmt.Println(*resource.PhysicalResourceId)
}

func printResourceTypes(stacks []*cloudformation.Stack, resourceTypes []string) {
	type resource struct {
		summary   *cloudformation.StackResourceSummary
		stackName string
	}
	res := []*resource{}

	for _, stack := range stacks {
		r := getStackResources(*stack.StackName, resourceTypes)
		for _, rs := range r {
			res = append(res, &resource{rs, *stack.StackName})
		}
	}

	sort.Slice(res, func(a, b int) bool {
		ra := *res[a].summary.ResourceType
		rb := *res[b].summary.ResourceType
		if ra == rb {
			return *res[a].summary.PhysicalResourceId < *res[b].summary.PhysicalResourceId
		}
		return ra < rb
	})

	lastType := ""
	for _, r := range res {
		if lastType != *r.summary.ResourceType {
			fmt.Println(tcolor.Colorize(*r.summary.ResourceType, colorResourceType))
		}
		fmt.Printf("  %s (%s)\n", *r.summary.PhysicalResourceId,
			tcolor.Colorize(r.stackName, colorStackRef))

		lastType = *r.summary.ResourceType
	}

}


text:
import {render} from '@testing-library/preact';
import {FunctionComponent} from 'preact';

import {I18nProvider} from '../../src/i18n/i18n';
import {SidebarHeader, SidebarRuntimeSettings, SidebarSummary} from '../../src/sidebar/sidebar';
import {FlowResultContext} from '../../src/util';
import {flowResult} from '../sample-flow';

let wrapper: FunctionComponent;

beforeEach(() => {
  wrapper = ({children}) => (
    <FlowResultContext.Provider value={flowResult}>
      <I18nProvider>
        {children}
      </I18nProvider>
    </FlowResultContext.Provider>
  );
});

describe('SidebarHeader', () => {
  it('renders title content', async () => {
    const title = 'Lighthouse flow report';
    const date = '2021-08-03T18:28:13.296Z';
    const root = render(<SidebarHeader title={title} date={date}/>, {wrapper});

    expect(root.getByText(title)).toBeTruthy();
    expect(root.getByText('Aug 3, 2021, 6:28 PM UTC')).toBeTruthy();
  });
});

describe('SidebarSummary', () => {
  it('highlighted by default', async () => {
    const root = render(<SidebarSummary/>, {wrapper});
    const link = root.getByRole('link') as HTMLAnchorElement;

    expect(link.href).toEqual('file:///Users/example/report.html/#');
    expect(link.classList).toContain('Sidebar--current');
  });
});

describe('SidebarRuntimeSettings', () => {
  it('displays default runtime settings', async () => {
    const settings = {
      formFactor: 'mobile',
      throttlingMethod: 'simulate',
      throttling: {
        cpuSlowdownMultiplier: 4,
        requestLatencyMs: 150 * 3.75,
        downloadThroughputKbps: 1.6 * 1024 * 0.9,
        uploadThroughputKbps: 750 * 0.9,
        throughputKbps: 1.6 * 1024,
        rttMs: 150,
      },
      screenEmulation: {disabled: true},
    } as any;
    const root = render(<SidebarRuntimeSettings settings={settings}/>, {wrapper});

    expect(root.getByText('Emulated Moto G4')).toBeTruthy();
    expect(root.queryByText('Emulated Moto G4 -')).toBeFalsy();
    expect(root.getByText('Slow 4G throttling')).toBeTruthy();
    expect(root.getByText('4x slowdown'));
  });

  it('displays custom runtime settings', async () => {
    const settings = {
      formFactor: 'desktop',
      throttlingMethod: 'devtools',
      throttling: {
        cpuSlowdownMultiplier: 1,
        requestLatencyMs: 1,
        downloadThroughputKbps: 1,
        uploadThroughputKbps: 1,
        throughputKbps: 1,
        rttMs: 1,
      },
      screenEmulation: {
        width: 100,
        height: 100,
        deviceScaleFactor: 2,
      },
    } as any;
    const root = render(<SidebarRuntimeSettings settings={settings}/>, {wrapper});

    expect(root.getByText('Emulated Desktop - 100x100, DPR 2')).toBeTruthy();
    expect(root.getByText('Custom throttling')).toBeTruthy();
    expect(root.getByText('1x slowdown'));
  });
});


text:
@implementation UIApplication (YBTools)

+ (UIViewController *)visibleViewController
{
    UIViewController *viewController = UIApplication.sharedApplication.delegate.window.rootViewController;
    return [self topViewController:viewController];
}

+ (UIViewController *)topViewController:(UIViewController *)parent {
    if (parent.presentedViewController) {
        return [self topViewController:parent.presentedViewController];
    }

    if ([parent isKindOfClass:UINavigationController.class]) {
        return [self topViewController:[(UINavigationController*)parent topViewController]];
    }

    if ([parent isKindOfClass:UITabBarController.class]) {
        return [self topViewController:[(UITabBarController*)parent selectedViewController]];
    }

    return parent;
}
@end


text:
package com.soebes.maven.extensions;

/**
 * @author Karl Heinz Marbaise kama@soebes.de
 */
class ProjectGoal
{
    private final ProjectKey project;

    private final GoalKey mojo;

    public ProjectGoal( ProjectKey project, GoalKey mojo )
    {
        super();
        this.project = project;
        this.mojo = mojo;
    }

    public ProjectKey getProject()
    {
        return project;
    }

    public GoalKey getMojo()
    {
        return mojo;
    }

    @Override
    public final int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ( ( mojo == null ) ? 0 : mojo.hashCode() );
        result = prime * result + ( ( project == null ) ? 0 : project.hashCode() );
        return result;
    }

    public String getId()
    {
        return getMojo().getGroupId() + ":" + getMojo().getArtifactId() + ":" + getMojo().getVersion() + ":"
            + getMojo().getGoal() + " (" + getMojo().getExecutionId() + ")";
    }

    @Override
    public final boolean equals( Object obj )
    {
        if ( this == obj )
        {
            return true;
        }
        if ( obj == null )
        {
            return false;
        }
        if ( !( obj instanceof ProjectGoal ) )
        {
            return false;
        }
        ProjectGoal other = (ProjectGoal) obj;
        if ( mojo == null )
        {
            if ( other.mojo != null )
            {
                return false;
            }
        }
        else if ( !mojo.equals( other.mojo ) )
        {
            return false;
        }
        if ( project == null )
        {
            if ( other.project != null )
            {
                return false;
            }
        }
        else if ( !project.equals( other.project ) )
        {
            return false;
        }
        return true;
    }

}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Runtime.Remoting.Metadata.W3cXsd2001
{
  sealed public partial class SoapName : ISoapXsd
  {
    #region Methods and constructors
    public string GetXsdType()
    {
      return default(string);
    }

    public static System.Runtime.Remoting.Metadata.W3cXsd2001.SoapName Parse(string value)
    {
      Contract.Ensures(Contract.Result<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapName>() != null);

      return default(System.Runtime.Remoting.Metadata.W3cXsd2001.SoapName);
    }

    public SoapName()
    {
    }

    public SoapName(string value)
    {
    }

    public override string ToString()
    {
      return default(string);
    }
    #endregion

    #region Properties and indexers
    public string Value
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public static string XsdType
    {
      get
      {
        Contract.Ensures(Contract.Result<string>() != null);
        Contract.Ensures(Contract.Result<string>() == @"Name");

        return default(string);
      }
    }
    #endregion
  }
}


text:
package org.kie.integration.testcoverage.instrumentation.model;

/**
 * A person's pet.
 */
public interface Pet {

    String getName();

    int getAge();

    void setAge(final int age);
}


text:
package pl.edu.uwb.mobiuwb.configuration;

public interface ConfigureEvents
{
    void onConfigurationFinished(boolean succeeded);
}


text:
Adds a `DropdownImageField` field which enables you to display images alongside the captions.
Uses a plugin for Chosen.js (which is used by SS), [Image-Select](https://github.com/websemantics/Image-Select). The plugin is modified.

![Working screenshot](https://github.com/fullscreeninteractive/silverstripe-dropdownimagefield/raw/master/docs/img/ss.png)

## Requirements

SilverStripe 4.0+

## Usage

Example:

```php
DropdownImageField::create('LanguageID', 'Select language',
	LanguageObj::get(), // Source for items.
	'ID',		// Key field on item.
	'Title',	// Caption field on item.
	'Icon'		// Image field on item. Can be a method/relation that returns an image.
)
```

## Notes

This plugin uses a `setTimeout` function with additional parameters. A polyfill is loaded to support IE9 and lower.


text:
require 'test_helper'

class TimeSheetTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WATF.Plugin.HPST.Assert
{
    public class Contain : WATF.Plugin.HPST.Assert.Base, WATF.Plugin.IPlugin
    {
        public object StartMethod(object parent = null, Dictionary<string, object> parameters = null)
        {
            //throw new NotImplementedException();
            if (!parameters.ContainsKey("Contain")) throw new ArgumentNullException("Contain");
            string contain = (string)parameters["Contain"];
            string key = (string)parent;
            if (!key.Contains(contain))
            {
                string message = parameters.ContainsKey("Message") ? (string)parameters["Message"] : "";
                base.AddReport(0, message, parent.ToString(), contain.ToString());
            }
            return default(object);
        }

        public void EndMethod()
        {
            //throw new NotImplementedException();
        }
    }
}


text:
<link rel="stylesheet" type="text/css" href="../../css/vivian.css"/>
<link rel="stylesheet" type="text/css" href="../../datatable/css/jquery.dataTables.css"/>
<link rel="stylesheet" type="text/css" href="../../datatable/css/buttons.dataTables.css"/>
<link rel="stylesheet" type="text/css" href="../../datatable/css/dataTables.searchHighlight.css"/>

All ICR List

Package: Registration ICR List

IA #
Name
Type
Custodial Package
Date Created
DBIC Approval Status
Status
Usage
File #
General Description
Remote Procedure
Routine
Date Activated

IA #
Name
Type
Custodial Package
Date Created
DBIC Approval Status
Status
Usage
File #
General Description
Remote Procedure
Routine
Date Activated

28
DBIA28
Routine
REGISTRATION
1989/03/21

Retired
Private

*****TEMPORARY SUPPORTED CALL FOR IFCAP V2 TEST SITES
ONLY*****
call to ZIS^DGUTL

DGUTL

4849
<a title=" For the PFSS project, which includes a number of VistA application packages, structures are setup for HL7 communication between VistA and an external COTS system for patient billing.
 Most inbound HL7 messages are being received for processing by the REGISTRATION package (DG), but two specific messages (ADT-A05 and ADT-A04) must be processed only by the INTEGRATED BILLING package within the new IBB module for PFSS.
 The IBB receivers use four PROTOCOLS (file #101) in order to route the ADT-A05 and ADT-A04 to the processing routine.  Since the COTS system will only use the HL7 APPLICATION PARAMETER (file #771) names setup for the DG application in their MSH segments, the IBB Protocols must be pointed to these file #771 entries.
 This IA allows the four IBB Protocols to utilize the DG Application Parameters DGPFSS ADT RECV and DGPFSS ADT SENDING as follows:
 NAME: IBB PFSS ADT-A04 CLIENT           TYPE: subscriber RECEIVING APPLICATION: DGPFSS ADT RECV EVENT TYPE: A04                       RESPONSE MESSAGE TYPE: ADT PROCESSING ROUTINE: D A04^IBBAADTI    SENDING FACILITY REQUIRED?: NO RECEIVING FACILITY REQUIRED?: NO
 NAME: IBB PFSS ADT-A04 SERVER           ITEM TEXT: PFSS/IBB ADT-A04 Receiver TYPE: event driver SENDING APPLICATION: DGPFSS ADT SENDING TRANSACTION MESSAGE TYPE: ADT         EVENT TYPE: A04 MESSAGE STRUCTURE: ACK                ACCEPT ACK CODE: AL APPLICATION ACK TYPE: AL              VERSION ID: 2.4 SUBSCRIBERS: IBB PFSS ADT-A04 CLIENT
 NAME: IBB PFSS ADT-A05 CLIENT           TYPE: subscriber RECEIVING APPLICATION: DGPFSS ADT RECV EVENT TYPE: A05                       RESPONSE MESSAGE TYPE: ADT PROCESSING ROUTINE: D A05^IBBAADTI    SENDING FACILITY REQUIRED?: NO RECEIVING FACILITY REQUIRED?: NO
 NAME: IBB PFSS ADT-A05 SERVER           ITEM TEXT: PFSS/IBB ADT-A05 Receiver TYPE: event driver SENDING APPLICATION: DGPFSS ADT SENDING TRANSACTION MESSAGE TYPE: ADT         EVENT TYPE: A05 ACCEPT ACK CODE: AL                   APPLICATION ACK TYPE: AL VERSION ID: 2.4
" href="https://code.osehra.org/vivian/files/ICR/ICR-4849.html">DBIA #4849
Other
REGISTRATION
2006/04/20
APPROVED
Active
Private
771

For the PFSS project, which includes a number of VistA
application packages, structures are setup for HL7 communication between VistA
and an external COTS system for patient billing.

Most inbound HL7 messages are being received for processing by the
REGISTRATION package (DG), but two specific messages (ADT-A05 and ADT-A04)
must be processed only by the INTEGRATED BILLING package within the new IBB
module for PFSS.

The IBB receivers use four PROTOCOLS (file #101) in order to route the ADT-A05
and ADT-A04 to the processing routine.  Since the COTS system will only use
the HL7 APPLICATION PARAMETER (file #771) names setup for the DG application
in their MSH segments, the IBB Protocols must be pointed to these file #771
entries.

This IA allows the four IBB Protocols to utilize the DG Application Parameters
DGPFSS ADT RECV and DGPFSS ADT SENDING as follows:

NAME: IBB PFSS ADT-A04 CLIENT           TYPE: subscriber
RECEIVING APPLICATION: DGPFSS ADT RECV
EVENT TYPE: A04                       RESPONSE MESSAGE TYPE: ADT
PROCESSING ROUTINE: D A04^IBBAADTI    SENDING FACILITY REQUIRED?: NO
RECEIVING FACILITY REQUIRED?: NO

NAME: IBB PFSS ADT-A04 SERVER           ITEM TEXT: PFSS/IBB ADT-A04 Receiver
TYPE: event driver
SENDING APPLICATION: DGPFSS ADT SENDING
TRANSACTION MESSAGE TYPE: ADT         EVENT TYPE: A04
MESSAGE STRUCTURE: ACK                ACCEPT ACK CODE: AL
APPLICATION ACK TYPE: AL              VERSION ID: 2.4 SUBSCRIBERS: IBB PFSS
ADT-A04 CLIENT

NAME: IBB PFSS ADT-A05 CLIENT           TYPE: subscriber
RECEIVING APPLICATION: DGPFSS ADT RECV
EVENT TYPE: A05                       RESPONSE MESSAGE TYPE: ADT
PROCESSING ROUTINE: D A05^IBBAADTI    SENDING FACILITY REQUIRED?: NO
RECEIVING FACILITY REQUIRED?: NO

NAME: IBB PFSS ADT-A05 SERVER           ITEM TEXT: PFSS/IBB ADT-A05 Receiver
TYPE: event driver
SENDING APPLICATION: DGPFSS ADT SENDING
TRANSACTION MESSAGE TYPE: ADT         EVENT TYPE: A05
ACCEPT ACK CODE: AL                   APPLICATION ACK TYPE: AL
VERSION ID: 2.4

10035
PATIENT FILE
File
REGISTRATION
2017/09/13
APPROVED
Active
Supported
2

Any nationally released cross-reference on the
supported fields in this Integration Agreement are "open/supported" for direct
global reference (as well as reference through VA FileMan).

2011/05/24

Generated from JAN 29,2016 IA Listing Descriptions


text:
#ifndef INCLUDE_cache_h__
#define INCLUDE_cache_h__

#include "common.h"

#include "git2/common.h"
#include "git2/oid.h"
#include "git2/odb.h"

#include "thread-utils.h"
#include "oidmap.h"

enum {
	GIT_CACHE_STORE_ANY = 0,
	GIT_CACHE_STORE_RAW = 1,
	GIT_CACHE_STORE_PARSED = 2
};

typedef struct {
	git_oid    oid;
	int16_t    type;  /* git_otype value */
	uint16_t   flags; /* GIT_CACHE_STORE value */
	size_t     size;
	git_atomic refcount;
} git_cached_obj;

typedef struct {
	git_oidmap *map;
	git_rwlock  lock;
	ssize_t     used_memory;
} git_cache;

extern bool git_cache__enabled;
extern ssize_t git_cache__max_storage;
extern git_atomic_ssize git_cache__current_storage;

int git_cache_set_max_object_size(git_otype type, size_t size);

int git_cache_init(git_cache *cache);
void git_cache_free(git_cache *cache);
void git_cache_clear(git_cache *cache);

void *git_cache_store_raw(git_cache *cache, git_odb_object *entry);
void *git_cache_store_parsed(git_cache *cache, git_object *entry);

git_odb_object *git_cache_get_raw(git_cache *cache, const git_oid *oid);
git_object *git_cache_get_parsed(git_cache *cache, const git_oid *oid);
void *git_cache_get_any(git_cache *cache, const git_oid *oid);

GIT_INLINE(size_t) git_cache_size(git_cache *cache)
{
	return (size_t)git_oidmap_size(cache->map);
}

GIT_INLINE(void) git_cached_obj_incref(void *_obj)
{
	git_cached_obj *obj = _obj;
	git_atomic_inc(&obj->refcount);
}

void git_cached_obj_decref(void *_obj);

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Gaming.Input;

namespace Cica4WD
{
    /// <summary>
    /// 既定の Application クラスを補完するアプリケーション固有の動作を提供します。
    /// </summary>
    sealed partial class App : Application
    {
        public static Gamepad GameController { get; private set; }

        public static IList<Gamepad> Gamepads { get; } = new List<Gamepad>();
        public static event EventHandler<Gamepad> AddedGamepad;
        public static event EventHandler<Gamepad> RemovedGamepad;

        /// <summary>
        /// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの
        ///最初の行であるため、main() または WinMain() と論理的に等価です。
        /// </summary>
        public App()
        {
            Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
                Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
                Microsoft.ApplicationInsights.WindowsCollectors.Session);
            this.InitializeComponent();
            Gamepad.GamepadAdded += (s, e) =>
            {
                Gamepads.Add(e);

                AddedGamepad?.Invoke(this, e);
            };
            Gamepad.GamepadRemoved += (s, e) =>
            {
                if (Gamepads.Any(i => i == e))
                {
                    Gamepads.Remove(e);
                }

                RemovedGamepad?.Invoke(this, e);
            };
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ ポイントは、
        /// アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。
        /// </summary>
        /// <param name="e">起動の要求とプロセスの詳細を表示します。</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            Frame rootFrame = Window.Current.Content as Frame;

            // ウィンドウに既にコンテンツが表示されている場合は、アプリケーションの初期化を繰り返さずに、
            // ウィンドウがアクティブであることだけを確認してください
            if (rootFrame == null)
            {
                // ナビゲーション コンテキストとして動作するフレームを作成し、最初のページに移動します
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: 以前中断したアプリケーションから状態を読み込みます
                }

                // フレームを現在のウィンドウに配置します
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // ナビゲーション スタックが復元されない場合は、最初のページに移動します。
                    // このとき、必要な情報をナビゲーション パラメーターとして渡して、新しいページを
                    //構成します
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // 現在のウィンドウがアクティブであることを確認します
                Window.Current.Activate();
            }
        }

        /// <summary>
        /// 特定のページへの移動が失敗したときに呼び出されます
        /// </summary>
        /// <param name="sender">移動に失敗したフレーム</param>
        /// <param name="e">ナビゲーション エラーの詳細</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// アプリケーションの実行が中断されたときに呼び出されます。
        /// アプリケーションが終了されるか、メモリの内容がそのままで再開されるかに
        /// かかわらず、アプリケーションの状態が保存されます。
        /// </summary>
        /// <param name="sender">中断要求の送信元。</param>
        /// <param name="e">中断要求の詳細。</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: アプリケーションの状態を保存してバックグラウンドの動作があれば停止します
            deferral.Complete();
        }
    }
}


text:
package org.opentides.persistence;

import java.util.List;

import org.opentides.bean.user.BaseUser;

/**
 * This is the DAO for users and permissions.
 * @author allanctan
 */
public interface UserDAO extends BaseEntityDAO<BaseUser, Long> {
	public boolean isRegisteredByEmail(String emailAddress);
	public BaseUser loadByUsername(String username);
	public BaseUser loadByEmailAddress(String emailAddress);
	public List<BaseUser> findByUsergroupName(String userGroupName);
	public void updateLastLogin(String username);
}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      {{'app_name'|translate}}

           {{item.title}}

        <button type="button" class="btn btn-success dropdown-toggle" dropdown-toggle ng-disabled="disabled">
          {{helloTip}}
        </button>

 编辑资料

 退出系统