text:
title: Typography
---

    # Headers

h1. Vestibulum ante ipsum primis in

h2. Vestibulum ante ipsum primis in

h3. Vestibulum ante ipsum primis in

h4. Vestibulum ante ipsum primis in

h5. Vestibulum ante ipsum primis in

h6. Vestibulum ante ipsum primis in

    # Paragraphs

Aenean vulputate eleifend tellus. Vestibulum dapibus nunc ac augue. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.
            Nulla
            facilisi. Pellentesque auctor neque nec urna.

 Nulla consequat massa quis enim. Vivamus laoreet. Donec posuere vulputate arcu. Ut non enim eleifend felis pretium feugiat.
            Praesent nonummy mi in odio. Phasellus volutpat, metus eget egestas mollis, lacus lacus blandit dui, id egestas quam mauris ut lacus.
            Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In dui magna, posuere eget, vestibulum et, tempor auctor, justo.
            Maecenas egestas arcu quis ligula mattis placerat.

    # Lists

Aenean vulputate eleifend tellus. Vestibulum dapibus nunc ac augue.

 Nulla consequat massa quis enim. Vivamus laoreet. Donec posuere vulputate arcu.

Curabitur ligula sapien tincidunt non

Nunc egestas augue at pellentesque

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus.

Phasellus accumsan cursus velit.

    List unstyled

Aenean vulputate eleifend tellus.

Curabitur ligula sapien tincidunt non.

Nunc egestas augue at pellentesque.

List inline

a) Aenean vulputate eleifend tellus.

b) Curabitur ligula sapien tincidunt non.

c) Nunc egestas augue at pellentesque.

List as path

                Home page

                First subpage

                Second subpage

Description list

Aenean vulputate eleifend tellus.

Duis lobortis massa imperdiet quam

Maecenas nec odio et ante

Curabitur ligula sapien tincidunt non.

Suspendisse enim turpis dictum sed

Nunc egestas augue at pellentesque.

Donec vitae sapien ut libero

    Separators in lists

Aenean vulputate eleifend tellus.

Curabitur ligula sapien tincidunt non.

Nunc egestas augue at pellentesque.

Aenean vulputate eleifend tellus.

Curabitur ligula sapien tincidunt non.

Nunc egestas augue at pellentesque.

Aenean vulputate eleifend tellus.

Curabitur ligula sapien tincidunt non.

Nunc egestas augue at pellentesque.

Aenean vulputate eleifend tellus.

Curabitur ligula sapien tincidunt non.

Nunc egestas augue at pellentesque.


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using NUnit.Framework;

namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests
{
	[TestFixture]
	public class GenerateInsertsForSqlServerTests
	{
		public struct Customer
		{
			public int? CustomerId;
			public string FirstName;
			public string LastName;
			public DateTime DateOfBirth;
		}

		[Test]
		public void Should_Return_The_Last_Inserted_Ids()
		{
			// Arrange
			const string sql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( sql )
				.ExecuteNonQuery( true );

			var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<Customer> { customer1, customer2, customer3 };

			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list )
				.ExecuteToList<long>();

			// Assert
			Assert.That( customerIds.Count == 3 );
			Assert.That( customerIds[0] == 1 );
			Assert.That( customerIds[1] == 2 );
			Assert.That( customerIds[2] == 3 );
		}

		[Test]
		public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object()
		{
			// Arrange
			const string createSchemaSql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( createSchemaSql )
				.ExecuteNonQuery( true );

			var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<Customer> { customer1, customer2, customer3 };

			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list )
				.ExecuteToList<long>( true );

			const string selectCustomerQuery = @"
SELECT  CustomerId,
		FirstName,
		LastName,
		DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

			var customers = new DatabaseCommand( dbConnection )
				.SetCommandText( selectCustomerQuery )
				.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
				.ExecuteToList<Customer>()
				.OrderBy( x => x.CustomerId )
				.ToList();

			// Assert
			Assert.That( customers.Count == 3 );

			Assert.That( customers[0].CustomerId == 1 );
			Assert.That( customers[0].FirstName == customer1.FirstName );
			Assert.That( customers[0].LastName == customer1.LastName );
			Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );

			Assert.That( customers[1].CustomerId == 2 );
			Assert.That( customers[1].FirstName == customer2.FirstName );
			Assert.That( customers[1].LastName == customer2.LastName );
			Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );

			Assert.That( customers[2].CustomerId == 3 );
			Assert.That( customers[2].FirstName == customer3.FirstName );
			Assert.That( customers[2].LastName == customer3.LastName );
			Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
		}

		[Test]
		public void Should_Be_Able_To_Specify_The_Table_Name()
		{
			// Arrange
			const string sql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Person' ) )
BEGIN

	DROP TABLE Person

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Person') )
BEGIN

	CREATE TABLE Person
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( sql )
				.ExecuteNonQuery( true );

			var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<Customer> { customer1, customer2, customer3 };

			// Act
			var numberOfAffectedRecords = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list, "[Person]" ) // Specifying a table name of Person
				.ExecuteNonQuery( true );

			// Assert
			Assert.That( numberOfAffectedRecords == list.Count );
		}

		[Test]
		public void Should_Throw_An_Exception_When_Passing_An_Anonymous_Object_And_Not_Specifying_A_TableName()
		{
			// Arrange
			const string sql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Person' ) )
BEGIN

	DROP TABLE Person

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Person') )
BEGIN

	CREATE TABLE Person
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( sql )
				.ExecuteNonQuery( true );

			var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<object> { customer1, customer2, customer3 };

			// Act
			TestDelegate action = () => new DatabaseCommand( dbConnection )
                .GenerateInsertsForSqlServer( list )
				.ExecuteScalar( true )
				.ToInt();

			// Assert
			var exception = Assert.Catch<ArgumentNullException>( action );
			Assert.That( exception.Message.Contains( "The 'tableName' parameter must be provided when the object supplied is an anonymous type." ) );
		}

		[Test]
		public void Should_Handle_Generating_Inserts_For_An_Anonymous_Object()
		{
			// Arrange
			const string createSchemaSql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( createSchemaSql )
				.ExecuteNonQuery( true );

			var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
			var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
			var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
			var list = new List<object> { customer1, customer2, customer3 };

			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list, "Customer" )
				.ExecuteToList<long>( true );

			const string selectCustomerQuery = @"
SELECT  CustomerId,
		FirstName,
		LastName,
		DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

			var customers = new DatabaseCommand( dbConnection )
				.SetCommandText( selectCustomerQuery )
				.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
				.ExecuteToList<Customer>()
				.OrderBy( x => x.CustomerId )
				.ToList();

			// Assert
			Assert.That( customers.Count == 3 );

			Assert.That( customers[0].CustomerId == 1 );
			Assert.That( customers[0].FirstName == customer1.FirstName );
			Assert.That( customers[0].LastName == customer1.LastName );
			Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );

			Assert.That( customers[1].CustomerId == 2 );
			Assert.That( customers[1].FirstName == customer2.FirstName );
			Assert.That( customers[1].LastName == customer2.LastName );
			Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );

			Assert.That( customers[2].CustomerId == 3 );
			Assert.That( customers[2].FirstName == customer3.FirstName );
			Assert.That( customers[2].LastName == customer3.LastName );
			Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
		}

		[Test]
		public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object()
		{
			// Arrange
			const string createSchemaSql = @"
IF ( EXISTS (	SELECT	*
				FROM	INFORMATION_SCHEMA.TABLES
				WHERE	TABLE_SCHEMA = 'dbo'
						AND	TABLE_NAME = 'Customer' ) )
BEGIN

	DROP TABLE Customer

END

IF ( NOT EXISTS (	SELECT	*
					FROM	INFORMATION_SCHEMA.TABLES
					WHERE	TABLE_SCHEMA = 'dbo'
							AND	TABLE_NAME = 'Customer') )
BEGIN

	CREATE TABLE Customer
	(
		CustomerId      INT             NOT NULL    IDENTITY(1,1)   PRIMARY KEY,
		FirstName       NVARCHAR(120)   NOT NULL,
		LastName        NVARCHAR(120)   NOT NULL,
		DateOfBirth     DATETIME        NOT NULL
	);

END
";

			var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );

			new DatabaseCommand( dbConnection )
				.SetCommandText( createSchemaSql )
				.ExecuteNonQuery( true );

			dynamic customer1 = new ExpandoObject();
			customer1.FirstName = "Clark";
			customer1.LastName = "Kent";
			customer1.DateOfBirth = DateTime.Parse( "06/18/1938" );

			dynamic customer2 = new ExpandoObject();
			customer2.FirstName = "Bruce";
			customer2.LastName = "Wayne";
			customer2.DateOfBirth = DateTime.Parse( "05/27/1939" );

			dynamic customer3 = new ExpandoObject();
			customer3.FirstName = "Peter";
			customer3.LastName = "Parker";
			customer3.DateOfBirth = DateTime.Parse( "08/18/1962" );

			var list = new List<dynamic> { customer1, customer2, customer3 };

			// Act
			var customerIds = new DatabaseCommand( dbConnection )
				.GenerateInsertsForSqlServer( list, "Customer" )
				.ExecuteToList<long>( true );

			const string selectCustomerQuery = @"
SELECT  CustomerId,
		FirstName,
		LastName,
		DateOfBirth
FROM    Customer
WHERE   CustomerId IN ( @CustomerIds );
";

			var customers = new DatabaseCommand( dbConnection )
				.SetCommandText( selectCustomerQuery )
				.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
				.ExecuteToList<Customer>()
				.OrderBy( x => x.CustomerId )
				.ToList();

			// Assert
			Assert.That( customers.Count == 3 );

			Assert.That( customers[0].CustomerId == 1 );
			Assert.That( customers[0].FirstName == customer1.FirstName );
			Assert.That( customers[0].LastName == customer1.LastName );
			Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );

			Assert.That( customers[1].CustomerId == 2 );
			Assert.That( customers[1].FirstName == customer2.FirstName );
			Assert.That( customers[1].LastName == customer2.LastName );
			Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );

			Assert.That( customers[2].CustomerId == 3 );
			Assert.That( customers[2].FirstName == customer3.FirstName );
			Assert.That( customers[2].LastName == customer3.LastName );
			Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "qvariant.h"

#include "qbitmap.h"
#include "qbrush.h"
#include "qcolor.h"
#include "qcursor.h"
#include "qdatastream.h"
#include "qdebug.h"
#include "qfont.h"
#include "qicon.h"
#include "qimage.h"
#include "qkeysequence.h"
#include "qtransform.h"
#include "qmatrix.h"
#include "qpalette.h"
#include "qpen.h"
#include "qpixmap.h"
#include "qpolygon.h"
#include "qregion.h"
#include "qsizepolicy.h"
#include "qtextformat.h"
#include "qmatrix4x4.h"
#include "qvector2d.h"
#include "qvector3d.h"
#include "qvector4d.h"
#include "qquaternion.h"

#include "private/qvariant_p.h"

QT_BEGIN_NAMESPACE

#ifdef QT3_SUPPORT
extern QDataStream &qt_stream_out_qcolorgroup(QDataStream &s, const QColorGroup &g);
extern QDataStream &qt_stream_in_qcolorgroup(QDataStream &s, QColorGroup &g);
#endif

Q_CORE_EXPORT const QVariant::Handler *qcoreVariantHandler();

static void construct(QVariant::Private *x, const void *copy)
{
    switch (x->type) {
    case QVariant::Bitmap:
        v_construct<QBitmap>(x, copy);
        break;
    case QVariant::Region:
        v_construct<QRegion>(x, copy);
        break;
    case QVariant::Polygon:
        v_construct<QPolygon>(x, copy);
        break;
    case QVariant::Font:
        v_construct<QFont>(x, copy);
        break;
    case QVariant::Pixmap:
        v_construct<QPixmap>(x, copy);
        break;
    case QVariant::Image:
        v_construct<QImage>(x, copy);
        break;
    case QVariant::Brush:
        v_construct<QBrush>(x, copy);
        break;
    case QVariant::Color:
        v_construct<QColor>(x, copy);
        break;
    case QVariant::Palette:
        v_construct<QPalette>(x, copy);
        break;
#ifdef QT3_SUPPORT
    case QVariant::ColorGroup:
        v_construct<QColorGroup>(x, copy);
        break;
#endif
#ifndef QT_NO_ICON
    case QVariant::Icon:
        v_construct<QIcon>(x, copy);
        break;
#endif
    case QVariant::Matrix:
        v_construct<QMatrix>(x, copy);
        break;
    case QVariant::Transform:
        v_construct<QTransform>(x, copy);
        break;
    case QVariant::TextFormat:
        v_construct<QTextFormat>(x, copy);
        break;
    case QVariant::TextLength:
        v_construct<QTextLength>(x, copy);
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
        v_construct<QKeySequence>(x, copy);
        break;
#endif
    case QVariant::Pen:
        v_construct<QPen>(x, copy);
        break;
    case QVariant::SizePolicy:
        v_construct<QSizePolicy>(x, copy);
        break;
#ifndef QT_NO_CURSOR
    case QVariant::Cursor:
        v_construct<QCursor>(x, copy);
        break;
#endif
    case 62: {
        // small 'trick' to let a QVariant(Qt::blue) create a variant
        // of type QColor
        x->type = QVariant::Color;
        QColor color(*reinterpret_cast<const Qt::GlobalColor *>(copy));
        v_construct<QColor>(x, &color);
        break;
    }
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
        v_construct<QMatrix4x4>(x, copy);
        break;
#endif
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        v_construct<QVector2D>(x, copy);
        break;
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        v_construct<QVector3D>(x, copy);
        break;
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        v_construct<QVector4D>(x, copy);
        break;
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        v_construct<QQuaternion>(x, copy);
        break;
#endif
    default:
        qcoreVariantHandler()->construct(x, copy);
        return;
    }
    x->is_null = !copy;
}

static void clear(QVariant::Private *d)
{
    switch (d->type) {
    case QVariant::Bitmap:
        v_clear<QBitmap>(d);
        break;
    case QVariant::Cursor:
        v_clear<QCursor>(d);
        break;
    case QVariant::Region:
        v_clear<QRegion>(d);
        break;
    case QVariant::Polygon:
        v_clear<QPolygon>(d);
        break;
    case QVariant::Font:
        v_clear<QFont>(d);
        break;
    case QVariant::Pixmap:
        v_clear<QPixmap>(d);
        break;
    case QVariant::Image:
        v_clear<QImage>(d);
        break;
    case QVariant::Brush:
        v_clear<QBrush>(d);
        break;
    case QVariant::Color:
        v_clear<QColor>(d);
        break;
    case QVariant::Palette:
        v_clear<QPalette>(d);
        break;
#ifdef QT3_SUPPORT
    case QVariant::ColorGroup:
        v_clear<QColorGroup>(d);
        break;
#endif
#ifndef QT_NO_ICON
    case QVariant::Icon:
        v_clear<QIcon>(d);
        break;
#endif
    case QVariant::Matrix:
        v_clear<QMatrix>(d);
        break;
    case QVariant::Transform:
        v_clear<QTransform>(d);
        break;
    case QVariant::TextFormat:
        v_clear<QTextFormat>(d);
        break;
    case QVariant::TextLength:
        v_clear<QTextLength>(d);
        break;
    case QVariant::SizePolicy:
        v_clear<QSizePolicy>(d);
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
        v_clear<QKeySequence>(d);
        break;
#endif
    case QVariant::Pen:
        v_clear<QPen>(d);
        break;
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
        v_clear<QMatrix4x4>(d);
        break;
#endif
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        v_clear<QVector2D>(d);
        break;
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        v_clear<QVector3D>(d);
        break;
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        v_clear<QVector4D>(d);
        break;
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        v_clear<QVector4D>(d);
        break;
#endif
    default:
        qcoreVariantHandler()->clear(d);
        return;
    }

    d->type = QVariant::Invalid;
    d->is_null = true;
    d->is_shared = false;
}

static bool isNull(const QVariant::Private *d)
{
    switch(d->type) {
    case QVariant::Bitmap:
        return v_cast<QBitmap>(d)->isNull();
    case QVariant::Region:
        return v_cast<QRegion>(d)->isEmpty();
    case QVariant::Polygon:
        return v_cast<QPolygon>(d)->isEmpty();
    case QVariant::Pixmap:
        return v_cast<QPixmap>(d)->isNull();
    case QVariant::Image:
        return v_cast<QImage>(d)->isNull();
#ifndef QT_NO_ICON
    case QVariant::Icon:
        return v_cast<QIcon>(d)->isNull();
#endif
    case QVariant::Matrix:
    case QVariant::TextFormat:
    case QVariant::TextLength:
    case QVariant::Cursor:
    case QVariant::StringList:
    case QVariant::Font:
    case QVariant::Brush:
    case QVariant::Color:
    case QVariant::Palette:
#ifdef QT3_SUPPORT
    case QVariant::ColorGroup:
#endif
    case QVariant::SizePolicy:
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
#endif
    case QVariant::Pen:
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
#endif
        break;
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        return v_cast<QVector2D>(d)->isNull();
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        return v_cast<QVector3D>(d)->isNull();
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        return v_cast<QVector4D>(d)->isNull();
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        return v_cast<QQuaternion>(d)->isNull();
#endif
    default:
        return qcoreVariantHandler()->isNull(d);
    }
    return d->is_null;
}

static bool compare(const QVariant::Private *a, const QVariant::Private *b)
{
    Q_ASSERT(a->type == b->type);
    switch(a->type) {
    case QVariant::Cursor:
#ifndef QT_NO_CURSOR
        return v_cast<QCursor>(a)->shape() == v_cast<QCursor>(b)->shape();
#endif
    case QVariant::Bitmap:
        return v_cast<QBitmap>(a)->cacheKey()
            == v_cast<QBitmap>(b)->cacheKey();
    case QVariant::Polygon:
        return *v_cast<QPolygon>(a) == *v_cast<QPolygon>(b);
    case QVariant::Region:
        return *v_cast<QRegion>(a) == *v_cast<QRegion>(b);
    case QVariant::Font:
        return *v_cast<QFont>(a) == *v_cast<QFont>(b);
    case QVariant::Pixmap:
        return v_cast<QPixmap>(a)->cacheKey() == v_cast<QPixmap>(b)->cacheKey();
    case QVariant::Image:
        return *v_cast<QImage>(a) == *v_cast<QImage>(b);
    case QVariant::Brush:
        return *v_cast<QBrush>(a) == *v_cast<QBrush>(b);
    case QVariant::Color:
        return *v_cast<QColor>(a) == *v_cast<QColor>(b);
    case QVariant::Palette:
        return *v_cast<QPalette>(a) == *v_cast<QPalette>(b);
#ifdef QT3_SUPPORT
    case QVariant::ColorGroup:
        return *v_cast<QColorGroup>(a) == *v_cast<QColorGroup>(b);
#endif
#ifndef QT_NO_ICON
    case QVariant::Icon:
        /* QIcon::operator==() cannot be reasonably implemented for QIcon,
         * so we always return false. */
        return false;
#endif
    case QVariant::Matrix:
        return *v_cast<QMatrix>(a) == *v_cast<QMatrix>(b);
    case QVariant::Transform:
        return *v_cast<QTransform>(a) == *v_cast<QTransform>(b);
    case QVariant::TextFormat:
        return *v_cast<QTextFormat>(a) == *v_cast<QTextFormat>(b);
    case QVariant::TextLength:
        return *v_cast<QTextLength>(a) == *v_cast<QTextLength>(b);
    case QVariant::SizePolicy:
        return *v_cast<QSizePolicy>(a) == *v_cast<QSizePolicy>(b);
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
        return *v_cast<QKeySequence>(a) == *v_cast<QKeySequence>(b);
#endif
    case QVariant::Pen:
        return *v_cast<QPen>(a) == *v_cast<QPen>(b);
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
        return *v_cast<QMatrix4x4>(a) == *v_cast<QMatrix4x4>(b);
#endif
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        return *v_cast<QVector2D>(a) == *v_cast<QVector2D>(b);
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        return *v_cast<QVector3D>(a) == *v_cast<QVector3D>(b);
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        return *v_cast<QVector4D>(a) == *v_cast<QVector4D>(b);
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        return *v_cast<QQuaternion>(a) == *v_cast<QQuaternion>(b);
#endif
    default:
        break;
    }
    return qcoreVariantHandler()->compare(a, b);
}

static bool convert(const QVariant::Private *d, QVariant::Type t,
                 void *result, bool *ok)
{
    switch (t) {
    case QVariant::ByteArray:
        if (d->type == QVariant::Color) {
            *static_cast<QByteArray *>(result) = v_cast<QColor>(d)->name().toLatin1();
            return true;
        }
        break;
    case QVariant::String: {
        QString *str = static_cast<QString *>(result);
        switch (d->type) {
#ifndef QT_NO_SHORTCUT
        case QVariant::KeySequence:
            *str = QString(*v_cast<QKeySequence>(d));
            return true;
#endif
        case QVariant::Font:
            *str = v_cast<QFont>(d)->toString();
            return true;
        case QVariant::Color:
            *str = v_cast<QColor>(d)->name();
            return true;
        default:
            break;
        }
        break;
    }
    case QVariant::Pixmap:
        if (d->type == QVariant::Image) {
            *static_cast<QPixmap *>(result) = QPixmap::fromImage(*v_cast<QImage>(d));
            return true;
        } else if (d->type == QVariant::Bitmap) {
            *static_cast<QPixmap *>(result) = *v_cast<QBitmap>(d);
            return true;
        } else if (d->type == QVariant::Brush) {
            if (v_cast<QBrush>(d)->style() == Qt::TexturePattern) {
                *static_cast<QPixmap *>(result) = v_cast<QBrush>(d)->texture();
                return true;
            }
        }
        break;
    case QVariant::Image:
        if (d->type == QVariant::Pixmap) {
            *static_cast<QImage *>(result) = v_cast<QPixmap>(d)->toImage();
            return true;
        } else if (d->type == QVariant::Bitmap) {
            *static_cast<QImage *>(result) = v_cast<QBitmap>(d)->toImage();
            return true;
        }
        break;
    case QVariant::Bitmap:
        if (d->type == QVariant::Pixmap) {
            *static_cast<QBitmap *>(result) = *v_cast<QPixmap>(d);
            return true;
        } else if (d->type == QVariant::Image) {
            *static_cast<QBitmap *>(result) = QBitmap::fromImage(*v_cast<QImage>(d));
            return true;
        }
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::Int:
        if (d->type == QVariant::KeySequence) {
            *static_cast<int *>(result) = (int)(*(v_cast<QKeySequence>(d)));
            return true;
        }
        break;
#endif
    case QVariant::Font:
        if (d->type == QVariant::String) {
            QFont *f = static_cast<QFont *>(result);
            f->fromString(*v_cast<QString>(d));
            return true;
        }
        break;
    case QVariant::Color:
        if (d->type == QVariant::String) {
            static_cast<QColor *>(result)->setNamedColor(*v_cast<QString>(d));
            return static_cast<QColor *>(result)->isValid();
        } else if (d->type == QVariant::ByteArray) {
            static_cast<QColor *>(result)->setNamedColor(QString::fromLatin1(
                                *v_cast<QByteArray>(d)));
            return true;
        } else if (d->type == QVariant::Brush) {
            if (v_cast<QBrush>(d)->style() == Qt::SolidPattern) {
                *static_cast<QColor *>(result) = v_cast<QBrush>(d)->color();
                return true;
            }
        }
        break;
    case QVariant::Brush:
        if (d->type == QVariant::Color) {
            *static_cast<QBrush *>(result) = QBrush(*v_cast<QColor>(d));
            return true;
        } else if (d->type == QVariant::Pixmap) {
            *static_cast<QBrush *>(result) = QBrush(*v_cast<QPixmap>(d));
            return true;
        }
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence: {
        QKeySequence *seq = static_cast<QKeySequence *>(result);
        switch (d->type) {
        case QVariant::String:
            *seq = QKeySequence(*v_cast<QString>(d));
            return true;
        case QVariant::Int:
            *seq = QKeySequence(d->data.i);
            return true;
        default:
            break;
        }
    }
#endif
    default:
        break;
    }
    return qcoreVariantHandler()->convert(d, t, result, ok);
}

#if !defined(QT_NO_DEBUG_STREAM) && !defined(Q_BROKEN_DEBUG_STREAM)
static void streamDebug(QDebug dbg, const QVariant &v)
{
    switch(v.type()) {
    case QVariant::Cursor:
#ifndef QT_NO_CURSOR
//        dbg.nospace() << qvariant_cast<QCursor>(v); //FIXME
#endif
        break;
    case QVariant::Bitmap:
//        dbg.nospace() << qvariant_cast<QBitmap>(v); //FIXME
        break;
    case QVariant::Polygon:
        dbg.nospace() << qvariant_cast<QPolygon>(v);
        break;
    case QVariant::Region:
        dbg.nospace() << qvariant_cast<QRegion>(v);
        break;
    case QVariant::Font:
//        dbg.nospace() << qvariant_cast<QFont>(v);  //FIXME
        break;
    case QVariant::Matrix:
        dbg.nospace() << qvariant_cast<QMatrix>(v);
        break;
    case QVariant::Transform:
        dbg.nospace() << qvariant_cast<QTransform>(v);
        break;
    case QVariant::Pixmap:
//        dbg.nospace() << qvariant_cast<QPixmap>(v); //FIXME
        break;
    case QVariant::Image:
//        dbg.nospace() << qvariant_cast<QImage>(v); //FIXME
        break;
    case QVariant::Brush:
        dbg.nospace() << qvariant_cast<QBrush>(v);
        break;
    case QVariant::Color:
        dbg.nospace() << qvariant_cast<QColor>(v);
        break;
    case QVariant::Palette:
//        dbg.nospace() << qvariant_cast<QPalette>(v); //FIXME
        break;
#ifndef QT_NO_ICON
    case QVariant::Icon:
//        dbg.nospace() << qvariant_cast<QIcon>(v); // FIXME
        break;
#endif
    case QVariant::SizePolicy:
//        dbg.nospace() << qvariant_cast<QSizePolicy>(v); //FIXME
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
        dbg.nospace() << qvariant_cast<QKeySequence>(v);
        break;
#endif
    case QVariant::Pen:
        dbg.nospace() << qvariant_cast<QPen>(v);
        break;
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
        dbg.nospace() << qvariant_cast<QMatrix4x4>(v);
        break;
#endif
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        dbg.nospace() << qvariant_cast<QVector2D>(v);
        break;
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        dbg.nospace() << qvariant_cast<QVector3D>(v);
        break;
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        dbg.nospace() << qvariant_cast<QVector4D>(v);
        break;
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        dbg.nospace() << qvariant_cast<QQuaternion>(v);
        break;
#endif
    default:
        qcoreVariantHandler()->debugStream(dbg, v);
        break;
    }
}
#endif

const QVariant::Handler qt_gui_variant_handler = {
    construct,
    clear,
    isNull,
#ifndef QT_NO_DATASTREAM
    0,
    0,
#endif
    compare,
    convert,
    0,
#if !defined(QT_NO_DEBUG_STREAM) && !defined(Q_BROKEN_DEBUG_STREAM)
    streamDebug
#else
    0
#endif
};

struct QMetaTypeGuiHelper
{
    QMetaType::Constructor constr;
    QMetaType::Destructor destr;
#ifndef QT_NO_DATASTREAM
    QMetaType::SaveOperator saveOp;
    QMetaType::LoadOperator loadOp;
#endif
};

extern Q_CORE_EXPORT const QMetaTypeGuiHelper *qMetaTypeGuiHelper;

#ifdef QT_NO_DATASTREAM
#  define Q_DECL_METATYPE_HELPER(TYPE) \
     typedef void *(*QConstruct##TYPE)(const TYPE *); \
     static const QConstruct##TYPE qConstruct##TYPE = qMetaTypeConstructHelper<TYPE>; \
     typedef void (*QDestruct##TYPE)(TYPE *); \
     static const QDestruct##TYPE qDestruct##TYPE = qMetaTypeDeleteHelper<TYPE>;
#else
#  define Q_DECL_METATYPE_HELPER(TYPE) \
     typedef void *(*QConstruct##TYPE)(const TYPE *); \
     static const QConstruct##TYPE qConstruct##TYPE = qMetaTypeConstructHelper<TYPE>; \
     typedef void (*QDestruct##TYPE)(TYPE *); \
     static const QDestruct##TYPE qDestruct##TYPE = qMetaTypeDeleteHelper<TYPE>; \
     typedef void (*QSave##TYPE)(QDataStream &, const TYPE *); \
     static const QSave##TYPE qSave##TYPE = qMetaTypeSaveHelper<TYPE>; \
     typedef void (*QLoad##TYPE)(QDataStream &, TYPE *); \
     static const QLoad##TYPE qLoad##TYPE = qMetaTypeLoadHelper<TYPE>;
#endif

#ifdef QT3_SUPPORT
Q_DECL_METATYPE_HELPER(QColorGroup)
#endif
Q_DECL_METATYPE_HELPER(QFont)
Q_DECL_METATYPE_HELPER(QPixmap)
Q_DECL_METATYPE_HELPER(QBrush)
Q_DECL_METATYPE_HELPER(QColor)
Q_DECL_METATYPE_HELPER(QPalette)
#ifndef QT_NO_ICON
Q_DECL_METATYPE_HELPER(QIcon)
#endif
Q_DECL_METATYPE_HELPER(QImage)
Q_DECL_METATYPE_HELPER(QPolygon)
Q_DECL_METATYPE_HELPER(QRegion)
Q_DECL_METATYPE_HELPER(QBitmap)
#ifndef QT_NO_CURSOR
Q_DECL_METATYPE_HELPER(QCursor)
#endif
Q_DECL_METATYPE_HELPER(QSizePolicy)
#ifndef QT_NO_SHORTCUT
Q_DECL_METATYPE_HELPER(QKeySequence)
#endif
Q_DECL_METATYPE_HELPER(QPen)
Q_DECL_METATYPE_HELPER(QTextLength)
Q_DECL_METATYPE_HELPER(QTextFormat)
Q_DECL_METATYPE_HELPER(QMatrix)
Q_DECL_METATYPE_HELPER(QTransform)
#ifndef QT_NO_MATRIX4X4
Q_DECL_METATYPE_HELPER(QMatrix4x4)
#endif
#ifndef QT_NO_VECTOR2D
Q_DECL_METATYPE_HELPER(QVector2D)
#endif
#ifndef QT_NO_VECTOR3D
Q_DECL_METATYPE_HELPER(QVector3D)
#endif
#ifndef QT_NO_VECTOR4D
Q_DECL_METATYPE_HELPER(QVector4D)
#endif
#ifndef QT_NO_QUATERNION
Q_DECL_METATYPE_HELPER(QQuaternion)
#endif

#ifdef QT_NO_DATASTREAM
#  define Q_IMPL_METATYPE_HELPER(TYPE) \
     { reinterpret_cast<QMetaType::Constructor>(qConstruct##TYPE), \
       reinterpret_cast<QMetaType::Destructor>(qDestruct##TYPE) }
#else
#  define Q_IMPL_METATYPE_HELPER(TYPE) \
     { reinterpret_cast<QMetaType::Constructor>(qConstruct##TYPE), \
       reinterpret_cast<QMetaType::Destructor>(qDestruct##TYPE), \
       reinterpret_cast<QMetaType::SaveOperator>(qSave##TYPE), \
       reinterpret_cast<QMetaType::LoadOperator>(qLoad##TYPE) \
     }
#endif

static const QMetaTypeGuiHelper qVariantGuiHelper[] = {
#ifdef QT3_SUPPORT
    Q_IMPL_METATYPE_HELPER(QColorGroup),
#else
    {0, 0, 0, 0},
#endif
    Q_IMPL_METATYPE_HELPER(QFont),
    Q_IMPL_METATYPE_HELPER(QPixmap),
    Q_IMPL_METATYPE_HELPER(QBrush),
    Q_IMPL_METATYPE_HELPER(QColor),
    Q_IMPL_METATYPE_HELPER(QPalette),
#ifdef QT_NO_ICON
    {0, 0, 0, 0},
#else
    Q_IMPL_METATYPE_HELPER(QIcon),
#endif
    Q_IMPL_METATYPE_HELPER(QImage),
    Q_IMPL_METATYPE_HELPER(QPolygon),
    Q_IMPL_METATYPE_HELPER(QRegion),
    Q_IMPL_METATYPE_HELPER(QBitmap),
#ifdef QT_NO_CURSOR
    {0, 0, 0, 0},
#else
    Q_IMPL_METATYPE_HELPER(QCursor),
#endif
    Q_IMPL_METATYPE_HELPER(QSizePolicy),
#ifdef QT_NO_SHORTCUT
    {0, 0, 0, 0},
#else
    Q_IMPL_METATYPE_HELPER(QKeySequence),
#endif
    Q_IMPL_METATYPE_HELPER(QPen),
    Q_IMPL_METATYPE_HELPER(QTextLength),
    Q_IMPL_METATYPE_HELPER(QTextFormat),
    Q_IMPL_METATYPE_HELPER(QMatrix),
    Q_IMPL_METATYPE_HELPER(QTransform),
#ifndef QT_NO_MATRIX4X4
    Q_IMPL_METATYPE_HELPER(QMatrix4x4),
#else
    {0, 0, 0, 0},
#endif
#ifndef QT_NO_VECTOR2D
    Q_IMPL_METATYPE_HELPER(QVector2D),
#else
    {0, 0, 0, 0},
#endif
#ifndef QT_NO_VECTOR3D
    Q_IMPL_METATYPE_HELPER(QVector3D),
#else
    {0, 0, 0, 0},
#endif
#ifndef QT_NO_VECTOR4D
    Q_IMPL_METATYPE_HELPER(QVector4D),
#else
    {0, 0, 0, 0},
#endif
#ifndef QT_NO_QUATERNION
    Q_IMPL_METATYPE_HELPER(QQuaternion)
#else
    {0, 0, 0, 0}
#endif
};

static const QVariant::Handler *qt_guivariant_last_handler = 0;
int qRegisterGuiVariant()
{
    qt_guivariant_last_handler = QVariant::handler;
    QVariant::handler = &qt_gui_variant_handler;
    qMetaTypeGuiHelper = qVariantGuiHelper;
    return 1;
}
Q_CONSTRUCTOR_FUNCTION(qRegisterGuiVariant)

int qUnregisterGuiVariant()
{
    QVariant::handler = qt_guivariant_last_handler;
    qMetaTypeGuiHelper = 0;
    return 1;
}
Q_DESTRUCTOR_FUNCTION(qUnregisterGuiVariant)

QT_END_NAMESPACE


text:
from PIL import ImageFont, Image, ImageDraw
import random

class YZMInfo:

    def __init__(self, img, code):
        self.img = img
        self.code = code

def ygm(font_size=20, count_min=4, count_max=10, code_height=30,
        string='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
        font_color=['black', 'darkblue', 'darkred', 'darkgreen'],
        font_family='arial.ttf'):
    if count_max < count_min:
        count_max = count_min
    code_count = random.randrange(count_min, count_max)
    background = (random.randrange(230, 255),
                  random.randrange(230, 255),
                  random.randrange(230, 255))
    line_color = [(random.randrange(0, 255),
                   random.randrange(0, 255),
                   random.randrange(0, 255)),
                  (random.randrange(0, 255),
                   random.randrange(0, 255),
                   random.randrange(0, 255)),
                  (random.randrange(0, 255),
                   random.randrange(0, 255),
                   random.randrange(0, 255))]
    img_width = (font_size + 1) * code_count
    img_height = code_height + font_size
    verify = ''
    im = Image.new('RGB', (img_width, img_height), background)
    draw = ImageDraw.Draw(im)
    code = random.sample(string, code_count)
    draw = ImageDraw.Draw(im)
    for i in range(random.randrange(code_count / 2, code_count)):
        xy = (random.randrange(0, img_width), random.randrange(0, img_height),
              random.randrange(0, img_width), random.randrange(0, img_height))
        draw.line(xy, fill=random.choice(line_color), width=1)
    x = font_size / 2
    for i in code:
        y = random.randrange(0, code_height)
        font = ImageFont.truetype(
            font_family, font_size + random.randrange(-font_size/3, font_size/3))
        draw.text((x, y), i, font=font, fill=random.choice(font_color))
        x += font_size
        verify += i
    return YZMInfo(img=im, code=verify.upper())

info = ygm(font_size=16,
           code_height=10,
           string='#@%&$abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
info.img.save("0010.GIF")
print info.code


text:
package com.iamshekhargh.hackernews.datastore.interfaces;

/**
 * Created by <<-- iamShekharGH -->>
 * on 24 May 2017
 * at 12:59 PM.
 */

public interface GetStoryIds {

    void getStoryIDs();

    void getNewStoriesIDs();

    void getBestStoriesIDs();

    void getAskStorieIDs();

    void getShowStorieIDs();

    void getJobStorieIDs();

    interface Interactor {
        void onDataArrived(String[] list);

        void onError();

    }

}


text:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using System.IO;

namespace DockerTestProject {
    public class Program {
        public static void Main(string[] args) {
            var host = new WebHostBuilder()
                                .UseKestrel()
                                .UseStartup<Startup>()
                                .UseContentRoot(Directory.GetCurrentDirectory())
                                .UseUrls("http://0.0.0.0:5000")
                                .Build();
            host.Run();
        }
    }
}


text:
package keywhiz.service.resources;

import com.google.common.collect.ImmutableMap;
import keywhiz.IntegrationTestRule;
import keywhiz.TestClients;
import keywhiz.api.ApiDate;
import keywhiz.api.SecretDeliveryResponse;
import keywhiz.api.model.SanitizedSecret;
import keywhiz.api.model.Secret;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;

import static keywhiz.testing.HttpClients.testUrl;
import static org.assertj.core.api.Assertions.assertThat;

public class SecretsDeliveryResourceIntegrationTest {
  OkHttpClient client;
  OkHttpClient noSecretsClient;
  OkHttpClient clientNoClientCert;

  SecretDeliveryResponse generalPassword;
  SecretDeliveryResponse databasePassword;
  SecretDeliveryResponse nobodyPgPassPassword;
  SecretDeliveryResponse nonExistentOwnerPass;

  @ClassRule public static final RuleChain chain = IntegrationTestRule.rule();

  @Before
  public void setUp() throws Exception {
    client = TestClients.mutualSslClient();
    noSecretsClient = TestClients.noSecretsClient();
    clientNoClientCert = TestClients.unauthenticatedClient();

    generalPassword = SecretDeliveryResponse.fromSanitizedSecret(
        SanitizedSecret.fromSecret(
            new Secret(0, "General_Password", null, null, () -> "YXNkZGFz", "checksum",
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null,
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null,
                null, null, null, 0, 1L,
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null)));
    databasePassword = SecretDeliveryResponse.fromSanitizedSecret(
        SanitizedSecret.fromSecret(
            new Secret(1, "Database_Password", null, null, () -> "MTIzNDU=","checksum",
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                null, null, null, 0, 2L,
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null)));
    nobodyPgPassPassword = SecretDeliveryResponse.fromSanitizedSecret(
        SanitizedSecret.fromSecret(
            new Secret(2, "Nobody_PgPass", null, null,
                () -> "c29tZWhvc3Quc29tZXBsYWNlLmNvbTo1NDMyOnNvbWVkYXRhYmFzZTptaXN0ZXJhd2Vzb21lOmhlbGwwTWNGbHkK",
                "checksum",
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                ImmutableMap.of("owner", "nobody", "mode", "0400"), null, null, 0, 3L,
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null)));
    nonExistentOwnerPass = SecretDeliveryResponse.fromSanitizedSecret(
        SanitizedSecret.fromSecret(
            new Secret(3, "NonexistentOwner_Pass", null, null, () -> "MTIzNDU=", "checksum",
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                ApiDate.parse("2011-09-29T15:46:00.232Z"), null,
                ImmutableMap.of("owner", "NonExistent", "mode", "0400"), null, null, 0, 4L,
                ApiDate.parse("2011-09-29T15:46:00.312Z"), null)));
  }

  @Test
  public void returnsJsonArrayWhenUserHasMultipleSecrets() throws Exception {
    Request get = new Request.Builder()
        .get()
        .url(testUrl("/secrets"))
        .build();

    Response response = client.newCall(get).execute();
    assertThat(response.code()).isEqualTo(200);

    String responseString = response.body().string();
    assertThat(responseString)
        .contains(generalPassword.getName())
        .contains(databasePassword.getName())
        .contains(nobodyPgPassPassword.getName())
        .contains(nonExistentOwnerPass.getName());
  }

  @Test
  public void returnsJsonArray() throws Exception {
    Request get = new Request.Builder()
        .get()
        .url(testUrl("/secrets"))
        .build();

    Response response = client.newCall(get).execute();
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.body().string()).startsWith("[").endsWith("]");
  }

  @Test
  public void returnsUnauthorizedWhenUnauthenticated() throws Exception {
    Request get = new Request.Builder()
        .get()
        .url(testUrl("/secrets"))
        .build();

    Response response = clientNoClientCert.newCall(get).execute();
    assertThat(response.code()).isEqualTo(401);
  }

  @Test
  public void returnsEmptyJsonArrayWhenUserHasNoSecrets() throws Exception {
    Request get = new Request.Builder()
        .get()
        .url(testUrl("/secrets"))
        .build();

    Response response = noSecretsClient.newCall(get).execute();
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.body().string()).isEqualTo("[]");
  }
}


text:
<?php

/**
 * sfWebDebugPanelLESS implements LESS web debug panel.
 *
 * @package    sfLESSPlugin
 * @subpackage debug
 * @author     Konstantin Kudryashov <ever.zet@gmail.com>
 * @version    1.0.0
 */
class sfWebDebugPanelLESS extends sfWebDebugPanel
{
  /**
   * Some files have been compiled
   */
  protected $compiled = false;

  /**
   * Some errors where triggered during the compilation
   */
  protected $errors = false;

  /**
   * Listens to LoadDebugWebPanel event & adds this panel to the Web Debug toolbar
   *
   * @param   sfEvent $event
   */
  public static function listenToLoadDebugWebPanelEvent(sfEvent $event)
  {
    $event->getSubject()->setPanel(
      'documentation',
      new self($event->getSubject())
    );
  }

  /**
   * @see sfWebDebugPanel
   */
  public function getTitle()
  {
    return ' less';
  }

  /**
   * @see sfWebDebugPanel
   */
  public function getPanelTitle()
  {
    return 'LESS Stylesheets';
  }

  /**
   * @see sfWebDebugPanel
   */
  public function getPanelContent()
  {
    $panel = $this->getConfigurationContent() . '

less file	css file	time (ms)
';
    $errorDescriptions = sfLESS::getCompileErrors();
    foreach (sfLESS::getCompileResults() as $info)
    {
      $info['error'] = isset($errorDescriptions[$info['lessFile']]) ? $errorDescriptions[$info['lessFile']] : false;
      $panel .= $this->getInfoContent($info);
    }
    $panel .= '
';

    $this->setStatus($this->errors?sfLogger::ERR:($this->compiled?sfLogger::WARNING:sfLogger::INFO));

    return $panel;
  }

  /**
   * Returns configuration information for LESS compiler
   *
   * @return  string
   */
  protected function getConfigurationContent()
  {
    $debugInfo = '
';
    $lessHelper = new sfLESS;
    foreach ($lessHelper->getDebugInfo() as $name => $value)
    {
      $debugInfo .= sprintf('
%s:

%s
', $name, $value);
    }
    $debugInfo .= '
';

    return sprintf(<<<EOF

configuration %s

      %s

EOF
      ,$this->getToggler('less_debug', 'Toggle debug info')
      ,$debugInfo
    );
  }

  /**
   * Returns information row for LESS style compilation
   *
   * @param   array   $info info of compilation process
   * @return  string
   */
  protected function getInfoContent($info, $error = false)
  {
    // ID of error row
    $errorId = md5($info['lessFile']);

    // File link for preferred editor
    $fileLink = $this->formatFileLink(
      $info['lessFile'], 1, str_replace(sfLESS::getLessPaths(), '', $info['lessFile'])
    );

    // Checking compile & error statuses
    if ($info['isCompiled'])
    {
      $this->compiled = true;
      $trStyle = 'background-color:#a1d18d;';
    }
    elseif ($info['error'])
    {
      $this->errors = true;
      $trStyle = 'background-color:#f18c89;';
      $fileLink .= ' ' . $this->getToggler('less_error_' . $errorId, 'Toggle error info');
    }
    else
    {
      $trStyle = '';
    }

    // Generating info rows
    $infoRows = sprintf(<<<EOF

        %s
        %s
        %.2f

%s

EOF
      ,$trStyle
      ,$fileLink
      ,str_replace(sfLESS::getCssPaths(), '', $info['cssFile'])
      ,($info['isCompiled'] ? $info['compTime'] * 1000 : 0)
      ,$errorId
      ,$info['error']
    );

    return $infoRows;
  }
}


text:
package com.jwsphere.accumulo.async.internal;

import com.jwsphere.accumulo.async.internal.Unchecked.CheckedFunction;
import com.jwsphere.accumulo.async.internal.Unchecked.CheckedRunnable;
import com.jwsphere.accumulo.async.internal.Unchecked.CheckedSupplier;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Utilities for working with interruptible functions.
 *
 * @author Jonathan Wonders
 */
public class Interruptible {

    @FunctionalInterface
    public interface InterruptibleRunnable extends CheckedRunnable {
        void run() throws InterruptedException;
    }

    @FunctionalInterface
    public interface InterruptibleSupplier<T> extends CheckedSupplier<T> {
        T get() throws InterruptedException;
    }

    @FunctionalInterface
    public interface InterruptibleFunction<T, R> extends CheckedFunction<T, R> {
        R apply(T arg) throws InterruptedException;
    }

    @FunctionalInterface
    public interface InterruptionHandler extends Function<InterruptedException, RuntimeException> {
        RuntimeException apply(InterruptedException e);
    }

    public static Runnable runnable(InterruptibleRunnable runnable) {
        return runnable(runnable, CompletionException::new);
    }

    public static Runnable runnable(InterruptibleRunnable runnable, InterruptionHandler handler) {
        return () -> {
            try {
                runnable.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw handler.apply(e);
            }
        };
    }

    public static <T> Supplier<T> supplier(InterruptibleSupplier<T> supplier) {
        return supplier(supplier, CompletionException::new);
    }

    public static <T> Supplier<T> supplier(InterruptibleSupplier<T> supplier, InterruptionHandler handler) {
        return () -> {
            try {
                return supplier.get();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw handler.apply(e);
            }
        };
    }

    public static <T> CompletionStage<T> failOnInterrupt(InterruptibleSupplier<CompletionStage<T>> supplier) {
        try {
            return supplier.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            CompletableFuture<T> failed = new CompletableFuture<>();
            failed.completeExceptionally(e);
            return failed;
        }
    }

    public static <T, U> Function<T, U> propagateInterrupt(InterruptibleFunction<T, U> function) {
        return arg -> {
            try {
                return function.apply(arg);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new CompletionException(e);
            }
        };
    }

}


text:
app.controller("HomeController", function ($scope, $log, $location, TaskService, SprintService, tasks, categories, sprints) {
    'use strict';
    $log.debug('Home Controller Loaded');
    $scope.tasks = tasks;
    $log.debug('Tasks:', $scope.tasks);
    $scope.categories = categories;
    $log.debug('Categories:', $scope.categories);
    $scope.sprints = sprints;
    $log.debug('Sprints:', $scope.sprints);
    $scope.noSprint = false;

    //setting active sprint
    angular.forEach($scope.sprints, function (s, i) {
        if (s.active) {
            $scope.sprint = $scope.sprints[i];
        }
    });
    $log.debug("Active Sprint: ", $scope.sprint);

    $scope.calculateBurndownPace = function () {
        //burndown pace calculation
        var today = new Date(),
            sprint_length = $scope.sprint.burndown.length - 1,
            day = parseInt((today - new Date($scope.sprint.date_start)) / (1000 * 60 * 60 * 24), 10) + 1,
            expected_pace = ($scope.sprint.sprint_total / sprint_length) * day,
            burndownPace = ($scope.sprint.sprint_total - $scope.sprint.active_total) - expected_pace;
            $log.debug('today:', today);
            $log.debug('sprint_length:', sprint_length);
            $log.debug('day:', day);
            $log.debug('expectedPace:', expected_pace);
            $log.debug('burndownPace:', burndownPace);
        $scope.burndownPace = '~' +Math.abs(Math.round(burndownPace * 100) / 100) + (burndownPace > 0 ? ' points ahead' : ' points behind');
    };

    if (!$scope.sprint) {
        $scope.noSprint = true;
        $log.debug("No Active Sprint Yet");
    } else {
        $scope.calculateBurndownPace();
    }

    //backlog total calculation
    $scope.backlogTotal = 0;
    angular.forEach($scope.tasks, function (task, i) {
        if (task.backlog) {
            $scope.backlogTotal += task.weight;
        }
    });

    $scope.updateTask = function (task) {
        $log.debug('updateTask', task);
        angular.forEach($scope.tasks, function (t) {
            if (t.id === task.id) {
                task.sprints = t.sprints;
            }
        });
        TaskService.updateTask(task.id, task).then(function (data) {
            SprintService.getSprint($scope.sprint.id).then(function (sprint) {
                $scope.sprint = sprint;
                $scope.sprint.burndownChart = $scope.initializeBurndownChart(sprint);
                $scope.calculateBurndownPace();
            });
        });
    };

    //highcharts configurations
    if ($scope.sprint) {
        $scope.initializeBurndownChart = function (sprint) {
            return {
                options: {
                    chart: {
                        type: 'areaspline'
                    },
                    tooltip: {
                        style: {
                            padding: 10,
                            fontWeight: 'bold'
                        }
                    }
                },
                series: [
                    {
                        name: 'Remaining Task Weight',
                        data: sprint.burndown
                    },
                    {
                        type: 'line',
                        name: 'Guide Line',
                        color: 'red',
                        data: [
                            [0, sprint.sprint_total],
                            [sprint.burndown.length - 1, 0]
                        ],
                        marker: {
                            enabled: false
                        },
                        states: {
                            hover: {
                                lineWidth: 0
                            }
                        },
                        enableMouseTracking: false
                    }
                ],
                title: {
                    text: 'Burndown'
                }
            };
        };

        $scope.sprint.burndownChart = $scope.initializeBurndownChart($scope.sprint);
    }
    //form validation and submission
    $scope.submitNewSprint = function (isValid) {
        $log.debug('submitNewSprint called');
        $scope.submitted = true;
        if (isValid) {
            $log.debug('Form Submission Valid', $scope.newSprint);
            $scope.newSprint.date_start = $scope.getDate($scope.newSprint.date_start);
            $scope.newSprint.date_finish = $scope.getDate($scope.newSprint.date_finish);
            SprintService.createSprint($scope.newSprint).then(function (data) {
                $scope.sprints.push(data);
                $scope.newSprint = {};
                $scope.NewSprintForm.$setPristine();
                $scope.submitted = false;
            });
        } else {
            $log.debug('Form Submission Invalid');
        }
    };

    $scope.submitNewTask = function (isValid) {
        $log.debug('newTask Called');
        $scope.submitted = true;
        if (isValid) {
            $log.debug('Form Submission Valid');
            TaskService.createTask($scope.newTask).then(function (data) {
                $scope.tasks.push(data);
                $scope.initializeTasks();
                $scope.newTask = {};
                $scope.NewTaskForm.$setPristine();
                $scope.submitted = false;
            });
        } else {
            $log.debug('Form Submission Invalid');
        }
    };
});


text:
package com.amazonaws.services.opensearch.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The status of an outbound cross-cluster connection.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OutboundConnectionStatus implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The status code for the outbound connection. Can be one of the following:
     *

     *

     *

     *

     * VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     * VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     * PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain
     * owner.
     *

     *

     *

     *

     * APPROVED - Outbound connection has been approved by the remote domain owner for getting provisioned.
     *

     *

     *

     *

     * PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     * ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     * REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     * REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     * DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     * DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     *

     */
    private String statusCode;
    /**
     *

     * Verbose information for the outbound connection.
     *

     */
    private String message;

    /**
     *

     * The status code for the outbound connection. Can be one of the following:
     *

     *

     *

     *

     * VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     * VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     * PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain
     * owner.
     *

     *

     *

     *

     * APPROVED - Outbound connection has been approved by the remote domain owner for getting provisioned.
     *

     *

     *

     *

     * PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     * ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     * REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     * REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     * DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     * DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     *

     *
     * @param statusCode
     *        The status code for the outbound connection. Can be one of the following:

     *

     *

     *

     *        VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     *        VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     *        PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote
     *        domain owner.
     *

     *

     *

     *

     *        APPROVED - Outbound connection has been approved by the remote domain owner for getting
     *        provisioned.
     *

     *

     *

     *

     *        PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     *        ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     *        REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     *        REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     *        DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     *        DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     * @see OutboundConnectionStatusCode
     */

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    /**
     *

     * The status code for the outbound connection. Can be one of the following:
     *

     *

     *

     *

     * VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     * VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     * PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain
     * owner.
     *

     *

     *

     *

     * APPROVED - Outbound connection has been approved by the remote domain owner for getting provisioned.
     *

     *

     *

     *

     * PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     * ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     * REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     * REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     * DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     * DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     *

     *
     * @return The status code for the outbound connection. Can be one of the following:

     *

     *

     *

     *         VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     *         VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     *         PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote
     *         domain owner.
     *

     *

     *

     *

     *         APPROVED - Outbound connection has been approved by the remote domain owner for getting
     *         provisioned.
     *

     *

     *

     *

     *         PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     *         ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     *         REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     *         REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     *         DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     *         DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     * @see OutboundConnectionStatusCode
     */

    public String getStatusCode() {
        return this.statusCode;
    }

    /**
     *

     * The status code for the outbound connection. Can be one of the following:
     *

     *

     *

     *

     * VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     * VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     * PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain
     * owner.
     *

     *

     *

     *

     * APPROVED - Outbound connection has been approved by the remote domain owner for getting provisioned.
     *

     *

     *

     *

     * PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     * ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     * REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     * REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     * DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     * DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     *

     *
     * @param statusCode
     *        The status code for the outbound connection. Can be one of the following:

     *

     *

     *

     *        VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     *        VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     *        PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote
     *        domain owner.
     *

     *

     *

     *

     *        APPROVED - Outbound connection has been approved by the remote domain owner for getting
     *        provisioned.
     *

     *

     *

     *

     *        PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     *        ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     *        REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     *        REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     *        DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     *        DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OutboundConnectionStatusCode
     */

    public OutboundConnectionStatus withStatusCode(String statusCode) {
        setStatusCode(statusCode);
        return this;
    }

    /**
     *

     * The status code for the outbound connection. Can be one of the following:
     *

     *

     *

     *

     * VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     * VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     * PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote domain
     * owner.
     *

     *

     *

     *

     * APPROVED - Outbound connection has been approved by the remote domain owner for getting provisioned.
     *

     *

     *

     *

     * PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     * ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     * REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     * REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     * DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     * DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     *

     *
     * @param statusCode
     *        The status code for the outbound connection. Can be one of the following:

     *

     *

     *

     *        VALIDATING - The outbound connection request is being validated.
     *

     *

     *

     *

     *        VALIDATION_FAILED - Validation failed for the connection request.
     *

     *

     *

     *

     *        PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by the remote
     *        domain owner.
     *

     *

     *

     *

     *        APPROVED - Outbound connection has been approved by the remote domain owner for getting
     *        provisioned.
     *

     *

     *

     *

     *        PROVISIONING - Outbound connection request is in process.
     *

     *

     *

     *

     *        ACTIVE - Outbound connection is active and ready to use.
     *

     *

     *

     *

     *        REJECTING - Outbound connection rejection by remote domain owner is in progress.
     *

     *

     *

     *

     *        REJECTED - Outbound connection request is rejected by remote domain owner.
     *

     *

     *

     *

     *        DELETING - Outbound connection deletion is in progress.
     *

     *

     *

     *

     *        DELETED - Outbound connection is deleted and can no longer be used.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OutboundConnectionStatusCode
     */

    public OutboundConnectionStatus withStatusCode(OutboundConnectionStatusCode statusCode) {
        this.statusCode = statusCode.toString();
        return this;
    }

    /**
     *

     * Verbose information for the outbound connection.
     *

     *
     * @param message
     *        Verbose information for the outbound connection.
     */

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *

     * Verbose information for the outbound connection.
     *

     *
     * @return Verbose information for the outbound connection.
     */

    public String getMessage() {
        return this.message;
    }

    /**
     *

     * Verbose information for the outbound connection.
     *

     *
     * @param message
     *        Verbose information for the outbound connection.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public OutboundConnectionStatus withMessage(String message) {
        setMessage(message);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getStatusCode() != null)
            sb.append("StatusCode: ").append(getStatusCode()).append(",");
        if (getMessage() != null)
            sb.append("Message: ").append(getMessage());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof OutboundConnectionStatus == false)
            return false;
        OutboundConnectionStatus other = (OutboundConnectionStatus) obj;
        if (other.getStatusCode() == null ^ this.getStatusCode() == null)
            return false;
        if (other.getStatusCode() != null && other.getStatusCode().equals(this.getStatusCode()) == false)
            return false;
        if (other.getMessage() == null ^ this.getMessage() == null)
            return false;
        if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getStatusCode() == null) ? 0 : getStatusCode().hashCode());
        hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
        return hashCode;
    }

    @Override
    public OutboundConnectionStatus clone() {
        try {
            return (OutboundConnectionStatus) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.opensearch.model.transform.OutboundConnectionStatusMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
import os
import urlparse

from .settings import *

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [
    'rohan.cincoovnis.com',
    'www.rohan.cincoovnis.com',
]

SECRET_KEY = os.environ['SECRET_KEY']

SITE_ID = 1

if "ROHAN_DATABASE_URL" in os.environ:
    urlparse.uses_netloc.append("postgres")
    url = urlparse.urlparse(os.environ["ROHAN_DATABASE_URL"])
    DATABASES = {
        "default": {
            "ENGINE": {
                "postgres": "django.db.backends.postgresql_psycopg2"
            }[url.scheme],
            "NAME": url.path[1:],
            "USER": url.username,
            "PASSWORD": url.password,
            "HOST": url.hostname,
            "PORT": url.port
        }
    }

MEDIA_ROOT = os.path.join(os.environ["ROHAN_DATA_DIR"], "site_media", "media")
STATIC_ROOT = os.path.join(os.environ["ROHAN_DATA_DIR"], "site_media", "static")

MEDIA_URL = "/site_media/media/"
STATIC_URL = "/site_media/static/"

# Opbeat
OPBEAT = {
    "ORGANIZATION_ID": os.environ.get("OPBEAT_ORGANIZATION_ID"),
    "APP_ID": os.environ.get("OPBEAT_APP_ID"),
    "SECRET_TOKEN": os.environ.get("OPBEAT_SECRET_TOKEN")
}

INSTALLED_APPS += (
    'opbeat.contrib.django',
)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>Welcome to simsoexp's documentation! — simsoexp 0 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="simsoexp 0 documentation" href="#" />

Navigation

          index

          modules |

simsoexp 0 documentation »

Welcome to simsoexp’s documentation!¶

Contents:

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">DBConfFile</tt><big>(</big>db, testset, identifier<big>)</big>¶

Represents a configuration file taken from a remote Simso Experiment Database.

<tt class="descname">configuration</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	the Simso configuration object represented by this configuration file.

Return type:	simso.configuration.Configuration

<tt class="descname">content</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	this configuration file’s XML content.

Return type:	str

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">DBResults</tt><big>(</big>db, identifier<big>)</big>¶

Represents a results set from a remote Simso Experiment Database.
These results contains :
- the scheduler and testset identifiers in the database used to build the experiment.
- the resulting metrics

<tt class="descname">metrics</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	A dictionnary containing a set of metrics indexed by their name.

Return type:	dict of dict

<tt class="descname">scheduler_id</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	The id of the scheduler used to build these results.

Return type:	int

<tt class="descname">testset_id</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	The id of the testset used to build these results.

Return type:	int

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">DBScheduler</tt><big>(</big>db, identifier<big>)</big>¶

Represents a scheduler taken from a remote Simso Experiment Database.

<tt class="descname">class_name</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	the scheduler’s main class in the scheduler’s code

Return type:	str

<tt class="descname">cls</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	the scheduler’s class object.

Return type:	type

<tt class="descname">code</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	this scheduler’s python code

Return type:	str

<tt class="descname">name</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	this scheduler visible name

Return type:	str

<tt class="descname">push</tt><big>(</big>newdb<big>)</big>¶

Pushes this DBScheduler object to another database.
Note : this scheduler might need to be validated by the maintainers of the destination database.

<col class="field-name" />
<col class="field-body" />

Parameters:	newdb (SimsoDatabase) – Destination database where the object will be pushed.

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">DBTestSet</tt><big>(</big>db, identifier<big>)</big>¶

Represents a test set taken from a remote Simso Experiment Database.

<tt class="descname">categories</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	This test set’s categories as a list.

Return type:	list of string

<tt class="descname">conf_files</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	a list of DBConfFile object for each configuration file in this test set.

Return type:	list of DBConfFile

<tt class="descname">description</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	The description of the test set.

Return type:	str

<tt class="descname">name</tt>¶

<col class="field-name" />
<col class="field-body" />

Returns:	The name of the test set

Return type:	str

<tt class="descname">push</tt><big>(</big>newdb<big>)</big>¶

Pushes this DBTestset object to another database.
Note : this testset might need to be validated by the maintainers of the destination database.

<col class="field-name" />
<col class="field-body" />

Parameters:	newdb (SimsoDatabase) – Destination database where the object will be pushed.

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">Experiment</tt><big>(</big>db, conf_files, scheduler<big>)</big>¶

Represent an experiment, which contains :

a set of configuration files

a scheduler

after run() : a set of metrics and results

<tt class="descname">run</tt><big>(</big><big>)</big>¶

Runs the experiment and computes the metrics.

<tt class="descname">upload</tt><big>(</big><big>)</big>¶

Uploads the experiment results to Simso Experiment Database.

An ApiError will be raised if the results of the experiment already exist.

Note you won’t be able to upload your results if you used a custom test set.

<col class="field-name" />
<col class="field-body" />

Raises ApiError:

 	the operation is not allowed (see exception details).

class <tt class="descclassname">simsoexp.clientapi.simsodb.</tt><tt class="descname">SimsoDatabase</tt><big>(</big>address, username=None, password=None<big>)</big>¶

SimsoDatabase is the main component of the Simso Experiment Platform API.

<tt class="descname">categories</tt><big>(</big><big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Returns:	a list of all the test categories in the database.

Return type:	list of str

Raises HttpError:

 	there was an error in the request.

<tt class="descname">categories_and_description</tt><big>(</big><big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Returns:	a list of tuples (category_name, description) for each test category.

Return type:	list of (str, str)

Raises HttpError:

 	there was an error in the request.

<tt class="descname">result</tt><big>(</big>identifier<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Returns:	a result set given its identifier in the database.

Return type:	DBResults

<tt class="descname">results</tt><big>(</big>testset, scheduler<big>)</big>¶

Gets the results associated to the given testset and scheduler.
These results have been obtained by running simso with the corresponding
scheduler and testsets.

<col class="field-name" />
<col class="field-body" />

Parameters:

testset (DBTestSet) – A DBTestSet instance.

scheduler (DBScheduler) – A DBScheduler instance.

Returns:
The results corresponding to the given scheduler and testset.

Return type:
list of DBResults

Raises HttpError:

there was an error in the request.

<tt class="descname">scheduler</tt><big>(</big>identifier<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Returns:	a scheduler given its id in the database.

Return type:	DBScheduler

<tt class="descname">scheduler_by_name</tt><big>(</big>name=''<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Parameters:
name (str) – The exact name of the schedulers to find.

Returns:
a scheduler given its name in the database.

Return type:
DBScheduler

Raises:

HttpError – there was an error in the request.

ApiError – the scheduler with the given name does not exist.

<tt class="descname">testset</tt><big>(</big>identifier<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Parameters:	identifier (int) – The identifier of the testset to retrieve.

Returns:	DBTestset instance whose id is identifier

Return type:	DBTestset

<tt class="descname">testset_by_name</tt><big>(</big>name<big>)</big>¶

<col class="field-name" />
<col class="field-body" />

Returns:	DBTestset instance whose name is name

Return type:	DBTestset

<tt class="descname">testsets</tt><big>(</big>category=''<big>)</big>¶

Gets a list of testsets given a category.
If no category is specified, all the testsets are returned.

<col class="field-name" />
<col class="field-body" />

Parameters:	category (str) – the category of testsets to display.

Returns:	list of testsets given a category.

Return type:	list of DBTestSet

Raises HttpError:

 	there was an error in the request.

<tt class="descname">upload_scheduler</tt><big>(</big>name, class_name, code<big>)</big>¶

Uploads a scheduler with the given name, class name and code
to the database.

The scheduler will be available in the database as soon as
it is validated by a maintainer.

If a VALIDATED scheduler with the same name already exists, an
ApiError is raised. If a non-validated scheduler with the same name
already exists, it will be overriden if you are the author of the
existing scheduler.

<col class="field-name" />
<col class="field-body" />

Parameters:

name (str) – name of the scheduler to upload. Should be unique.

class_name (str) – name of the main class of the scheduler in the code.

code (str) – python code of the scheduler.

Raises:

HttpError – there was an error in the request.

ApiError – the operation is not allowed (see exception details)

<tt class="descname">upload_testset</tt><big>(</big>name, description, categories, conf_files<big>)</big>¶

Uploads a test set with the given name, categories
and configuration files (list of Configuration objects).

The testset will be available in the database as soon as
it is validated by a maintainer.

If a VALIDATED testset with the same name already exists, an
ApiError is raised. If a non-validated testset with the same name
already exists, it will be overriden if you are the author of the
existing test set.

<col class="field-name" />
<col class="field-body" />

Parameters:

name (str) – name of the test set to upload

description (str) – description of the test set to upload.

categories (list of str) – categories linked to the test set. They must already exist in the DB.

Raises:

HttpError – there was an error in the request.

ApiError – the operation is not allowed (see exception details)

Indices and tables¶

Index

Module Index

Search Page

Table Of Contents

Welcome to simsoexp’s documentation!

Indices and tables

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

simsoexp 0 documentation »

        © Copyright 2015, Josué Alvarez.
      Created using Sphinx 1.2.2.


text:
.class final Lcom/android/server/am/BroadcastQueue$AppNotResponding;
.super Ljava/lang/Object;
.source "BroadcastQueue.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/am/BroadcastQueue;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "AppNotResponding"
.end annotation

# instance fields
.field private final mAnnotation:Ljava/lang/String;

.field private final mApp:Lcom/android/server/am/ProcessRecord;

.field final synthetic this$0:Lcom/android/server/am/BroadcastQueue;

# direct methods
.method public constructor <init>(Lcom/android/server/am/BroadcastQueue;Lcom/android/server/am/ProcessRecord;Ljava/lang/String;)V
    .locals 0
    .parameter
    .parameter "app"
    .parameter "annotation"

    .prologue
    .line 155
    iput-object p1, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->this$0:Lcom/android/server/am/BroadcastQueue;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 156
    iput-object p2, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->mApp:Lcom/android/server/am/ProcessRecord;

    .line 157
    iput-object p3, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->mAnnotation:Ljava/lang/String;

    .line 158
    return-void
.end method

# virtual methods
.method public run()V
    .locals 6

    .prologue
    const/4 v2, 0x0

    .line 162
    iget-object v0, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->this$0:Lcom/android/server/am/BroadcastQueue;

    iget-object v0, v0, Lcom/android/server/am/BroadcastQueue;->mService:Lcom/android/server/am/ActivityManagerService;

    iget-object v1, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->mApp:Lcom/android/server/am/ProcessRecord;

    const/4 v4, 0x0

    iget-object v5, p0, Lcom/android/server/am/BroadcastQueue$AppNotResponding;->mAnnotation:Ljava/lang/String;

    move-object v3, v2

    invoke-virtual/range {v0 .. v5}, Lcom/android/server/am/ActivityManagerService;->appNotResponding(Lcom/android/server/am/ProcessRecord;Lcom/android/server/am/ActivityRecord;Lcom/android/server/am/ActivityRecord;ZLjava/lang/String;)V

    .line 163
    return-void
.end method


text:
package com.beardedhen.androidbootstrap;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.api.attributes.BootstrapBrand;
import com.beardedhen.androidbootstrap.api.defaults.DefaultBootstrapBrand;
import com.beardedhen.androidbootstrap.api.view.BootstrapBrandView;
import com.beardedhen.androidbootstrap.api.view.BootstrapTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.beardedhen.androidbootstrap.font.IconSet;
import com.beardedhen.androidbootstrap.font.MaterialIcons;
import com.beardedhen.androidbootstrap.font.Typicon;

import java.io.Serializable;

/**
 * This class extends the default Android TextView to supply Bootstrap behaviour. The text color
 * can be set by changing the BootstrapBrand, and scalable Typeface icons can be interspersed with
 * regular text, using the BootstrapText spannable.
 */
public class AwesomeTextView extends TextView implements BootstrapTextView, BootstrapBrandView {

    private static final String TAG = "com.beardedhen.androidbootstrap.AwesomeTextView";

    private BootstrapText bootstrapText;
    private BootstrapBrand bootstrapBrand;

    public enum AnimationSpeed {
        FAST(500, 200),
        MEDIUM(1000, 500),
        SLOW(2000, 1000);

        private final long rotateDuration;
        private final long flashDuration;

        AnimationSpeed(long rotateDuration, long flashDuration) {
            this.rotateDuration = rotateDuration;
            this.flashDuration = flashDuration;
        }

        public long getRotateDuration() {
            return rotateDuration;
        }

        public long getFlashDuration() {
            return flashDuration;
        }
    }

    public AwesomeTextView(Context context) {
        super(context);
        initialise(null);
    }

    public AwesomeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise(attrs);
    }

    public AwesomeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialise(attrs);
    }

    private void initialise(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.AwesomeTextView);
        String markdownText;

        try {
            int typeOrdinal = a.getInt(R.styleable.AwesomeTextView_bootstrapBrand, -1);
            int faIconOrdinal = a.getInt(R.styleable.AwesomeTextView_fontAwesomeIcon, -1);
            int typiconOrdinal = a.getInt(R.styleable.AwesomeTextView_typicon, -1);
            int materialIconOrdinal = a.getInt(R.styleable.AwesomeTextView_materialIcon, -1);

            boolean clickable = a.getBoolean(R.styleable.AwesomeTextView_android_clickable, true);

            this.bootstrapBrand = DefaultBootstrapBrand.fromAttributeValue(typeOrdinal);
            boolean editMode = isInEditMode();

            if (typiconOrdinal != -1) {
                final IconSet typicon = TypefaceProvider.retrieveRegisteredIconSet(Typicon.FONT_PATH, editMode);

                if (!editMode) {
                    setIcon(typicon.iconCodeForAttrIndex(typiconOrdinal), typicon);
                }
            }
            if (faIconOrdinal != -1) {
                final IconSet fontAwesome = TypefaceProvider.retrieveRegisteredIconSet(FontAwesome.FONT_PATH, editMode);

                if (!editMode) {
                    setIcon(fontAwesome.iconCodeForAttrIndex(faIconOrdinal), fontAwesome);
                }
            }
            if (materialIconOrdinal != -1) {
                final IconSet materialIcons = TypefaceProvider.retrieveRegisteredIconSet(MaterialIcons.FONT_PATH, editMode);

                if (!editMode) {
                    setIcon(materialIcons.iconCodeForAttrIndex(materialIconOrdinal), materialIcons);
                }
            }
            markdownText = a.getString(R.styleable.AwesomeTextView_bootstrapText);

            setClickable(clickable); // allows view to reach android:state_pressed

            int gravity = a.getInt(R.styleable.AwesomeTextView_android_gravity, Gravity.CENTER);
            setGravity(gravity);
        }
        finally {
            a.recycle();
        }

        if (markdownText != null) {
            setMarkdownText(markdownText);
        }
        updateBootstrapState();
    }

    @Override public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(TAG, super.onSaveInstanceState());
        bundle.putSerializable(BootstrapTextView.KEY, bootstrapText);
        bundle.putSerializable(BootstrapBrand.KEY, bootstrapBrand);
        return bundle;
    }

    @Override public void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;

            Serializable text = bundle.getSerializable(BootstrapTextView.KEY);
            Serializable brand = bundle.getSerializable(BootstrapBrand.KEY);

            if (brand instanceof BootstrapBrand) {
                bootstrapBrand = (BootstrapBrand) brand;
            }
            if (text instanceof BootstrapText) {
                bootstrapText = (BootstrapText) text;
            }
            state = bundle.getParcelable(TAG);
        }
        super.onRestoreInstanceState(state);
        updateBootstrapState();
    }

    /**
     * Starts a Flashing Animation on the AwesomeTextView
     *
     * @param forever whether the animation should be infinite or play once
     * @param speed   how fast the item should flash
     */
    public void startFlashing(boolean forever, AnimationSpeed speed) {
        Animation fadeIn = new AlphaAnimation(0, 1);

        //set up extra variables
        fadeIn.setDuration(50);
        fadeIn.setRepeatMode(Animation.REVERSE);

        //default repeat count is 0, however if user wants, set it up to be infinite
        fadeIn.setRepeatCount(0);
        if (forever) {
            fadeIn.setRepeatCount(Animation.INFINITE);
        }

        fadeIn.setStartOffset(speed.getFlashDuration());
        startAnimation(fadeIn);
    }

    /**
     * Starts a rotating animation on the AwesomeTextView
     *
     * @param clockwise true for clockwise, false for anti clockwise spinning
     * @param speed     how fast the item should rotate
     */
    public void startRotate(boolean clockwise, AnimationSpeed speed) {
        Animation rotate;

        //set up the rotation animation
        if (clockwise) {
            rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        }
        else {
            rotate = new RotateAnimation(360, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        }

        //set up some extra variables
        rotate.setRepeatCount(Animation.INFINITE);
        rotate.setInterpolator(new LinearInterpolator());
        rotate.setStartOffset(0);
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setDuration(speed.getRotateDuration());
        startAnimation(rotate);
    }

    /**
     * Sets the text to display a FontIcon, replacing whatever text is already present.
     * Used to set the text to display a FontAwesome Icon.
     *
     * @param iconSet - An implementation of FontIcon
     */
    public void setIcon(CharSequence iconCode, IconSet iconSet) {
        setBootstrapText(new BootstrapText.Builder(getContext(), isInEditMode()).addIcon(iconCode, iconSet).build());
    }

    /**
     * Sets the text to display a FontIcon, replacing whatever text is already present.
     * Used to set the text to display a FontAwesome Icon.
     *
     * @param iconCode the fontawesome icon code e.g. "fa_play"
     */
    public void setFontAwesomeIcon(@FontAwesome.Icon CharSequence iconCode) {
        setBootstrapText(new BootstrapText.Builder(getContext(), isInEditMode()).addFontAwesomeIcon(iconCode).build());
    }

    /**
     * Sets the text to display a MaterialIcon, replacing whatever text is already present.
     * Used to set the text to display a MaterialIcon Icon.
     *
     * @param iconCode the fontawesome icon code e.g. "md_share"
     */
    public void setMaterialIcon(@FontAwesome.Icon CharSequence iconCode) {
        setBootstrapText(new BootstrapText.Builder(getContext(), isInEditMode()).addMaterialIcon(iconCode).build());
    }

    /**
     * Sets the text to display a FontIcon, replacing whatever text is already present.
     * Used to set the text to display a Typicon.
     *
     * @param iconCode the typicon icon code e.g. "ty_adjust_brightness"
     */
    public void setTypicon(@Typicon.Icon CharSequence iconCode) {
        setBootstrapText(new BootstrapText.Builder(getContext(), isInEditMode()).addTypicon(iconCode).build());
    }

    @Override public void setMarkdownText(String text) {
        setBootstrapText(IconResolver.resolveMarkdown(getContext(), text, isInEditMode()));
    }

    protected void updateBootstrapState() {
        if (bootstrapText != null) {
            setText(bootstrapText);
        }
        if (bootstrapBrand != null) {
            setTextColor(bootstrapBrand.defaultFill(getContext()));
        }
    }

    /*
     * Getters/Setters
     */

    @Override public void setBootstrapText(BootstrapText bootstrapText) {
        this.bootstrapText = bootstrapText;
        updateBootstrapState();
    }

    @Nullable @Override public BootstrapText getBootstrapText() {
        return bootstrapText;
    }

    @Override public void setBootstrapBrand(@NonNull BootstrapBrand bootstrapBrand) {
        this.bootstrapBrand = bootstrapBrand;
        updateBootstrapState();
    }

    @NonNull @Override public BootstrapBrand getBootstrapBrand() {
        return bootstrapBrand;
    }

    @Override public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        bootstrapText = null;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        if(!(text!=null && text.length()>0)){
            setVisibility(GONE);
        }else{
            setVisibility(VISIBLE);
        }
    }

}