text:
//---------------------------------------------------------------------------//
//!
//! \file   tstDataProcessor.cpp
//! \author Alex Robinson
//! \brief  DataProcessor class unit tests.
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <string>

// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayView.hpp>

// FRENSIE Includes
#include "Utility_DataProcessor.hpp"
#include "Utility_TupleMemberTraits.hpp"
#include "Utility_Tuple.hpp"
#include "Utility_UnitTestHarnessExtensions.hpp"

//---------------------------------------------------------------------------//
// Testing Data.
//---------------------------------------------------------------------------//
#define INDEP_VAR 5.11e-1
#define LOG_INDEP_VAR -6.7138568877843e-1
#define SQR_INDEP_VAR 2.61121e-1
#define DEP_VAR 3.14
#define LOG_DEP_VAR 1.1442227999202
#define SQR_DEP_VAR 9.8596
#define ZERO 0
#define SLOPE 6.1448140900196
#define CDF_NORM 64.98387
#define SHELL 5
#define SHELL_NAME "5"
#define TOL 1e-12

//---------------------------------------------------------------------------//
// Instantiation Macros.
//---------------------------------------------------------------------------//
#define TUPLE_TYPEDEFS()					\
  typedef Utility::Pair<double,double> pair_d_d;			\
  typedef Utility::Pair<unsigned,double> pair_u_d;			\
  typedef Utility::Pair<double,unsigned> pair_d_u;			\
  typedef Utility::Trip<double,double,double> trip_d_d_d;		\
  typedef Utility::Trip<unsigned,double,double> trip_u_d_d;		\
  typedef Utility::Trip<unsigned,double,unsigned> trip_u_d_u;		\
  typedef Utility::Trip<double,double,unsigned> trip_d_d_u;		\
  typedef Utility::Trip<unsigned,unsigned,double> trip_u_u_d;		\
  typedef Utility::Trip<double,unsigned,double> trip_d_u_d;		\
  typedef Utility::Quad<double,double,double,double> quad_d_d_d_d;	\
  typedef Utility::Quad<unsigned,unsigned,double,double> quad_u_u_d_d;	\
  typedef Utility::Quad<unsigned,double,double,unsigned> quad_u_d_d_u;	\
  typedef Utility::Quad<unsigned,double,double,double> quad_u_d_d_d;	\
  typedef Utility::Quad<double,double,double,unsigned> quad_d_d_d_u;	\
  typedef Utility::Quad<double,double,unsigned,unsigned> quad_d_d_u_u;	\
  typedef Utility::Quad<double,unsigned,unsigned,double> quad_d_u_u_d;	\
  typedef Utility::Quad<unsigned,double,unsigned,double> quad_u_d_u_d;	\
  typedef Utility::Quad<unsigned,unsigned,unsigned,double> quad_u_u_u_d; \
  typedef Utility::Quad<unsigned,unsigned,unsigned,unsigned> quad_u_u_u_u; \

#define UNIT_TEST_INSTANTIATION_POLICY( type, name )	\
  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type,				\
					name,				\
					LogLogDataProcessing )	\
  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type,				\
					name,				\
					SqrSqrDataProcessing ) \

#define UNIT_TEST_INSTANTIATION_POLICY_TUPLE( type, name )		\
  TUPLE_TYPEDEFS()							\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					LogLogDataProcessing,	\
					pair_d_d )			\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					LogLogDataProcessing,	\
					trip_d_d_d )			\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					LogLogDataProcessing,	\
					quad_d_d_d_d )			\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					SqrSqrDataProcessing, \
					pair_d_d )			\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					SqrSqrDataProcessing, \
					trip_d_d_d )			\
  TEUCHOS_UNIT_TEST_TEMPLATE_2_INSTANT( type,				\
					name,				\
					SqrSqrDataProcessing, \
					quad_d_d_d_d )			\

#define UNIT_TEST_INSTANTIATION_TUPLE( type, name )			\
  TUPLE_TYPEDEFS()							\
  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, pair_d_d )		\
  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, trip_d_d_d )	\
  TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, quad_d_d_d_d )	\

#define UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( type, name, array ) \
  TUPLE_TYPEDEFS()							\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type, \
							    name, \
							    THIRD, \
							    trip_d_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type, \
							    name, \
							    THIRD, \
							    quad_d_d_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type, \
							    name, \
							    FOURTH, \
							    quad_d_d_d_d, \
							    array )	\

#define UNIT_TEST_INSTANTIATION_MEMBER_TUPLE( type, name )		\
  TUPLE_TYPEDEFS()							\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      SECOND,		\
						      pair_d_d )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      SECOND,		\
						      pair_u_d )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      SECOND,		\
						      trip_d_d_d )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      SECOND,		\
						      trip_u_d_d )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      THIRD,		\
						      quad_d_d_d_d )	\
  UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_INSTANT( type,		\
						      name,		\
						      THIRD,		\
						      quad_u_u_d_d )	\

#define UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_2_ARRAY( type, name, array ) \
  TUPLE_TYPEDEFS()							\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    FIRST,	\
							    pair_d_u,	\
							    trip_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    SECOND,	\
							    pair_d_u,	\
							    pair_u_d,	\
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    THIRD,	\
							    trip_d_d_u, \
							    trip_u_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    FOURTH,	\
							    quad_u_d_d_d, \
							    quad_d_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    FIRST,	\
							    pair_d_u,	\
							    pair_u_d,	\
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    SECOND,	\
							    trip_u_u_d, \
							    trip_d_u_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    THIRD,	\
							    trip_d_u_d, \
							    trip_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    FOURTH,	\
							    quad_u_u_d_d, \
							    quad_u_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    THIRD,	\
							    FIRST,	\
							    trip_d_d_u, \
							    trip_u_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    THIRD,	\
							    SECOND,	\
							    trip_d_u_d, \
							    trip_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    THIRD,	\
							    THIRD,	\
							    trip_d_d_d, \
							    trip_u_u_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    THIRD,	\
							    FOURTH,	\
							    quad_d_d_d_d, \
							    quad_u_u_u_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FOURTH,	\
							    FIRST,	\
							    quad_u_d_d_d, \
							    quad_d_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FOURTH,	\
							    SECOND,	\
							    quad_u_u_d_d, \
							    quad_u_d_d_u, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FOURTH,	\
							    THIRD,	\
							    quad_d_d_d_d, \
							    quad_u_u_u_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_INSTANT( type, \
							    name, \
							    FOURTH, \
							    FOURTH, \
							    quad_d_d_d_u, \
							    quad_u_u_u_u, \
							    array )	\

#define UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_1_ARRAY( type, name, array ) \
  TUPLE_TYPEDEFS()							\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    SECOND,	\
							    pair_d_d,	\
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    THIRD,	\
							    trip_d_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    FIRST,	\
							    FOURTH,	\
							    quad_d_d_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    THIRD,	\
							    trip_u_d_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    SECOND,	\
							    FOURTH,	\
							    quad_u_d_u_d, \
							    array )	\
  UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_INSTANT( type,	\
							    name,	\
							    THIRD,	\
							    FOURTH,	\
							    quad_d_d_u_u, \
							    array )	\

//---------------------------------------------------------------------------//
// Testing Structs.
//---------------------------------------------------------------------------//

class TestDataProcessor : public Utility::DataProcessor
{
public:
  TestDataProcessor()
  { /* ... */ }

  virtual ~TestDataProcessor()
  { /* ... */ }

  void processDataFiles()
  { /* ... */ }

  // Allow public access to the DataProcessor protected member functions
  using Utility::DataProcessor::processContinuousData;
  using Utility::DataProcessor::removeElementsLessThanValue;
  using Utility::DataProcessor::removeElementsGreaterThanValue;
  using Utility::DataProcessor::coarsenConstantRegions;
  using Utility::DataProcessor::calculateSlopes;
  using Utility::DataProcessor::calculateContinuousCDF;
  using Utility::DataProcessor::calculateDiscreteCDF;
  using Utility::DataProcessor::copyTupleMemberData;
  using Utility::DataProcessor::swapTupleMemberData;
  using Utility::DataProcessor::uintToShellStr;
};

typedef Utility::LogLogDataProcessing LogLogDataProcessing;
typedef Utility::SqrSqrDataProcessing SqrSqrDataProcessing;

template<typename ProcessingPolicy>
struct ProcessingPolicyTestingTraits
{
  static const double referenceIndepValue;
  static const double referenceDepValue;
};

template<typename ProcessingPolicy>
const double ProcessingPolicyTestingTraits<ProcessingPolicy>::referenceIndepValue = 0.0;

template<typename ProcessingPolicy>
const double ProcessingPolicyTestingTraits<ProcessingPolicy>::referenceDepValue = 0.0;

template<>
struct ProcessingPolicyTestingTraits<Utility::LogLogDataProcessing>
{
  static const double referenceIndepValue;
  static const double referenceDepValue;
};

const double ProcessingPolicyTestingTraits<Utility::LogLogDataProcessing>::referenceIndepValue = LOG_INDEP_VAR;

const double ProcessingPolicyTestingTraits<Utility::LogLogDataProcessing>::referenceDepValue = LOG_DEP_VAR;

template<>
struct ProcessingPolicyTestingTraits<Utility::SqrSqrDataProcessing>
{
  static const double referenceIndepValue;
  static const double referenceDepValue;
};

const double ProcessingPolicyTestingTraits<Utility::SqrSqrDataProcessing>::referenceIndepValue = SQR_INDEP_VAR;

const double ProcessingPolicyTestingTraits<Utility::SqrSqrDataProcessing>::referenceDepValue = SQR_DEP_VAR;

//---------------------------------------------------------------------------//
// Helper functions.
//---------------------------------------------------------------------------//
template<Utility::TupleMember member, typename T, template<typename> class Array>
void fillArrayOneTupleMemberData( Array<T> &array )
{
  typedef typename Utility::TupleMemberTraits<T,member>::tupleMemberType
    tupleMemberType;

  typename Array<T>::size_type size = Utility::getArraySize( array );

  if( size > 0 )
  {
    for( unsigned int i = 1; i <= size; ++i )
    {
      Utility::set<member>( array[i-1], static_cast<tupleMemberType>( i ) );
    }
  }
}

template<Utility::TupleMember indepMember,
	 Utility::TupleMember depMember,
	 typename T,
	 template<typename> class Array>
void fillArrayTwoTupleMemberData( Array<T> &array )
{
  typedef typename Utility::TupleMemberTraits<T,indepMember>::tupleMemberType indepTupleMemberType;
  typedef typename Utility::TupleMemberTraits<T,depMember>::tupleMemberType depTupleMemberType;

  typename Array<T>::size_type size = Utility::getArraySize( array );

  if( size > 0 )
  {
    for( unsigned int i = 0; i < size; ++i )
    {
      Utility::set<indepMember>( array[i],
		            static_cast<indepTupleMemberType>( i*INDEP_VAR ) );
      Utility::set<depMember>( array[i],
		                static_cast<depTupleMemberType>( i*DEP_VAR ) );
    }
  }
}

//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the DataProcessingPolicies correctly process data
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DataProcessor,
				   DataProcessingPolicy,
				   Policy )
{
  double processed_indep_var, processed_dep_var;
  processed_indep_var = Policy::processIndependentVar( INDEP_VAR );
  processed_dep_var = Policy::processDependentVar( DEP_VAR );

  double ref_indep_var, ref_dep_var;
  ref_indep_var = ProcessingPolicyTestingTraits<Policy>::referenceIndepValue;
  ref_dep_var = ProcessingPolicyTestingTraits<Policy>::referenceDepValue;

  TEST_FLOATING_EQUALITY( processed_indep_var, ref_indep_var, TOL );
  TEST_FLOATING_EQUALITY( processed_dep_var, ref_dep_var, TOL );
}

UNIT_TEST_INSTANTIATION_POLICY( DataProcessor, DataProcessingPolicy );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can processes an array of UTILITY Tuple structs
// in the desired format
TEUCHOS_UNIT_TEST_TEMPLATE_2_DECL( DataProcessor,
				   processContinuousData,
				   Policy,
				   Tuple )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Tuple data_point;
  data_point.first = INDEP_VAR;
  data_point.second = DEP_VAR;
  Teuchos::Array<Tuple> processed_data( 10, data_point );

  // Load the reference array
  data_point.first = ProcessingPolicyTestingTraits<Policy>::referenceIndepValue;
  data_point.second = ProcessingPolicyTestingTraits<Policy>::referenceDepValue;
  Teuchos::Array<Tuple> ref_data( 10, data_point );

  // Process the Array
  data_processor.processContinuousData<Policy,
				       Utility::FIRST,
				       Utility::SECOND>( processed_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( processed_data, ref_data, TOL );
}

UNIT_TEST_INSTANTIATION_POLICY_TUPLE( DataProcessor, processContinuousData );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can remove elements with a tuple member less
// than a specified value
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DataProcessor,
				   removeElementsLessThanValue,
				   Tuple )
{
  TestDataProcessor data_processor;

  Teuchos::Array<Tuple> ref_data( 10 ), clipped_data( 10 );

  // Load the reference array
  fillArrayOneTupleMemberData<Utility::FIRST>( ref_data );

  // Load the clipped array
  clipped_data = ref_data;

  // Set the lower bound to the min value in the array and clip the array
  double lower_bound = Utility::get<Utility::FIRST>( ref_data.front() );
  data_processor.removeElementsLessThanValue<Utility::FIRST>( clipped_data,
							     lower_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data );

  // Set the lower bound to a value less than the min value in the array and
  // clip the array
  clipped_data = ref_data;
  lower_bound = 0.0;
  data_processor.removeElementsLessThanValue<Utility::FIRST>( clipped_data,
							     lower_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data );

  // Set the lower bound to a value greater than the min value but between
  // two bin boundaries and clip the array
  clipped_data = ref_data;
  lower_bound = (Utility::get<Utility::FIRST>( ref_data[2] ) +
		 Utility::get<Utility::FIRST>( ref_data[1] ) )/2.0;
  data_processor.removeElementsLessThanValue<Utility::FIRST>( clipped_data,
							     lower_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data( 1, ref_data.size()-1 ) );

  // Set the lower bound to a value greater than the min value but on
  // a bin boundary and clip the array
  clipped_data = ref_data;
  lower_bound = Utility::get<Utility::FIRST>( ref_data[2] );
  data_processor.removeElementsLessThanValue<Utility::FIRST>( clipped_data,
							     lower_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data( 2, ref_data.size()-2 ) );
}

UNIT_TEST_INSTANTIATION_TUPLE( DataProcessor, removeElementsLessThanValue );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can remove elements with a tuple member greater
// than a specified value
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DataProcessor,
				   removeElementsGreaterThanValue,
				   Tuple )
{
  TestDataProcessor data_processor;

  Teuchos::Array<Tuple> ref_data( 10 ), clipped_data( 10 );

  // Load the reference array
  fillArrayOneTupleMemberData<Utility::FIRST>( ref_data );

  // Load the clipped array
  clipped_data = ref_data;

  // Set the upper bound to the max value in the array and clip the array
  double upper_bound = Utility::get<Utility::FIRST>( ref_data.back() );
  data_processor.removeElementsGreaterThanValue<Utility::FIRST>( clipped_data,
								upper_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data );

  // Set the upper bound to a value greater than the max value in the array and
  // clip the array
  clipped_data = ref_data;
  upper_bound = Utility::get<Utility::FIRST>( ref_data.back() ) + 1.0;
  data_processor.removeElementsGreaterThanValue<Utility::FIRST>( clipped_data,
								upper_bound );

  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data );

  // Set the upper bound to a value less than the max value but between
  // two bin boundaries and clip the array
  clipped_data = ref_data;
  upper_bound = (Utility::get<Utility::FIRST>( ref_data[ref_data.size()-2] ) +
		 Utility::get<Utility::FIRST>( ref_data[ref_data.size()-3]))/2.0;
  data_processor.removeElementsGreaterThanValue<Utility::FIRST>( clipped_data,
								upper_bound );
  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data( 0, ref_data.size()-1 ) );

  // Set the upper bound to a value less than the max value but on
  // a bin boundary and clip the array
  clipped_data = ref_data;
  upper_bound = Utility::get<Utility::FIRST>( ref_data[ref_data.size()-3] );
  data_processor.removeElementsGreaterThanValue<Utility::FIRST>( clipped_data,
								upper_bound );
  UTILITY_TEST_COMPARE_ARRAYS( clipped_data, ref_data( 0, ref_data.size()-2 ) );
}

UNIT_TEST_INSTANTIATION_TUPLE( DataProcessor, removeElementsGreaterThanValue );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can coarsen constant regions in an array
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DataProcessor,
				   coarsenConstantRegions,
				   Tuple )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Tuple data_point;
  data_point.first = INDEP_VAR;
  data_point.second = DEP_VAR;
  Teuchos::Array<Tuple> coarsened_data( 10, data_point );

  // Load the reference array
  data_point.first = INDEP_VAR;
  data_point.second = DEP_VAR;
  Teuchos::Array<Tuple> reference_data( 2, data_point );

  // Coarsen the array
  data_processor.coarsenConstantRegions<Utility::SECOND>( coarsened_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( coarsened_data, reference_data, TOL );
}

UNIT_TEST_INSTANTIATION_TUPLE( DataProcessor, coarsenConstantRegions );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can calculate the slopes between all pairs
// of data points in an array and store in the desired tuple member
UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_DECL( DataProcessor,
						       calculateSlopes,
						       member,
						       Tuple,
						       array )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple> raw_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( raw_data );
  array<Tuple> processed_data;
  Utility::copyArrayView( processed_data, raw_data() );

  // Load the reference array
  Teuchos::Array<Tuple> ref_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( ref_data );

  double slope = 0.0;
  for( unsigned int i = 0; i < ref_data.size(); ++i )
  {
    if( i != ref_data.size() - 1 )
    {
      slope = (ref_data[i+1].second - ref_data[i].second)/
	(ref_data[i+1].first - ref_data[i].first);
      Utility::set<member>( ref_data[i], slope );
    }
    else
      Utility::set<member>( ref_data[i], 0.0 );
  }

  // Processes the array
  data_processor.calculateSlopes<Utility::FIRST,
				 Utility::SECOND,
				 member>( processed_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( processed_data, ref_data, TOL );
}

UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateSlopes, Array );
UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateSlopes, ArrayView );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can calculate a continuous cdf from an array
// of data and store in the desired tuple member
UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_DECL( DataProcessor,
						       calculateContinuousCDF,
						       member,
						       Tuple,
						       array )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple> raw_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( raw_data );
  array<Tuple> processed_data;
  Utility::copyArrayView( processed_data, raw_data() );

  // Load the reference array
  Teuchos::Array<Tuple> ref_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( ref_data );
  double cdf_value;

  for( unsigned int i = 0; i < ref_data.size(); ++i )
  {
    if( i != 0 )
    {
      cdf_value += 0.5*(ref_data[i].first - ref_data[i-1].first)*
	(ref_data[i].second + ref_data[i-1].second);
    }
    else
      cdf_value = 0.0;

    Utility::set<member>( ref_data[i], cdf_value );
  }

  double norm_value = Utility::get<member>( ref_data.back() );
  for( unsigned int i = 0; i < ref_data.size(); ++i )
  {
    ref_data[i].second /= norm_value;
    Utility::set<member>( ref_data[i],
			 Utility::get<member>( ref_data[i] )/norm_value );
  }

  // Processes the array
  data_processor.calculateContinuousCDF<Utility::FIRST,
					Utility::SECOND,
					member>( processed_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( processed_data, ref_data, TOL );
}

UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateContinuousCDF, Array );
UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateContinuousCDF, ArrayView );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can calculate a continuous pdf from an array
// of data and store in the desired tuple member
UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_ARRAY_TEMPLATE_DECL( DataProcessor,
							calculateContinuousPDF,
							member,
							Tuple,
							array )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple> raw_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( raw_data );
  array<Tuple> processed_data;
  Utility::copyArrayView( processed_data, raw_data() );

  // Load the reference array
  Teuchos::Array<Tuple> ref_data( 10 );
  fillArrayTwoTupleMemberData<Utility::FIRST,Utility::SECOND>( ref_data );
  double pdf_value;

  for( unsigned int i = 0; i < ref_data.size(); ++i )
  {
    if( i != 0 )
    {
      pdf_value = (ref_data[i].second - ref_data[i-1].second)/
	(ref_data[i].first - ref_data[i-1].first);
    }
    else
    {
      pdf_value = (ref_data[i+1].second - ref_data[i].second)/
	(ref_data[i+1].first - ref_data[i].second);
    }

    Utility::set<member>( ref_data[i], pdf_value );
  }

  // Processes the array
  data_processor.calculateContinuousPDF<Utility::FIRST,
					member,
					Utility::SECOND>( processed_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( processed_data, ref_data, TOL );
}

UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateContinuousPDF, Array );
UNIT_TEST_INSTANTIATION_MEMBER_1_TUPLE_1_ARRAY( DataProcessor, calculateContinuousPDF, ArrayView );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can calculate a discrete cdf from an array
// of data in place
UTILITY_UNIT_TEST_MEMBER_1_TUPLE_1_TEMPLATE_DECL( DataProcessor,
						 calculateDiscreteCDF,
						 member,
						 Tuple )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple> processed_data( 10 );
  fillArrayOneTupleMemberData<member>( processed_data );

  // Load the reference array
  Teuchos::Array<Tuple> ref_data( 10 );
  fillArrayOneTupleMemberData<member>( ref_data );

  for( unsigned int i = 1; i < ref_data.size(); ++i )
  {
    Utility::set<member>( ref_data[i], Utility::get<member>( ref_data[i-1] ) +
			 Utility::get<member>( ref_data[i] ) );
  }

  for( unsigned int i = 0; i < ref_data.size(); ++i )
  {
    Utility::set<member>( ref_data[i], Utility::get<member>( ref_data[i] )/
			 Utility::get<member>( ref_data.back() ) );
  }

  // Processes the array
  data_processor.calculateDiscreteCDF<member,
  				      member>( processed_data );

  UTILITY_TEST_COMPARE_FLOATING_ARRAYS( processed_data, ref_data, TOL );
}

UNIT_TEST_INSTANTIATION_MEMBER_TUPLE( DataProcessor, calculateDiscreteCDF );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can swap data in one member of a tuple with
// data in another member (for all tuples in an array)
UTILITY_UNIT_TEST_MEMBER_2_TUPLE_2_ARRAY_TEMPLATE_DECL( DataProcessor,
						       copyTupleMemberData,
						       Member1,
						       Member2,
						       Tuple1,
						       Tuple2,
						       array )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple1> raw_original_data( 10 );
  fillArrayOneTupleMemberData<Member1>( raw_original_data );
  array<Tuple1>  original_data;
  Utility::copyArrayView( original_data, raw_original_data() );

  Teuchos::Array<Tuple2> raw_processed_data( raw_original_data.size() );
  array<Tuple2> processed_data;
  Utility::copyArrayView( processed_data, raw_processed_data() );

  // Load the reference array
  Teuchos::Array<Tuple2> ref_data( 10 );
  fillArrayOneTupleMemberData<Member2>( ref_data );

  // Process the array
  data_processor.copyTupleMemberData<Member1,Member2>( original_data,
						       processed_data );

  UTILITY_TEST_COMPARE_ARRAYS( processed_data, ref_data );
}

UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_2_ARRAY( DataProcessor, copyTupleMemberData, Array );
UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_2_ARRAY( DataProcessor, copyTupleMemberData, ArrayView );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can swap data in one member with data in
// another member (for all tuples in an array)
UTILITY_UNIT_TEST_MEMBER_2_TUPLE_1_ARRAY_TEMPLATE_DECL( DataProcessor,
						       swapTupleMemberData,
						       Member1,
						       Member2,
						       Tuple,
						       array )
{
  TestDataProcessor data_processor;

  // Load the array to be processed
  Teuchos::Array<Tuple> raw_data( 10 );
  fillArrayOneTupleMemberData<Member1>( raw_data );
  array<Tuple>  processed_data;
  Utility::copyArrayView( processed_data, raw_data() );

  // Load the reference array
  Teuchos::Array<Tuple> ref_data( 10 );
  fillArrayOneTupleMemberData<Member2>( ref_data );

  // Process the array
  data_processor.swapTupleMemberData<Member1,Member2>( processed_data );

  UTILITY_TEST_COMPARE_ARRAYS( processed_data, ref_data );
}

UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_1_ARRAY( DataProcessor, swapTupleMemberData, Array );
UNIT_TEST_INSTANTIATION_MEMBER_2_TUPLE_1_ARRAY( DataProcessor, swapTupleMemberData, ArrayView );

//---------------------------------------------------------------------------//
// Check that the DataProcessor can convert an unsigned int to a string
TEUCHOS_UNIT_TEST( DataProcessor, uint_to_string_test )
{
  TestDataProcessor data_processor;

  std::string shell = data_processor.uintToShellStr( SHELL );
  std::string reference_shell( SHELL_NAME );

  TEST_EQUALITY( shell, reference_shell );
}

//---------------------------------------------------------------------------//
// end tstDataProcessor.cpp
//---------------------------------------------------------------------------//


text:
package example.springdata.jpa.security;

import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author Thomas Darimont
 */
@Entity
@Data
@RequiredArgsConstructor
public class User {

	private @Id @GeneratedValue @Getter Long id;
	private final String firstname, lastname, emailAddress;

	@SuppressWarnings("unused")
	private User() {

		this.firstname = null;
		this.lastname = null;
		this.emailAddress = null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
'''Quick and dirty way to show your data.'''

import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.decomposition import PCA

def plot2d(data, target, target_names=None):
    '''Show data reduced to 2 dimensions as scatter plot.
    Colors mark the different labels.
    '''
    pca = PCA(n_components=2, whiten=True)
    compressed = pca.fit_transform(data)
    target_names = set(target) if target_names is None else target_names
    colors = cycle('rgbcmykw')
    target_ids = range(len(target_names))
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    for i, c, label in zip(target_ids, colors, target_names):
        ax.scatter(compressed[target == i, 0], compressed[target == i, 1],
                   c=c, label=label)
    ax.legend()
    return fig

if __name__ == '__main__':
    from sklearn.datasets import load_iris
    iris = load_iris()
    fig = plot2d(iris.data, iris.target, iris.target_names)
    plt.show()  # We use plt.show so it'll block until the image is closed


text:
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using Fluid.Values;

namespace Fluid.Benchmarks
{
    [MemoryDiagnoser]
    public class FluidValueBenchmarks
    {
        // many interfaces, none of which is dictionary
        private static readonly List<string> nonDictionaryType = new();

        private static readonly TemplateOptions options = new();

        [Benchmark]
        public FluidValue CreateFromList()
        {
            return FluidValue.Create(nonDictionaryType, options);
        }
    }
}


text:
namespace yas::proc {
using channel_index_t = int64_t;
using track_index_t = int64_t;
using frame_index_t = int64_t;
using module_index_t = std::size_t;
using length_t = uint64_t;
using sample_rate_t = uint32_t;

using connector_index_t = uint32_t;
using connector_index_set_t = std::unordered_set<connector_index_t>;

enum class continuation {
    abort,
    keep,
};
}  // namespace yas::proc


text:
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define([
            '$',
            'plugin',
            'bouncefix',
            'velocity',
            'lockup',
            'shade',
            'deckard'
        ], factory);
    } else {
        var framework = window.Zepto || window.jQuery;
        factory(framework, window.Plugin, window.bouncefix);
    }
}(function($, Plugin, bouncefix, Velocity) {
    var EFFECT_REQUIRED = 'Pikabu requires a declared effect to operate. For more information read: https://github.com/mobify/pikabu#initializing-the-plugin';
    var FOCUSABLE_ELEMENTS = 'a[href], area[href], input, select, textarea, button, iframe, object, embed, [tabindex], [contenteditable]';
    var FOCUSABLE_INPUT_ELEMENTS = 'input, select, textarea';

    /**
     * Function.prototype.bind polyfill required for < iOS6
     */
    /* jshint ignore:start */
    if (!Function.prototype.bind) {
        Function.prototype.bind = function(scope) {
            var fn = this;
            return function() {
                return fn.apply(scope);
            };
        };
    }
    /* jshint ignore:end */

    var iOS7orBelow = $.os.ios && $.os.major <= 7;

    var classes = {
        PIKABU: 'pikabu__drawer',
        ELEMENT: 'pikabu__element',
        CONTAINER: 'pikabu__container',
        VIEWPORT: 'pikabu',
        HEADER: 'pikabu__header',
        WRAPPER: 'pikabu__wrapper',
        SPACER: 'pikabu__spacer',
        TITLE: 'pikabu__title',
        CLOSE: 'pikabu__close',
        CONTENT: 'pikabu__content',
        OPENED: 'pikabu--is-open',
        SCROLLABLE: 'pikabu--is-scrollable',
        FIXED: 'pikabu__fixed'
    };

    /**
     * Template constants required for building the default HTML structure
     */
    var template = {
        COMPONENT: '<{0} class="' + classes.PIKABU + '__{0}">{1}</{0}>',
        HEADER: '
{0}
<button class="' + classes.CLOSE + '">Close</button>',
        FOOTER: '{0}'
    };

    var events = {
        click: 'click.pikabu',
        focus: 'focus.pikabu',
        blur: 'blur.pikabu'
    };

    function Pikabu(element, options) {
        Pikabu.__super__.call(this, element, options, Pikabu.DEFAULTS);
    }

    Pikabu.VERSION = '2.0.0';

    Pikabu.DEFAULTS = {
        effect: null,
        container: $('.' + classes.CONTAINER),
        appendTo: $('.' + classes.VIEWPORT),
        structure: {
            header: false,
            footer: false
        },
        zIndex: 0,
        cssClass: '',
        coverage: '100%',
        easing: 'swing',
        duration: 200,
        shade: {
            zIndex: 2
        },
        open: $.noop,
        opened: $.noop,
        close: $.noop,
        closed: $.noop,
        scrollDuration: 50,
        spacerHeight: 300
    };

    Plugin.create('pikabu', Pikabu, {
        /**
         * Common animation callbacks used in the effect objects
         */
        animation: {
            beginClose: function() {
                this.options.shade && this.$shade.shade('close');
            },
            openComplete: function() {
                this._trigger('opened');
                this._focus();

                // Fixes an issue with collapsed browser chrome in iOS8
                window.scrollTo(0,0);
            },
            closeComplete: function() {
                this._trigger('closed');

                this._resetFocus();

                this.$viewport.removeClass(classes.OPENED);
                this.$viewport.css('height', '');
                this.$animators.css('transform', '');
                this.$pikabu.lockup('unlock');
                this.$pikabu.hide();
            }
        },

        _init: function(element) {
            this.id = 'pikabu-' + $.uniqueId();

            this.$element = $(element);
            this.$doc = $(document);
            this.$body = $('body');
            this.$animators = $('.' + classes.CONTAINER + ', ' + '.' + classes.FIXED);

            this._build();

            if (!this.options.effect) {
                throw EFFECT_REQUIRED;
            }

            this.effect = this.options.effect.call(this);

            this.$element.removeAttr('hidden');

            this._bindEvents();
        },

        toggle: function() {
            this[this.$pikabu.hasClass(classes.OPENED) ? 'close' : 'open']();
        },

        open: function() {
            if (this._isOpen() || this._isAnimating()) {
                return;
            }

            this._trigger('open');

            bouncefix.add(classes.SCROLLABLE);

            this.$pikabu.lockup('lock');
            this.$pikabu.show();

            this.$viewport.height(window.innerHeight);

            this.effect.open.call(this);

            this.options.shade && this.$shade.shade('open');

            this.$pikabu.addClass(classes.OPENED);
            this.$viewport.addClass(classes.OPENED);
        },

        close: function() {
            var plugin = this;

            if (!this._isOpen() || this._isAnimating()) {
                return;
            }

            this._trigger('close');

            bouncefix.remove(classes.SCROLLABLE);

            this.$pikabu.removeClass(classes.OPENED);

            this.effect.close.call(this);
        },

        _isOpen: function() {
            return this.$pikabu.hasClass(classes.OPENED);
        },

        _isAnimating: function() {
            return this.$container.hasClass('velocity-animating');
        },

        _bindEvents: function() {
            // Block scrolling on anything but pikabu content
            this.$pikabu.on('touchmove', function(e) {
                if (!$(e.target).parents().hasClass(classes.CONTENT)) {
                    e.preventDefault();
                }
            });
        },

        /**
         Builds Pikabu using the following structure:

                 {header content}

                 {content}

                 {footer content}

         */
        _build: function() {
            var plugin = this;

            this.$pikabu = $('
')
                .addClass(classes.PIKABU)
                .addClass(this.options.cssClass)
                .css({
                    position: 'fixed',
                    zIndex: this.options.zIndex,
                    width: this.options.coverage,
                    height: this.options.coverage
                })
                .on(events.click, '.' + classes.CLOSE, function(e) {
                    e.preventDefault();
                    plugin.close();
                })
                .lockup({
                    container: this.options.container,
                    locked: function () {
                        plugin._handleKeyboardShown();
                    },
                    unlocked: function () {
                        plugin._handleKeyboardHidden();
                    }
                });

            this.$viewport = $('.' + classes.VIEWPORT);

            this.$container = this.$pikabu.data('lockup').$container.addClass(classes.CONTAINER);

            this.$pikabu.appendTo(this.options.appendTo ? $(this.options.appendTo) : this.$container);

            if (this.options.structure) {
                var $wrapper = $('
')
                    .addClass(classes.WRAPPER)
                    .appendTo(this.$pikabu);

                this._buildComponent('header').appendTo($wrapper);

                $('
')
                    .addClass(classes.CONTENT)
                    .addClass(classes.SCROLLABLE)
                    .append(this.$element.addClass(classes.ELEMENT))
                    .append(this.$spacer)
                    .appendTo($wrapper);

                this._buildComponent('footer').appendTo($wrapper);
            } else {
                this.$element
                    .addClass(classes.ELEMENT)
                    .appendTo(this.$pikabu);
            }

            this.$header = this.$pikabu.find('.' + classes.HEADER);
            this.$content = this.$pikabu.find('.' + classes.CONTENT);

            this.$spacer = $('
')
                .addClass(classes.SPACER)
                .height(this.options.spacerHeight)
                .attr('hidden', 'hidden')
                .appendTo(this.$content);

            this._addAccessibility();

            if (this.options.shade) {
                this.$shade = this.$viewport.shade(
                    $.extend(
                        true,
                        this.options.shade,
                        {
                            append: 'appendTo',
                            click: function() {
                                $('.' + classes.ELEMENT).pikabu('close');
                            }
                        }
                    )
                );

                this.$shadeEl = this.$viewport.shade('getElement');
            }
            this.$animators = this.$animators.add(this.$shadeEl);
        },

        _buildComponent: function(name) {
            var component = this.options.structure[name];
            var $element = $([]);

            if (component !== false) {
                var html = this._isHtml(component) ? component : template[name.toUpperCase()].replace('{0}', component);

                $element = $(template.COMPONENT.replace(/\{0\}/g, name).replace(/\{1\}/g, html));
            }

            return $element;
        },

        _isHtml: function(input) {
            return /<[a-z][\s\S]*>/i.test(input);
        },

        /**
         * Takes the coverage option and turns it into a effect value
         */
        _coverage: function(divisor) {
            var coverage;
            var percent = this.options.coverage.match(/(\d*)%$/);

            if (percent) {
                coverage = 100 - parseInt(percent[1]);

                if (divisor) {
                    coverage = coverage / divisor;
                }
            }

            return percent ? coverage + '%' : this.options.coverage;
        },

        /**
         * Accessibility Considerations
         */
        _addAccessibility: function() {
            var headerID = this.id + '__header';
            var $header = this.$pikabu.find('h1, .' + classes.TITLE).first();
            var $wrapper = this.$pikabu.find('.' + classes.WRAPPER);

            this.$container
                .attr('aria-hidden', 'false');

            this.$pikabu
                .attr('role', 'dialog')
                .attr('aria-labelledby', headerID)
                .attr('aria-hidden', 'true')
                .attr('tabindex', '-1');

            $wrapper
                .attr('role', 'document');

            $header
                .attr('id', headerID);
        },

        _focus: function() {
            this.originalActiveElement = document.activeElement;

            this._disableInputs();

            this.$pikabu.attr('aria-hidden', 'false');

            this.$pikabu.children().first().focus();

            this.$container.attr('aria-hidden', 'true');
        },

        _resetFocus: function() {
            this._enableInputs();

            this.$container.attr('aria-hidden', 'false');

            this.$pikabu.attr('aria-hidden', 'true');

            this.originalActiveElement.focus();
        },

        /**
         * Traps any tabbing within the visible Pikabu window
         * by disabling tabbing into all inputs outside of
         * pikabu using a negative tabindex.
         */
        _disableInputs: function() {
            var $focusableElements = $(FOCUSABLE_ELEMENTS).not(function() {
                return $(this).closest('.pikabu').length;
            });

            $focusableElements.each(function(_, el) {
                var $el = $(el);
                var currentTabIndex = $el.attr('tabindex') || 0;

                $el
                    .data('tabindex', currentTabIndex)
                    .attr('tabindex', '-1');
            });
        },

        /**
         * Reverses the above!!
         */
        _enableInputs: function() {
            var $disabledInputs = $('[data-pikabu-tabindex]');

            $disabledInputs.each(function(_, el) {
                var $el = $(el);
                var oldTabIndex = $el.data('tabindex');

                if (oldTabIndex) {
                    $el.attr('tabindex', oldTabIndex);
                } else {
                    $el.removeAttr('tabindex');
                }

                $el.removeData('tabindex');
            });
        },

        /**
         * In iOS7 or below, when elements are focussed inside pikabu
         * the keyboard obscures the input. We need to scroll back to
         * the element to keep it in view.
         */
        _handleKeyboardShown: function() {
            if (iOS7orBelow) {
                this.$pikabu.find(FOCUSABLE_INPUT_ELEMENTS)
                    .on(events.focus, this._inputFocus.bind(this))
                    .on(events.blur, this._inputBlur.bind(this));
            }
        },

        _handleKeyboardHidden: function() {
            if (iOS7orBelow) {
                this.$pikabu.find(FOCUSABLE_INPUT_ELEMENTS)
                    .off(events.focus)
                    .off(events.blur);
            }
        },

        /**
         * In iOS7 or below, when inputs are focussed inside pikabu, we show a
         * spacer element at the bottom of pikabu content so that it creates space
         * in the viewport to facilitate scrolling back to the element.
         */
        _inputFocus: function () {
            this.$spacer.removeAttr('hidden');

            Velocity.animate(this._scrollTarget(), 'scroll', {
                container: this.$content[0],
                offset: -1 * (this.$header.height() + parseInt(this.$content.css('padding-top'))),
                duration: this.options.scrollDuration
            });
        },

        _inputBlur: function () {
            !this._activeElement().is(FOCUSABLE_INPUT_ELEMENTS) && this.$spacer.attr('hidden', '');
        },

        _activeElement: function () {
            return $(document.activeElement);
        },

        /**
         * Returns the closest parent element that doesn't have relative positioning
         * (within the pikabu__content container). Relative positioning messes with
         * Velocity's scroll, which prevents us from correctly scrolling back to active
         * inputs in pikabu__content.
         */
        _scrollTarget: function () {
            var $scrollTarget = this._activeElement();
            var $activeElementParent = $scrollTarget.parent();

            while ($activeElementParent.css('position') === 'relative' && !$activeElementParent.hasClass(classes.CONTENT)) {
                $scrollTarget = $activeElementParent;
                $activeElementParent = $scrollTarget.parent();
            }

            return $scrollTarget;
        }
    });

    $('[data-pikabu]').each(function() {
        var $pikabu = $(this);
        var effect = $(this).data('pikabu');

        if (!effect.length) {
            throw EFFECT_REQUIRED;
        }

        $pikabu.pikabu({
            effect: effect
        });
    });

    return $;
}));


text:
Brocchinia is a Framework who work with OpenFL.
It provide many management to easily develop a game, and to manage the ressources.

This project is OpenSource, under a MIT licence, so you are free to work on it, and with it, just please, talk about us in the credits, for the engine, if you use it.

Notice that some of the features there aren't totally finished or tested yet.


text:
LuCI - Lua Configuration Interface

Copyright 2008 Steven Barth <steven@midlink.org>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

$Id$
]]--

m = Map("w8021x", translate("Wired 802.1X Authentication"),
	translate("IEEE 802.1X Authentication for Wired Networks is mainly used in many campus networks."))

s = m:section(TypedSection, "item", translate("Items"))
s.template = "cbi/tblsection"
s.extedit  = luci.dispatcher.build_url("admin/network/w8021x/item/%s")
s.addremove = true
s.anonymous = true

function s.create(...)
	local id = TypedSection.create(...)
	luci.http.redirect(s.extedit % id)
end

function s.remove(self, section)
	if m.uci:get("w8021x", section) == "item" then
		local iface = m.uci:get("w8021x", section, "interface")
	end

	return TypedSection.remove(self, section)
end

o = s:option(Flag, "auto", translate("Auth on boot"))
o.rmempty = false
o.width   = "120px"
function o.cfgvalue(...)
	local v = Flag.cfgvalue(...)
	return v == "1" and "1" or "0"
end
function o.write(self, section, value)
	Flag.write(self, section, value == "1" and "1" or "0")
end

o = s:option(DummyValue, "identity", translate("Identity"))
o.width    = "16%"
function o.cfgvalue(...)
	local v = Value.cfgvalue(...) or ("<%s>" % translate("Unknown"))
	return v
end

o = s:option(DummyValue, "method", translate("EAP-Method"))
o.width    = "15%"
function o.cfgvalue(...)
	local v = Value.cfgvalue(...)
	if v == "md5" then
		v = translate("MD5-Challenge")
	else
		v = translate("Protected EAP (PEAP)")
	end
	return v
end

o = s:option(DummyValue, "interface", translate("Interface"))
o.template = "cbi/network_netinfo"
o.width    = "10%"

o = s:option(DummyValue, "_status", translate("Status"))
o.template = "w8021x/w8021x_eap_status"
o.width    = "12%"

o = s:option(DummyValue, "_action", translate("Action"))
o.template = "w8021x/w8021x_eap_action"
o.width    = "10%"

return m


text:
autocommit off;

insert into joe.employees_v
select ssn, name, dept_no
  from joe.employee_c;
rollback work;
rollback;


text:
class CreateSupportingInventoryResponse < ActiveRecord::Migration
  def change
    create_table :supporting_inventory_responses do |t|
      t.references :score, index: true
      t.integer :product_entries, default: [], array: true, null: false
      t.integer :data_entries, default: [], array: true, null: false
      t.text :product_entry_evidence
      t.text :data_entry_evidence
      t.timestamps null: false
    end
  end
end


text:
<?php

namespace Jc\JolieCarBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Proprietaire
 *
 * @ORM\Table(name="proprietaire")
 * @ORM\Entity(repositoryClass="Jc\JolieCarBundle\Entity\ProprietaireRepository")
 */
class Proprietaire
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     * @Assert\NotBlank(message="Veuillez fournir le nom du Proprietaire")
     */
    private $nom;

    /**
     * @ORM\OneToMany(targetEntity="Voiture", mappedBy="proprietaire")
     */
    private $voitures;

    /**
     * @ORM\OneToOne(targetEntity="Adresse")
     * @Assert\Valid()
     */
    private $adresse;

    /**
     * @ORM\ManyToOne(targetEntity="TypeProprietaire",inversedBy="proprietaires")
     * @Assert\Valid()
     */
    private $typeProprietaire;
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nom
     *
     * @param string $nom
     * @return Proprietaire
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->voiture = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add voiture
     *
     * @param \Jc\JolieCarBundle\Entity\Voiture $voiture
     * @return Proprietaire
     */
    public function addVoiture(Voiture $voiture)
    {
        $this->voiture[] = $voiture;

        return $this;
    }

    /**
     * Remove voiture
     *
     * @param \Jc\JolieCarBundle\Entity\Voiture $voiture
     */
    public function removeVoiture(Voiture $voiture)
    {
        $this->voiture->removeElement($voiture);
    }

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

    /**
     * Set adresse
     *
     * @param \Jc\JolieCarBundle\Entity\Adresse $adresse
     * @return Proprietaire
     */
    public function setAdresse(Adresse $adresse = null)
    {
        $this->adresse = $adresse;

        return $this;
    }

    /**
     * Get adresse
     *
     * @return \Jc\JolieCarBundle\Entity\Adresse
     */
    public function getAdresse()
    {
        return $this->adresse;
    }

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

    /**
     * Set typeProprietaire
     *
     * @param \Jc\JolieCarBundle\Entity\TypeProprietaire $typeProprietaire
     * @return Proprietaire
     */
    public function setTypeProprietaire(\Jc\JolieCarBundle\Entity\TypeProprietaire $typeProprietaire = null)
    {
        $this->typeProprietaire = $typeProprietaire;

        return $this;
    }

    /**
     * Get typeProprietaire
     *
     * @return \Jc\JolieCarBundle\Entity\TypeProprietaire
     */
    public function getTypeProprietaire()
    {
        return $this->typeProprietaire;
    }
}


text:
package com.google.gerrit.server.restapi.change;

import com.google.gerrit.entities.HumanComment;
import com.google.gerrit.server.CommentsUtil;
import com.google.gerrit.server.change.RevisionResource;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class ListRevisionComments extends ListRevisionDrafts {
  @Inject
  ListRevisionComments(Provider<CommentJson> commentJson, CommentsUtil commentsUtil) {
    super(commentJson, commentsUtil);
  }

  @Override
  protected boolean includeAuthorInfo() {
    return true;
  }

  @Override
  protected Iterable<HumanComment> listComments(RevisionResource rsrc) {
    ChangeNotes notes = rsrc.getNotes();
    return commentsUtil.publishedByPatchSet(notes, rsrc.getPatchSet().id());
  }
}


text:
#include "config.h"
#include "PropertySetCSSStyleDeclaration.h"

#include "CSSParser.h"
#include "CSSStyleSheet.h"
#include "HTMLNames.h"
#include "InspectorInstrumentation.h"
#include "MutationObserverInterestGroup.h"
#include "MutationRecord.h"
#include "StylePropertySet.h"
#include "StyledElement.h"
#include "UndoManager.h"
#include "WebCoreMemoryInstrumentation.h"
#include <wtf/MemoryInstrumentationHashMap.h>

using namespace std;

namespace WebCore {

namespace {

class StyleAttributeMutationScope {
    WTF_MAKE_NONCOPYABLE(StyleAttributeMutationScope);
public:
    StyleAttributeMutationScope(PropertySetCSSStyleDeclaration* decl)
    {
        ++s_scopeCount;

        if (s_scopeCount != 1) {
            ASSERT(s_currentDecl == decl);
            return;
        }

        ASSERT(!s_currentDecl);
        s_currentDecl = decl;

#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
        if (!s_currentDecl->parentElement())
            return;

        bool shouldReadOldValue = false;

#if ENABLE(MUTATION_OBSERVERS)
        m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(s_currentDecl->parentElement(), HTMLNames::styleAttr);
        if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
            shouldReadOldValue = true;
#endif
#if ENABLE(UNDO_MANAGER)
        m_isRecordingAutomaticTransaction = UndoManager::isRecordingAutomaticTransaction(s_currentDecl->parentElement());
        if (m_isRecordingAutomaticTransaction)
            shouldReadOldValue = true;
#endif

        AtomicString oldValue;
        if (shouldReadOldValue)
            oldValue = s_currentDecl->parentElement()->getAttribute(HTMLNames::styleAttr);

#if ENABLE(MUTATION_OBSERVERS)
        if (m_mutationRecipients) {
            AtomicString requestedOldValue = m_mutationRecipients->isOldValueRequested() ? oldValue : nullAtom;
            m_mutation = MutationRecord::createAttributes(s_currentDecl->parentElement(), HTMLNames::styleAttr, requestedOldValue);
        }
#endif
#if ENABLE(UNDO_MANAGER)
        if (m_isRecordingAutomaticTransaction)
            m_oldValue = oldValue;
#endif

#endif
    }

    ~StyleAttributeMutationScope()
    {
        --s_scopeCount;
        if (s_scopeCount)
            return;

#if ENABLE(MUTATION_OBSERVERS)
        if (m_mutation && s_shouldDeliver)
            m_mutationRecipients->enqueueMutationRecord(m_mutation);
#endif
#if ENABLE(UNDO_MANAGER)
        if (m_isRecordingAutomaticTransaction && s_shouldDeliver) {
            UndoManager::addTransactionStep(AttrChangingDOMTransactionStep::create(
                s_currentDecl->parentElement(), HTMLNames::styleAttr, m_oldValue, s_currentDecl->parentElement()->getAttribute(HTMLNames::styleAttr)));
        }
#endif
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
        s_shouldDeliver = false;
#endif
        if (!s_shouldNotifyInspector) {
            s_currentDecl = 0;
            return;
        }
        // We have to clear internal state before calling Inspector's code.
        PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
        s_currentDecl = 0;
        s_shouldNotifyInspector = false;
        if (localCopyStyleDecl->parentElement() && localCopyStyleDecl->parentElement()->document())
            InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement()->document(), localCopyStyleDecl->parentElement());
    }

#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    void enqueueMutationRecord()
    {
        s_shouldDeliver = true;
    }
#endif

    void didInvalidateStyleAttr()
    {
        s_shouldNotifyInspector = true;
    }

private:
    static unsigned s_scopeCount;
    static PropertySetCSSStyleDeclaration* s_currentDecl;
    static bool s_shouldNotifyInspector;
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    static bool s_shouldDeliver;
#endif

#if ENABLE(MUTATION_OBSERVERS)
    OwnPtr<MutationObserverInterestGroup> m_mutationRecipients;
    RefPtr<MutationRecord> m_mutation;
#endif
#if ENABLE(UNDO_MANAGER)
    bool m_isRecordingAutomaticTransaction;
    AtomicString m_oldValue;
#endif
};

unsigned StyleAttributeMutationScope::s_scopeCount = 0;
PropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
bool StyleAttributeMutationScope::s_shouldNotifyInspector = false;
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
bool StyleAttributeMutationScope::s_shouldDeliver = false;
#endif

} // namespace

void PropertySetCSSStyleDeclaration::ref()
{
    m_propertySet->ref();
}

void PropertySetCSSStyleDeclaration::deref()
{
    m_propertySet->deref();
}

void PropertySetCSSStyleDeclaration::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    info.addMember(m_propertySet);
    info.addMember(m_cssomCSSValueClones);
}

unsigned PropertySetCSSStyleDeclaration::length() const
{
    return m_propertySet->propertyCount();
}

String PropertySetCSSStyleDeclaration::item(unsigned i) const
{
    if (i >= m_propertySet->propertyCount())
        return "";
    return m_propertySet->propertyAt(i).cssName();
}

String PropertySetCSSStyleDeclaration::cssText() const
{
    return m_propertySet->asText();
}

void PropertySetCSSStyleDeclaration::setCssText(const String& text, ExceptionCode& ec)
{
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    StyleAttributeMutationScope mutationScope(this);
#endif
    willMutate();

    ec = 0;
    // FIXME: Detect syntax errors and set ec.
    m_propertySet->parseDeclaration(text, contextStyleSheet());

    didMutate(PropertyChanged);

#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    mutationScope.enqueueMutationRecord();
#endif
}

PassRefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
{
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return 0;
    return cloneAndCacheForCSSOM(m_propertySet->getPropertyCSSValue(propertyID).get());
}

String PropertySetCSSStyleDeclaration::getPropertyValue(const String &propertyName)
{
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return String();
    return m_propertySet->getPropertyValue(propertyID);
}

String PropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
{
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return String();
    return m_propertySet->propertyIsImportant(propertyID) ? "important" : "";
}

String PropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
{
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return String();
    CSSPropertyID shorthandID = m_propertySet->getPropertyShorthand(propertyID);
    if (!shorthandID)
        return String();
    return getPropertyNameString(shorthandID);
}

bool PropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
{
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return false;
    return m_propertySet->isPropertyImplicit(propertyID);
}

void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionCode& ec)
{
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    StyleAttributeMutationScope mutationScope(this);
#endif
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return;

    bool important = priority.find("important", 0, false) != notFound;

    willMutate();

    ec = 0;
    bool changed = m_propertySet->setProperty(propertyID, value, important, contextStyleSheet());

    didMutate(changed ? PropertyChanged : NoChanges);

    if (changed) {
        // CSS DOM requires raising SYNTAX_ERR of parsing failed, but this is too dangerous for compatibility,
        // see <http://bugs.webkit.org/show_bug.cgi?id=7296>.
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
        mutationScope.enqueueMutationRecord();
#endif
    }
}

String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionCode& ec)
{
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    StyleAttributeMutationScope mutationScope(this);
#endif
    CSSPropertyID propertyID = cssPropertyID(propertyName);
    if (!propertyID)
        return String();

    willMutate();

    ec = 0;
    String result;
    bool changed = m_propertySet->removeProperty(propertyID, &result);

    didMutate(changed ? PropertyChanged : NoChanges);

    if (changed) {
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
        mutationScope.enqueueMutationRecord();
#endif
    }
    return result;
}

PassRefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
{
    return m_propertySet->getPropertyCSSValue(propertyID);
}

String PropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
{
    return m_propertySet->getPropertyValue(propertyID);
}

void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionCode& ec)
{
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
    StyleAttributeMutationScope mutationScope(this);
#endif
    willMutate();

    ec = 0;
    bool changed = m_propertySet->setProperty(propertyID, value, important, contextStyleSheet());

    didMutate(changed ? PropertyChanged : NoChanges);

    if (changed) {
#if ENABLE(MUTATION_OBSERVERS) || ENABLE(UNDO_MANAGER)
        mutationScope.enqueueMutationRecord();
#endif
    }
}

CSSValue* PropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
{
    if (!internalValue)
        return 0;

    // The map is here to maintain the object identity of the CSSValues over multiple invocations.
    // FIXME: It is likely that the identity is not important for web compatibility and this code should be removed.
    if (!m_cssomCSSValueClones)
        m_cssomCSSValueClones = adoptPtr(new HashMap<CSSValue*, RefPtr<CSSValue> >);

    RefPtr<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtr<CSSValue>()).iterator->value;
    if (!clonedValue)
        clonedValue = internalValue->cloneForCSSOM();
    return clonedValue.get();
}

StyleSheetContents* PropertySetCSSStyleDeclaration::contextStyleSheet() const
{
    CSSStyleSheet* cssStyleSheet = parentStyleSheet();
    return cssStyleSheet ? cssStyleSheet->contents() : 0;
}

PassRefPtr<StylePropertySet> PropertySetCSSStyleDeclaration::copy() const
{
    return m_propertySet->copy();
}

PassRefPtr<StylePropertySet> PropertySetCSSStyleDeclaration::makeMutable()
{
    ASSERT(m_propertySet->isMutable());
    return m_propertySet;
}

bool PropertySetCSSStyleDeclaration::cssPropertyMatches(const CSSProperty* property) const
{
    return m_propertySet->propertyMatches(property);
}

StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(StylePropertySet* propertySet, CSSRule* parentRule)
    : PropertySetCSSStyleDeclaration(propertySet)
    , m_refCount(1)
    , m_parentRule(parentRule)
{
    m_propertySet->ref();
}

StyleRuleCSSStyleDeclaration::~StyleRuleCSSStyleDeclaration()
{
    m_propertySet->deref();
}

void StyleRuleCSSStyleDeclaration::ref()
{
    ++m_refCount;
}

void StyleRuleCSSStyleDeclaration::deref()
{
    ASSERT(m_refCount);
    if (!--m_refCount)
        delete this;
}

void StyleRuleCSSStyleDeclaration::willMutate()
{
    if (m_parentRule && m_parentRule->parentStyleSheet())
        m_parentRule->parentStyleSheet()->willMutateRules();
}

void StyleRuleCSSStyleDeclaration::didMutate(MutationType type)
{
    if (type == PropertyChanged)
        m_cssomCSSValueClones.clear();

    // Style sheet mutation needs to be signaled even if the change failed. willMutateRules/didMutateRules must pair.
    if (m_parentRule && m_parentRule->parentStyleSheet())
        m_parentRule->parentStyleSheet()->didMutateRules();
}

CSSStyleSheet* StyleRuleCSSStyleDeclaration::parentStyleSheet() const
{
    return m_parentRule ? m_parentRule->parentStyleSheet() : 0;
}

void StyleRuleCSSStyleDeclaration::reattach(StylePropertySet* propertySet)
{
    ASSERT(propertySet);
    m_propertySet->deref();
    m_propertySet = propertySet;
    m_propertySet->ref();
}

void StyleRuleCSSStyleDeclaration::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    PropertySetCSSStyleDeclaration::reportMemoryUsage(memoryObjectInfo);
    info.addMember(m_parentRule);
}

void InlineCSSStyleDeclaration::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
    PropertySetCSSStyleDeclaration::reportMemoryUsage(memoryObjectInfo);
    info.addMember(m_parentElement);
}

void InlineCSSStyleDeclaration::didMutate(MutationType type)
{
    if (type == NoChanges)
        return;

    m_cssomCSSValueClones.clear();

    if (!m_parentElement)
        return;

    m_parentElement->setNeedsStyleRecalc(InlineStyleChange);
    m_parentElement->invalidateStyleAttribute();
    StyleAttributeMutationScope(this).didInvalidateStyleAttr();
}

CSSStyleSheet* InlineCSSStyleDeclaration::parentStyleSheet() const
{
    return m_parentElement ? m_parentElement->document()->elementSheet() : 0;
}

} // namespace WebCore


text:
(function($) {
	// Create namespace object and add to window (global).
	if(typeof window.cms === 'undefined') {window.cms = {};}

	/** Set document orientation. */
	function setDocumentOrientation(intValue) {
		// Validate orientation.
		switch(intValue) {
			default: case 0: // Portrait.
				if(!$(document.body).hasClass('orientation_portrait')) {
					$(document.body).removeClass('orientation_landscape').addClass('orientation_portrait');
				}
				break;
			case 90: case -90: // Landscape.
				if(!$(document.body).hasClass('orientation_landscape')) {
					$(document.body).removeClass('orientation_portrait').addClass('orientation_landscape');
				}
				break;
		}
	}

	// Validate default orientation from document and add to global object.
	if(typeof window.orientation !== 'undefined') {
		window.cms.intOrientation = window.orientation;
	} else if($(document.body).hasClass('orientation_portrait')) {
		window.cms.intOrientation = 0;
	} else if($(document.body).hasClass('orientation_landscape')) {
		window.cms.intOrientation = 90;
	}

	// Validate global object from window.
	if(typeof window.cms.intOrientation !== 'undefined') {
		// Init.
		var objSupportsOrientationChange = 'onorientationchange' in window, objOrientationEvent = objSupportsOrientationChange ? 'orientationchange' : 'resize';
		// Add orientation event to global object.
		window.cms.objOrientationEvent = objOrientationEvent;
		// Set document orientation.
		setDocumentOrientation(window.cms.intOrientation);
		// Bind event.
		$(window).bind(objOrientationEvent, function(evt) {
			setDocumentOrientation(window.orientation);
		});
	}
})(jQuery);

;(function($){
	// https://github.com/allmarkedup/jQuery-URL-Toolbox
	// jquery.url_toolbox.js

	// JQuery URL Toolbox
	// Written by Mark Perkins, mark@allmarkedup.com
	// License: http://unlicense.org/ (i.e. do what you want with it!)

	// a few helper functions

	var isStr = function( item ) { return typeof item === 'string'; };
	var isObj = function( item ) { return typeof item === 'object'; };
	var isfunc = function( item ) { return typeof item === 'function'; };

	var isGetter = function( args ) { return ( args.length == 1 && ! isObj(args[0]) ); }
	var isSetter = function( args ) { return ( args.length >= 2 || (args.length == 1 && isObj(args[0])) ); }

	var stripQ = function( str ) { return str.replace(/\?.*$/, ''); }
	var stripH = function( str ) { return str.replace(/^#/, ''); }

	// set up a few constants & shortcuts
	var loc = document.location,
	tag2attr = { a : 'href', img : 'src', form : 'action', base : 'href', script	: 'src', iframe	: 'src', link : 'href' };

	// split up a query sting
	function splitQuery( string )
	{
		var ret = {},
		seg = string.replace(/^\?/,'').split('&'),
		len = seg.length, i = 0, s;
		for (;i<len;i++)
		{
			if (!seg[i]) { continue; }
			s = seg[i].split('=');
			ret[s[0]] = s[1];
		}
		return ret;
	}

	// reconstructs a query string from an object of key:value pairs
	var combineQuery = function( params, prefixQM )
	{
		var queryString = ( prefixQM === true ) ? '?' : '';
		for ( i in params ) queryString += i+'='+params[i]+'&';
		return queryString.slice(0, -1);
	};

	// reconstructs a path string from an array of parts
	var combinePath = function( segments )
	{
		return segments.join('/');
	};

	function splitHashSegments( hash )
	{
		if ( hash.indexOf('=') === -1 )
		{
			if ( hash.charAt(hash.length-1) == '/' ) hash = hash.slice(0, -1);
			return hash.replace(/^\//,'').split('/');
		}
		return null;
	}

	function splitHashParams( hash )
	{
		if ( hash.indexOf('=') !== -1 ) return splitQuery( hash );
		return null;
	}

	// utility function to get tag name of $ objects
	var getTagName = function( elm )
	{
		var tg = $(elm).get(0).tagName;
		if ( tg !== undefined ) return tg.toLowerCase();
		return tg;
	}

	var throwParserError = function( msg )
	{
		if ( msg === undefined ) msg = 'url parser error';
		// console.log( msg );
	};

	var getHost = function( hostname, port )
	{
		// deals with non-standard port name issues, mostly in safari
		var portRegex = new RegExp( ':'+port ); // need to strip the non-standard ports out of safari
		return hostname.replace( portRegex, '' );
	}

	////////////////////////////////////////////////////////////////////////////////////////////////

	// create :internal and :external URL filters

	$.extend($.expr[':'],{
	    external : function( elm, i, m )
		{
			var tagName = elm.tagName;

			if ( tagName !== undefined )
			{
				var tg = tagName.toLowerCase();
				var attr = tag2attr[tg];
				if ( elm[attr] )
				{
					if ( tg !== 'a' )
					{
						var a = document.createElement('a');
    					a.href = elm[attr];
					}
					else var a = elm;
					return a.hostname && getHost( a.hostname, a.port ) !== getHost( loc.hostname, loc.port );
				}
			}
			return false;
	    },
		internal : function( elm, i, m )
		{
			var tagName = elm.tagName;
			if ( tagName !== undefined )
			{
				var tg = tagName.toLowerCase();
				var attr = tag2attr[tg];
				if ( elm[attr] )
				{
					if ( tg !== 'a' )
					{
						var a = document.createElement('a');
    					a.href = elm[attr];
					}
					else var a = elm;
					return a.hostname && getHost( a.hostname, a.port ) === getHost( loc.hostname, loc.port );
				}
			}
			return false;
	    }
	});

	/////// two essentially analagous functions to return an activeUrl object (just in different ways) ////////

	// this one is for when you just want to use a manually passed in URL string
	$.url = function( urlString )
	{
		return new activeUrl( urlString );
	};

	// this one is when using DOM objects as the source for the URL
	$.fn.url = function()
	{
		if ( this.size() > 1 )
		{
			// more than one object, return a collection of activeUrls
			var activeUrls = {};

			this.each(function( i ){
				activeUrls[i] = new activeUrl( $(this) );
			});

			return activeUrls;
		}
		else
		{
			// just one item, return just the one active url
			return new activeUrl( this );
		}
	};

	/////// guts of the parser /////////////////////////////////////////////////////////////

	function parseUrl( url )
	{
    	var a =  document.createElement('a');
    	a.href = url;
		if (a.protocol == ":") a.protocol = 'http:';
    	return {
	        source: url,
	        protocol: a.protocol.replace(':',''),
	        host: getHost( a.hostname, a.port ),
			base : (function(){
				if ( a.port != 0 && a.port !== null && a.port !== "" ) return a.protocol+"//"+getHost( a.hostname, a.port )+":"+a.port;
				return a.protocol+"//"+a.host;
			})(),
	        port: a.port,
	        query: a.search,
	        params: splitQuery(a.search),
	        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
	        hash: stripH(a.hash),
	        path: (function(){
				var pn = a.pathname.replace(/^([^\/])/,'/$1');
				if (pn == '/') pn = '';
				return pn;
			})(),
	        segments: a.pathname.replace(/^\//,'').split('/'),
			hashSegments: splitHashSegments( stripH(a.hash) ),
			hashParams: splitHashParams( stripH(a.hash) )
	    };
	};

	// this is the 'active' URL object that gets returned

	var activeUrl = function( source )
	{
		var sourceType = null, // elm | doc | str
			ref = null, // if it is attached to a $ object, keep the reference here
			parsed = {}; // the parsed url

		// reconstructs the hash
		var makeHash = function( prefixHash )
		{
			var hash = '';

			if ( parsed.hashParams != null )
			{
				// treated as query string
				hash = makeQueryString( parsed.hashParams );
			}
			else if ( parsed.hashSegments != null )
			{
				//treat as segments
				hash = makePathString( parsed.hashSegments );
			}

			if ( hash !== '' )
			{
				if ( parsed.hash.charAt(0) == '/' ) hash = '/'+hash;
				if ( prefixHash === true ) return '#'+hash;
		 		return hash;
			}

			return '';
		};

		/////////////////////////////////

		var updateElement = function()
		{
			if ( sourceType == 'elm' )
			{
				ref.attr( tag2attr[getTagName(ref)], parsed.source );
			}
			else if ( sourceType == 'doc' )
			{
				loc.href = parsed.source;
			}
		};

		var updateSource = function()
		{
			parsed.source = parsed.base+parsed.path+parsed.query;
			if ( parsed.hash && parsed.hash != '') parsed.source += '#'+parsed.hash;
		}

		var updateParsedAttrs = function( key, val )
		{
			switch( key )
			{
				case 'source':
					parsed = parseUrl( val ); // need to reparse the entire URL
				break;

				case 'base':
					// need to update: host, protocol, port
					if ( val.charAt(val.length-1) == '/' ) val = val.slice(0, -1); // remove the trailing slash if present
					var a = document.createElement('a');
    				a.href = parsed.base = val;
			 		parsed.protocol = a.protocol.replace(':','');
			        parsed.host = getHost( a.hostname, a.port );
			        parsed.port = a.port;
				break;

				case 'protocol':
				case 'host':
				case 'port':
					// need to update: base
					parsed[key] = val;
					if ( a.port != 0 && a.port !== null && a.port !== "" ) parsed.base = a.protocol+"//"+getHost( a.hostname, a.port )+":"+a.port;
					else parsed.base = a.protocol+"//"+a.host;
				break;

				case 'query':
					// need to update: params
					parsed.query = '?'+val.replace(/\?/,'');
					parsed.params = splitQuery( val );
				break;

				case 'file':
					// need to update: path, segments
					parsed.path = parsed.path.replace( new RegExp( parsed.file+'$' ), val );
					parsed.file = val;
				break;

				case 'hash':
					// need to update: hashParams, hashSegments
					parsed.hash = val;
					parsed.hashSegments = splitHashSegments( val );
					parsed.hashParams = splitHashParams( val );
				break;

				case 'path':
					// need to update: file, segments
					if ( val.charAt(0) != '/' ) val = '/'+val;
					parsed.path = val;
					parsed.file = (val.match(/\/([^\/?#]+)$/i) || [,''])[1];
				 	parsed.segments = val.replace(/^\//,'').split('/');
				break;

				default:
					throwParserError('you can\'t update this property directly');
				break;
			}

			updateSource(); // update the source
		};

		var updateParsedParams = function( key, val )
		{
			 // set the value, then update the query string
			parsed.params[key] = val;
			parsed.query = combineQuery( parsed.params, true );
			updateSource();
		};

		var updateParsedSegments = function( key, val )
		{
			 // set the value, then update the segments
			parsed.segments[key] = val;
			parsed.path = '/'+combinePath( parsed.segments );
			parsed.file = (parsed.path.match(/\/([^\/?#]+)$/i) || [,''])[1];
			updateSource();
		};

		var updateHashParams = function( key, val )
		{
			parsed.hashParams[key] = val;
			parsed.hash = combineQuery( parsed.hashParams, true );
			updateSource();
		};

		var updateHashSegments = function( key, val )
		{
			var slash = ( parsed.hash.charAt(0) == '/' ) ? '/' : '';
			parsed.hashSegments[key] = val;
			parsed.hash = slash+combinePath( parsed.hashSegments );
			updateSource();
		};

		var action = function( gettObj, sett, args )
		{
			if ( isGetter( args ) )
			{
				var key = args[0];
				return ( gettObj === undefined || gettObj[key] === undefined || gettObj[key] === "" ) ? null : gettObj[key];
			}
			else if ( isSetter( args ) )
			{
				if ( isObj( args[0] ) )
				{
					for (var key in args[0]) sett( key, args[0][key] ); // set multiple properties
					if ( args[1] !== false ) updateElement(); // now update the value of the attached element
				}
				else
				{
					sett( args[0], args[1] ); // set a single property
					if ( args[2] !== false ) updateElement(); // now update the value of the attached element
				}

				return this; // return reference to this object
			}
		};

		var init = function()
		{
			if ( isObj( source ) && source.size() )
			{
				urlAttr = undefined;

				var tagName = getTagName(source);
				if ( tagName !== undefined ) urlAttr = tag2attr[tagName];

				if ( tagName !== undefined && urlAttr !== undefined )
				{
					// using a valid $ element as the source of the URL
					sourceType = 'elm';
					ref = source;
					var url = source.attr( urlAttr );
				}
				else if ( tagName !== undefined && urlAttr === undefined )
				{
					// passed a $ element, but not one that can contain a URL. throw an error.
					throwParserError('no valid URL on object');
					return;
				}
				else
				{
					// use the document location as the source
					sourceType = 'doc';
					var url = loc.href;

					$(window).bind('hashchange',function( hash ){
						// listen out for hashChanges, if one is triggered then update the hash
						updateParsedAttrs( 'hash', stripH( loc.hash ) );
					});
				}
			}
			else if ( ! isObj( source ) )
			{
				// just a URL string
				sourceType = 'str';
				var url = source;
			}
			else
			{
				// passed an empty $ item.... don't return anything
				throwParserError( 'no valid item' );
				return;
			}

			parsed = parseUrl( url ); // parse the URL.

		}();

		return {

			// set/get attributes of the URL
			attr : function(){ return action( parsed, updateParsedAttrs, arguments ) },

			// get/set query string parameters
			param : function(){ return action( parsed.params, updateParsedParams, arguments ) },

			// get/set segments in the URL
			segment : function(){ return action( parsed.segments, updateParsedSegments, arguments ) },

			// get/set 'query string' parameters in the FRAGMENT
			hashParam : function() { return action( parsed.hashParams, updateHashParams, arguments ) },

			// get/set segments in the FRAGMENT
			hashSegment : function() { return action( parsed.hashSegments, updateHashSegments, arguments ) },

			// apply some tests
			is : function( test )
			{
				if ( test === 'internal' || test === ':internal' )
				{
					return parsed.host && parsed.host === getHost(loc.hostname);
				}
				else if ( test === 'external' || test === ':external' )
				{
					return parsed.host && parsed.host !== getHost(loc.hostname);
				}
			},

			// return the current URL  as a string
			toString : function(){ return parsed.source; }
		};

	};
})(jQuery);

(function($) {
	// Validate full-screen mode.
	if(navigator.standalone) {
		// Navigate like native application.
		$('a:internal').live('click', function(evt) {
			evt.preventDefault();
			window.location = $(this).attr('href');
		});
	} else { // Not in full-screen.
		// Init default behavior for external links.
		$('a:external').not('.share a').addClass('external').bind('click', function(evt){
			return !window.open(this.href);
		});
		// Hide URL bar on mobile only.
		/mobile/i.test(navigator.userAgent) && !location.hash && setTimeout(function() {
			if(!pageYOffset) {window.scrollTo(0, 1);}
		}, 1000);
	}
})(jQuery);


text:
import 'vs/css!./media/debugViewlet';
import * as nls from 'vs/nls';
import { IAction } from 'vs/base/common/actions';
import * as DOM from 'vs/base/browser/dom';
import { IActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { ViewContainerViewlet } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { IDebugService, VIEWLET_ID, State, BREAKPOINTS_VIEW_ID, IDebugConfiguration, REPL_ID } from 'vs/workbench/contrib/debug/common/debug';
import { StartAction, ConfigureAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/contrib/debug/browser/debugActions';
import { StartDebugActionViewItem, FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { memoize } from 'vs/base/common/decorators';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ViewletPanel } from 'vs/workbench/browser/parts/views/panelViewlet';
import { IMenu, MenuId, IMenuService, MenuItemAction } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { TogglePanelAction } from 'vs/workbench/browser/panel';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';

export class DebugViewlet extends ViewContainerViewlet {

	private startDebugActionViewItem: StartDebugActionViewItem;
	private progressResolve: (() => void) | undefined;
	private breakpointView: ViewletPanel;
	private panelListeners = new Map<string, IDisposable>();
	private debugToolBarMenu: IMenu;
	private disposeOnTitleUpdate: IDisposable;

	constructor(
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@ITelemetryService telemetryService: ITelemetryService,
		@IProgressService private readonly progressService: IProgressService,
		@IDebugService private readonly debugService: IDebugService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IStorageService storageService: IStorageService,
		@IThemeService themeService: IThemeService,
		@IContextMenuService contextMenuService: IContextMenuService,
		@IExtensionService extensionService: IExtensionService,
		@IConfigurationService configurationService: IConfigurationService,
		@IKeybindingService private readonly keybindingService: IKeybindingService,
		@IContextViewService private readonly contextViewService: IContextViewService,
		@IMenuService private readonly menuService: IMenuService,
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@INotificationService private readonly notificationService: INotificationService
	) {
		super(VIEWLET_ID, `${VIEWLET_ID}.state`, false, configurationService, layoutService, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService);

		this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state)));
		this._register(this.debugService.onDidNewSession(() => this.updateToolBar()));
		this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea()));
		this._register(this.configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('debug.toolBarLocation')) {
				this.updateTitleArea();
			}
		}));
	}

	create(parent: HTMLElement): void {
		super.create(parent);
		DOM.addClass(parent, 'debug-viewlet');
	}

	focus(): void {
		super.focus();

		if (this.startDebugActionViewItem) {
			this.startDebugActionViewItem.focus();
		}
	}

	@memoize
	private get startAction(): StartAction {
		return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL));
	}

	@memoize
	private get configureAction(): ConfigureAction {
		return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL));
	}

	@memoize
	private get toggleReplAction(): ToggleReplAction {
		return this._register(this.instantiationService.createInstance(ToggleReplAction, ToggleReplAction.ID, ToggleReplAction.LABEL));
	}

	@memoize
	private get selectAndStartAction(): SelectAndStartAction {
		return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session")));
	}

	getActions(): IAction[] {
		if (this.showInitialDebugActions) {
			return [this.startAction, this.configureAction, this.toggleReplAction];
		}

		if (!this.debugToolBarMenu) {
			this.debugToolBarMenu = this.menuService.createMenu(MenuId.DebugToolBar, this.contextKeyService);
			this._register(this.debugToolBarMenu);
		}

		const { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService);
		if (this.disposeOnTitleUpdate) {
			dispose(this.disposeOnTitleUpdate);
		}
		this.disposeOnTitleUpdate = disposable;

		return actions;
	}

	get showInitialDebugActions(): boolean {
		const state = this.debugService.state;
		return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';
	}

	getSecondaryActions(): IAction[] {
		if (this.showInitialDebugActions) {
			return [];
		}

		return [this.selectAndStartAction, this.configureAction, this.toggleReplAction];
	}

	getActionViewItem(action: IAction): IActionViewItem | undefined {
		if (action.id === StartAction.ID) {
			this.startDebugActionViewItem = this.instantiationService.createInstance(StartDebugActionViewItem, null, action);
			return this.startDebugActionViewItem;
		}
		if (action.id === FocusSessionAction.ID) {
			return new FocusSessionActionViewItem(action, this.debugService, this.themeService, this.contextViewService, this.configurationService);
		}
		if (action instanceof MenuItemAction) {
			return new MenuEntryActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
		}

		return undefined;
	}

	focusView(id: string): void {
		const view = this.getView(id);
		if (view) {
			view.focus();
		}
	}

	private onDebugServiceStateChange(state: State): void {
		if (this.progressResolve) {
			this.progressResolve();
			this.progressResolve = undefined;
		}

		if (state === State.Initializing) {
			this.progressService.withProgress({ location: VIEWLET_ID }, _progress => {
				return new Promise(resolve => this.progressResolve = resolve);
			});
		}

		this.updateToolBar();
	}

	private updateToolBar(): void {
		if (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') {
			this.updateTitleArea();
		}
	}

	addPanels(panels: { panel: ViewletPanel, size: number, index?: number }[]): void {
		super.addPanels(panels);

		for (const { panel } of panels) {
			// attach event listener to
			if (panel.id === BREAKPOINTS_VIEW_ID) {
				this.breakpointView = panel;
				this.updateBreakpointsMaxSize();
			} else {
				this.panelListeners.set(panel.id, panel.onDidChange(() => this.updateBreakpointsMaxSize()));
			}
		}
	}

	removePanels(panels: ViewletPanel[]): void {
		super.removePanels(panels);
		for (const panel of panels) {
			dispose(this.panelListeners.get(panel.id));
			this.panelListeners.delete(panel.id);
		}
	}

	private updateBreakpointsMaxSize(): void {
		if (this.breakpointView) {
			// We need to update the breakpoints view since all other views are collapsed #25384
			const allOtherCollapsed = this.panels.every(view => !view.isExpanded() || view === this.breakpointView);
			this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize;
		}
	}
}

class ToggleReplAction extends TogglePanelAction {
	static readonly ID = 'debug.toggleRepl';
	static LABEL = nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'debugConsoleAction' }, 'Debug Console');

	constructor(id: string, label: string,
		@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
		@IPanelService panelService: IPanelService
	) {
		super(id, label, REPL_ID, panelService, layoutService, 'debug-action toggle-repl');
	}
}


text:
from GUI.PopUps.FileSavingDialogPopUp import FileSavingDialogPopUp
from Utils.FileHandler import copy_file_as
from os import path

class FileCopyDialogPopUp(FileSavingDialogPopUp):
    """
    A class to handle copying a imported file to the media folder, if the file already
    exists in the media folder
    """
    FOLDER_NAME = "media folder"
    DISMISS_BTN_TEXT = "Import existing"

    def __init__(self, source, destination, filename_list, listener, project_path):
        """
        Constructs a popup that can be used to save a copy of the selected file
        or to replace the destination file
        :param source: the source file
        :param destination: the destination file
        :param filename_list: a list to append the imported file name to after saving
        :param listener: the listener to notify when file is imported
        :param project_path: the path to save the file to
        """
        super(FileCopyDialogPopUp, self).__init__(source=source,
                                                  destination=destination,
                                                  filename_list=filename_list,
                                                  listener=listener,
                                                  path=project_path,
                                                  folder_name=self.FOLDER_NAME,
                                                  dismiss_button_text=self.DISMISS_BTN_TEXT)

    def replace_file(self):
        """
        Replaces the destination file with the source file
        :return: None
        """
        self.copy_source_file_as(self.destination)

    def create_new_file(self):
        """
        Creates a new file from the source file
        :return:
        """
        filename = path.join(self.path, self.ids.save_as.text)
        self.copy_source_file_as(filename)

    def copy_source_file_as(self, filename):
        """
        Copies the source file as selected file
        :param filename: the filename to copy the source as
        :return: None
        """
        try:
            copy_file_as(self.source, filename)
            self.filename_list.append(filename)
            self.listener.notify_file_import()
        except Exception as ex:
            self.error(ex)


text:
package org.moonlightcontroller.managers.models;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.moonlightcontroller.blocks.ObiType;
import org.moonlightcontroller.main.ControllerProperties;
import org.moonlightcontroller.managers.models.messages.IMessage;
import org.moonlightcontroller.southbound.client.SingleInstanceConnection;
import org.moonlightcontroller.southbound.server.SouthboundServer;
import org.openbox.dashboard.SouthboundProfiler;

/**
 * Connection Instance is class responsible of connection with OBIs
 * It implements the IConnectionInstance interface which enables sending messages to OBIs
 */
public class ConnectionInstance implements IConnectionInstance {

    private long dpid;
	private LocalDateTime lastKeepAlive;
	private String version;
	private int keepaliveInterval;
	private Map<String, List<String>> capabilities;
	private boolean isProcessingGraphReceived;
	private SingleInstanceConnection client;
    private final ObiType obiType;
	private String ip;

	public ConnectionInstance(long dpid,
                              String version,
                              int keepaliveInterval,
                              Map<String, List<String>> capabilities,
                              String ip, ObiType obiType) {
		this.setDpid(dpid);
		this.version = version;
		this.keepaliveInterval = keepaliveInterval;
		this.capabilities = capabilities;
		this.obiType = obiType;
		this.setProcessingGraphReceived(false);
		String[] ipPort = ip.split(":");
		this.ip = ip;

		int port = 3636;

		if (ipPort.length == 2)
			port = Integer.valueOf(ipPort[1]);

		this.client = new SingleInstanceConnection(ipPort[0], port, SouthboundServer.SERVER_HOST,  SouthboundServer.SERVER_PORT);
	}

	/**
	 * Updates the last keepalive update to Now
	 */
	public void updateKeepAlive() {
		this.lastKeepAlive = LocalDateTime.now();
	}

	/**
	 * @return the last keep alive time
	 */
	public LocalDateTime getKeepAliveDate() {
		return this.lastKeepAlive;
	}

	/**
	 * @return the keep alive interval
	 */
	public int getKeepAliveInterval() {
		return this.keepaliveInterval;
	}

	/**
	 * @return the OBI dpid for this connection
	 */
	public long getDpid() {
		return dpid;
	}

	/**
	 * Sets the dpid for this connection
	 * @param dpid
	 */
	public void setDpid(long dpid) {
		this.dpid = dpid;
	}

	/**
	 * @return the version of the connection
	 */
	public String getVersion() {
		return version;
	}

	/**
	 * @return the capabilities of the OBI for this connection
	 */
	public Map<String, List<String>> getCapabilities() {
		return capabilities;
	}

    public ObiType getObiType() {
        return obiType;
    }

	/**
	 * @return whether a processing graph was configured for this OBI
	 */
	public boolean isProcessingGraphReceived() {
		return isProcessingGraphReceived;
	}

	/**
	 * Sets the processing graph configured flag
	 * @param isProcessingGraphConfiged
	 */
	public void setProcessingGraphReceived(boolean isProcessingGraphConfiged) {
		this.isProcessingGraphReceived = isProcessingGraphConfiged;
	}

	public static class Builder {
		private final int DEFAULT_KEEPALIVE_DURATION = ControllerProperties.getInstance().getKeepAliveInterval();

		long dpid;
		int keepaliveInterval = DEFAULT_KEEPALIVE_DURATION;
		LocalDateTime lastKeepAlive;
		String version = "";
		String ip;
		Map<String, List<String>> capabilities = new HashMap<>();
        private ObiType obiType;

        public Builder() {

		}

		public Builder setIp(String ip) {
			this.ip = ip;
			return this;
		}

		public Builder setDpid(long dpid) {
			this.dpid = dpid;
			return this;
		}

		public Builder setKeepAliveInterval(int keepaliveInterval) {
			this.keepaliveInterval = keepaliveInterval;
			return this;
		}

		public Builder setVersion(String version) {
			this.version = version;
			return this;
		}

		public Builder setCapabilities(Map<String, List<String>> capabilities) {
			this.capabilities = capabilities;
			return this;
		}

		public ConnectionInstance build () {
			return new ConnectionInstance(dpid,
					version,
					keepaliveInterval,
					capabilities,
					ip,
                    obiType);
		}

        public Builder setObiType(ObiType obiType) {
            this.obiType = obiType;
            return this;
        }

    }

	@Override
	public void sendRequest(IMessage message, IRequestSender requestSender) {
		client.sendMessage(message);
		SouthboundProfiler.getInstance().onMessage(message, false);

	}
}