text:
// Need to override adaptor classes for toolkit test harness, so include
// test harness headers before dali headers.
#include <dali-toolkit-test-suite-utils.h>

#include <dali.h>
#include <dali-toolkit/dali-toolkit.h>

#include <dali/devel-api/adaptor-framework/accessibility.h>
#include <dali/devel-api/atspi-interfaces/accessible.h>
#include <dali/devel-api/atspi-interfaces/text.h>
#include <dali-toolkit/internal/controls/text-controls/text-field-impl.h>
#include <dali-toolkit/internal/controls/text-controls/text-editor-impl.h>

#include <automated-tests/src/dali-toolkit-internal/dali-toolkit-test-utils/dbus-wrapper.h>

void utc_dali_toolkit_accessibility_text_startup(void)
{
  test_return_value = TET_UNDEF;
  DBusWrapper::Install(std::unique_ptr<DBusWrapper>(new TestDBusWrapper));
}

void utc_dali_toolkit_accessibility_text_cleanup(void)
{
  test_return_value = TET_PASS;
}

int utcDaliAccessibilityTextEditorGetName(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  DALI_TEST_EQUALS( editor.GetProperty<std::string>(Actor::Property::NAME), "", TEST_LOCATION );
  editor.SetProperty(Actor::Property::NAME, "editor");
  DALI_TEST_EQUALS( editor.GetProperty<std::string>(Actor::Property::NAME), "editor", TEST_LOCATION );

  END_TEST;
}

int utcDaliAccessibilityTextEditorGetText(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q = Dali::Accessibility::Accessible::Get( editor );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetText( 0, 0 ), "", TEST_LOCATION );
    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "exemplary_text" );
    DALI_TEST_EQUALS( x->GetText( 0, 9 ), "exemplary", TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextEditorGetCharacterCount(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q = Dali::Accessibility::Accessible::Get( editor );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetCharacterCount(), 0, TEST_LOCATION );
    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "editor" );
    DALI_TEST_EQUALS( x->GetCharacterCount(), 6, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextEditorGetTextAtOffset(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q = Dali::Accessibility::Accessible::Get( editor );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text editor test sentence" );
    range = x->GetTextAtOffset( 5, Dali::Accessibility::TextBoundary::CHARACTER );
    DALI_TEST_EQUALS( range.content, "e", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 5, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 6, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 3, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 28, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 36, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 4, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "text    \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 6, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " editor  \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 14, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 24, TEST_LOCATION );

    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 8, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " test sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 25, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 39, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextEditorGetSetRangeOfSelection(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q = Dali::Accessibility::Accessible::Get( editor );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );

    x->SetRangeOfSelection( 0, 4, 9 );
    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "exemplary_text" );
    range = x->GetRangeOfSelection( 0 );

    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );
    DALI_TEST_EQUALS( range.content, "plary", TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextEditorRemoveSelection(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q = Dali::Accessibility::Accessible::Get( editor );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    x->SetRangeOfSelection( 0, 4, 9 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    x->RemoveSelection( 0 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextEditorGetRangeExtents(void)
{
  ToolkitTestApplication application;

  auto editor = Dali::Toolkit::TextEditor::New();
  auto q     = Dali::Accessibility::Accessible::Get( editor );
  auto x     = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );

  if( x )
  {
    auto rangeExtents = x->GetRangeExtents( 0, 0, Dali::Accessibility::CoordinateType::WINDOW );
    DALI_TEST_EQUALS( (int)rangeExtents.x, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.y, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.width, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.height, 0, TEST_LOCATION );

    application.GetScene().Add( editor );

    editor.SetProperty( Toolkit::TextEditor::Property::POINT_SIZE, 7.f );
    editor.SetProperty( Actor::Property::SIZE, Vector2(200.f, 200.f) );
    editor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
    editor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
    editor.SetProperty( Toolkit::TextEditor::Property::TEXT, "text editor test sentence" );

    // Avoid a crash when core load gl resources.
    application.GetGlAbstraction().SetCheckFramebufferStatusResult(GL_FRAMEBUFFER_COMPLETE);

    // Render and notify
    application.SendNotification();
    application.Render();

    auto characterCount = x->GetCharacterCount();
    rangeExtents        = x->GetRangeExtents( 0, characterCount, Dali::Accessibility::CoordinateType::WINDOW );

    DALI_TEST_EQUALS((int)rangeExtents.x >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.y >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.width <= 200, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.height <= 200, true, TEST_LOCATION);
  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetName(void)
{
  ToolkitTestApplication application;

  auto field = Toolkit::TextField::New();
  DALI_TEST_EQUALS( field.GetProperty<std::string>(Actor::Property::NAME), "", TEST_LOCATION );
  field.SetProperty(Actor::Property::NAME, "field");
  DALI_TEST_EQUALS( field.GetProperty<std::string>(Actor::Property::NAME), "field", TEST_LOCATION );

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetText(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q = Dali::Accessibility::Accessible::Get( field );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetText( 0, 0 ), "", TEST_LOCATION );
    field.SetProperty( Toolkit::TextField::Property::TEXT, "exemplary_text" );
    DALI_TEST_EQUALS( x->GetText( 0, 9 ), "exemplary", TEST_LOCATION );

    Dali::Property::Map hiddenInputSettings;
    hiddenInputSettings[ Toolkit::HiddenInput::Property::MODE ] = Toolkit::HiddenInput::Mode::HIDE_ALL;

    field.SetProperty( Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS, hiddenInputSettings );

    DALI_TEST_EQUALS( x->GetName(), "", TEST_LOCATION );
    DALI_TEST_EQUALS( x->GetText( 0, 9 ), "*********", TEST_LOCATION );

    hiddenInputSettings[ Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER ] = 0x23;
    field.SetProperty( Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS, hiddenInputSettings );

    DALI_TEST_EQUALS( x->GetName(), "", TEST_LOCATION );
    DALI_TEST_EQUALS( x->GetText( 0, 9 ), "#########", TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetCharacterCount(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q = Dali::Accessibility::Accessible::Get( field );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetCharacterCount(), 0, TEST_LOCATION );
    field.SetProperty( Toolkit::TextField::Property::TEXT, "field" );
    DALI_TEST_EQUALS( x->GetCharacterCount(), 5, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetTextAtOffset(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q = Dali::Accessibility::Accessible::Get( field );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text editor test sentence" );
    range = x->GetTextAtOffset( 5, Dali::Accessibility::TextBoundary::CHARACTER );
    DALI_TEST_EQUALS( range.content, "e", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 5, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 6, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 3, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 28, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 36, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 4, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "text    \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 6, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " editor  \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 14, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 24, TEST_LOCATION );

    field.SetProperty( Toolkit::TextField::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 8, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " test sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 25, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 39, TEST_LOCATION );

    Dali::Property::Map hiddenInputSettings;
    hiddenInputSettings[ Toolkit::HiddenInput::Property::MODE ] = Toolkit::HiddenInput::Mode::HIDE_ALL;
    hiddenInputSettings[ Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER ] = 0x23;
    field.SetProperty( Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS, hiddenInputSettings );
    range = x->GetTextAtOffset( 8, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetSetRangeOfSelection(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q = Dali::Accessibility::Accessible::Get( field );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );

    x->SetRangeOfSelection( 0, 4, 9 );
    field.SetProperty( Toolkit::TextEditor::Property::TEXT, "exemplary_text" );
    range = x->GetRangeOfSelection( 0 );

    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );
    DALI_TEST_EQUALS( range.content, "plary", TEST_LOCATION );

    Dali::Property::Map hiddenInputSettings;
    hiddenInputSettings[ Toolkit::HiddenInput::Property::MODE ] = Toolkit::HiddenInput::Mode::HIDE_ALL;
    field.SetProperty( Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS, hiddenInputSettings );

    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );
    DALI_TEST_EQUALS( range.content, "*****", TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldRemoveSelection(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q = Dali::Accessibility::Accessible::Get( field );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    x->SetRangeOfSelection( 0, 4, 9 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    x->RemoveSelection( 0 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextFieldGetRangeExtents(void)
{
  ToolkitTestApplication application;

  auto field = Dali::Toolkit::TextField::New();
  auto q     = Dali::Accessibility::Accessible::Get( field );
  auto x     = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );

  if( x )
  {
    auto rangeExtents = x->GetRangeExtents( 0, 0, Dali::Accessibility::CoordinateType::WINDOW );
    DALI_TEST_EQUALS( (int)rangeExtents.x, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.y, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.width, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.height, 0, TEST_LOCATION );

    application.GetScene().Add( field );

    field.SetProperty( Toolkit::TextField::Property::POINT_SIZE, 7.f );
    field.SetProperty( Actor::Property::SIZE, Vector2(200.f, 200.f) );
    field.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
    field.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
    field.SetProperty( Toolkit::TextField::Property::TEXT, "text field test sentence" );

    // Avoid a crash when core load gl resources.
    application.GetGlAbstraction().SetCheckFramebufferStatusResult(GL_FRAMEBUFFER_COMPLETE);

    // Render and notify
    application.SendNotification();
    application.Render();

    auto characterCount = x->GetCharacterCount();
    rangeExtents        = x->GetRangeExtents( 0, characterCount, Dali::Accessibility::CoordinateType::WINDOW );

    DALI_TEST_EQUALS((int)rangeExtents.x >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.y >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.width <= 200, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.height <= 200, true, TEST_LOCATION);
  }

  END_TEST;
}

int utcDaliAccessibilityTextLabelGetName(void)
{
  ToolkitTestApplication application;

  auto label = Toolkit::TextLabel::New();
  DALI_TEST_EQUALS( label.GetProperty<std::string>(Actor::Property::NAME), "", TEST_LOCATION );
  label.SetProperty(Actor::Property::NAME, "label");
  DALI_TEST_EQUALS( label.GetProperty<std::string>(Actor::Property::NAME), "label", TEST_LOCATION );

  END_TEST;
}

int utcDaliAccessibilityTextLabelGetText(void)
{
  ToolkitTestApplication application;

  auto label = Dali::Toolkit::TextLabel::New();
  auto q = Dali::Accessibility::Accessible::Get( label );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetText( 0, 0 ), "", TEST_LOCATION );
    label.SetProperty( Toolkit::TextField::Property::TEXT, "exemplary_text" );
    DALI_TEST_EQUALS( x->GetText( 0, 9 ), "exemplary", TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextLabelGetCharacterCount(void)
{
  ToolkitTestApplication application;

  auto label = Dali::Toolkit::TextLabel::New();
  auto q = Dali::Accessibility::Accessible::Get( label );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    DALI_TEST_EQUALS( x->GetCharacterCount(), 0, TEST_LOCATION );
    label.SetProperty( Toolkit::TextField::Property::TEXT, "field" );
    DALI_TEST_EQUALS( x->GetCharacterCount(), 5, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextLabelGetTextAtOffset(void)
{
  ToolkitTestApplication application;

  auto label = Dali::Toolkit::TextLabel::New();
  auto q = Dali::Accessibility::Accessible::Get( label );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text editor test sentence" );
    range = x->GetTextAtOffset( 5, Dali::Accessibility::TextBoundary::CHARACTER );
    DALI_TEST_EQUALS( range.content, "e", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 5, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 6, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 3, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 28, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 36, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 4, Dali::Accessibility::TextBoundary::WORD );
    DALI_TEST_EQUALS( range.content, "", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 0, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, "text    \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 6, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " editor  \n", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 14, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 24, TEST_LOCATION );

    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text    \n\n\n\n\n\n editor  \n\n test sentence" );
    range = x->GetTextAtOffset( 8, Dali::Accessibility::TextBoundary::LINE );
    DALI_TEST_EQUALS( range.content, " test sentence", TEST_LOCATION );
    DALI_TEST_EQUALS( range.startOffset, 25, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 39, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextLabelRemoveSelection( void )
{
  ToolkitTestApplication application;

  auto label = Dali::Toolkit::TextLabel::New();
  auto q = Dali::Accessibility::Accessible::Get( label );
  auto x = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );
  if( x )
  {
    auto range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );

    x->SetRangeOfSelection( 0, 4, 9 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 4, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 9, TEST_LOCATION );

    x->RemoveSelection( 0 );
    range = x->GetRangeOfSelection( 0 );
    DALI_TEST_EQUALS( range.startOffset, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( range.endOffset, 0, TEST_LOCATION );
  }

  END_TEST;
}

int utcDaliAccessibilityTextLabelGetRangeExtents(void)
{
  ToolkitTestApplication application;

  auto label = Dali::Toolkit::TextLabel::New();
  auto q     = Dali::Accessibility::Accessible::Get( label );
  auto x     = dynamic_cast< Dali::Accessibility::Text* >( q );
  DALI_TEST_CHECK( x );

  if( x )
  {
    auto rangeExtents = x->GetRangeExtents( 0, 0, Dali::Accessibility::CoordinateType::WINDOW );
    DALI_TEST_EQUALS( (int)rangeExtents.x, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.y, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.width, 0, TEST_LOCATION );
    DALI_TEST_EQUALS( (int)rangeExtents.height, 0, TEST_LOCATION );

    application.GetScene().Add( label );

    label.SetProperty( Toolkit::TextLabel::Property::POINT_SIZE, 7.f );
    label.SetProperty( Toolkit::TextLabel::Property::MULTI_LINE, true );
    label.SetProperty( Actor::Property::SIZE, Vector2(200.f, 200.f) );
    label.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
    label.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
    label.SetProperty( Toolkit::TextLabel::Property::TEXT, "text label\n test sentence" );

    // Avoid a crash when core load gl resources.
    application.GetGlAbstraction().SetCheckFramebufferStatusResult(GL_FRAMEBUFFER_COMPLETE);

    // Render and notify
    application.SendNotification();
    application.Render();

    auto characterCount = x->GetCharacterCount();
    rangeExtents        = x->GetRangeExtents( 0, characterCount, Dali::Accessibility::CoordinateType::WINDOW );

    DALI_TEST_EQUALS((int)rangeExtents.x >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.y >= 0, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.width <= 200, true, TEST_LOCATION);
    DALI_TEST_EQUALS((int)rangeExtents.height <= 200, true, TEST_LOCATION);
  }

  END_TEST;
}


text:
package release

import (
	"github.com/enaml-ops/enaml/pkg"
	"github.com/enaml-ops/enaml/pull"
)

// PivnetRelease wraps a .pivotal release and all of its contained BOSH
// releases and jobs
type PivnetRelease struct {
	BoshRelease map[string]*BoshRelease
}

// LoadPivnetRelease creates an initialized pivnetRelease instance from the
// specified .pivotal file.
func LoadPivnetRelease(releaseRepo pull.Release, path string) (release *PivnetRelease, err error) {
	release = &PivnetRelease{}
	var localPath string
	localPath, err = releaseRepo.Pull(path)
	if err != nil {
		return
	}
	release = &PivnetRelease{
		BoshRelease: make(map[string]*BoshRelease),
	}
	err = release.readPivnetRelease(localPath)
	return
}

// BoshReleaseOrEmpty returns the named BOSH release from this pivnet release
// if it exists, otherwise emptyBoshRelease is returned.
func (r *PivnetRelease) BoshReleaseOrEmpty(name string) *BoshRelease {
	br := r.BoshRelease[name]
	if br == nil {
		br = emptyBoshRelease
	}
	return br
}

// readPivnetRelease reads a pivnet release out of the given reader into a new
// pivnetRelease struct
func (r *PivnetRelease) readPivnetRelease(path string) error {
	walker := pkg.NewZipWalker(path)
	walker.OnMatch("releases/", func(file pkg.FileEntry) error {
		br, berr := readBoshRelease(file.Reader)
		if berr != nil {
			return berr
		}
		r.BoshRelease[br.ReleaseManifest.Name] = br
		return nil
	})
	return walker.Walk()
}

redpajama_set_name: RedPajamaGithub


text:
#define	MPPE_POLICY_ALLOWED	1
#define	MPPE_POLICY_REQUIRED	2

#define	MPPE_TYPE_40BIT		2
#define	MPPE_TYPE_128BIT	4

#define	RPI_DEFAULT		1
#define	RPI_PID			2
#define	RPI_IFNUM		3
#define	RPI_TUNNUM		4

struct radius {
  struct fdescriptor desc;	/* We're a sort of (selectable) fdescriptor */
  struct {
    int fd;			/* We're selecting on this */
    struct rad_handle *rad;	/* Using this to talk to our lib */
    struct pppTimer timer;	/* for this long */
    struct authinfo *auth;	/* Tell this about success/failure */
  } cx;
  unsigned valid : 1;           /* Is this structure valid ? */
  unsigned vj : 1;              /* FRAMED Compression */
  struct in_addr ip;            /* FRAMED IP */
  struct in_addr mask;          /* FRAMED Netmask */
  unsigned long mtu;            /* FRAMED MTU */
  unsigned long sessiontime;    /* Session-Timeout */
  char *filterid;		/* FRAMED Filter Id */
  struct sticky_route *routes;  /* FRAMED Routes */
  char *msrepstr;		/* MS-CHAP2-Response */
  char *repstr;			/* Reply-Message */
  char *errstr;			/* Error-Message */
#ifndef NOINET6
  uint8_t *ipv6prefix;		/* FRAMED IPv6 Prefix */
  struct sticky_route *ipv6routes;  /* FRAMED IPv6 Routes */
#endif
  struct {
    int policy;			/* MPPE_POLICY_* */
    int types;			/* MPPE_TYPE_*BIT bitmask */
    char *recvkey;
    size_t recvkeylen;
    char *sendkey;
    size_t sendkeylen;
  } mppe;
  struct {
    char file[PATH_MAX];	/* Radius config file */
  } cfg;
  struct {
    struct pppTimer timer;	/* for this long */
    int interval;
  } alive;
  short unsigned int port_id_type;
};

struct radacct {
  struct radius *rad_parent;	/* "Parent" struct radius stored in bundle */
  char user_name[AUTHLEN];	/* Session User-Name */
  char session_id[256];		/* Unique session ID */
  char multi_session_id[51];	/* Unique MP session ID */
  int  authentic;		/* How the session has been authenticated */
  u_short proto;		/* Protocol number */
  union {
    struct {
      struct in_addr addr;
      struct in_addr mask;
    } ip;
#ifndef NOINET6
    struct {
      u_char ifid[8];
    } ipv6;
#endif
  } peer;
};

#define descriptor2radius(d) \
  ((d)->type == RADIUS_DESCRIPTOR ? (struct radius *)(d) : NULL)

struct bundle;

extern void radius_Flush(struct radius *);
extern void radius_Init(struct radius *);
extern void radius_Destroy(struct radius *);

extern void radius_Show(struct radius *, struct prompt *);
extern void radius_StartTimer(struct bundle *);
extern void radius_StopTimer(struct radius *);
extern int radius_Authenticate(struct radius *, struct authinfo *,
                               const char *, const char *, int,
                               const char *, int);
extern void radius_Account_Set_Ip(struct radacct *, struct in_addr *,
				  struct in_addr *);
#ifndef NOINET6
extern void radius_Account_Set_Ipv6(struct radacct *, u_char *);
#endif
extern void radius_Account(struct radius *, struct radacct *,
                           struct datalink *, int, struct pppThroughput *);

/* An (int) parameter to radius_Account, from radlib.h */
#if !defined(RAD_START)
#define RAD_START	1
#define RAD_STOP	2
#endif

#define RAD_ALIVE	3

/* Get address from NAS pool */
#define RADIUS_INADDR_POOL	htonl(0xfffffffe)	/* 255.255.255.254 */


text:
//-*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-

#include "random_generator.h"

std::mt19937& mt()
{
    static thread_local std::random_device random_device;
    static thread_local std::mt19937 mt(random_device());
    return mt;
}


text:
<?php

if ( ! class_exists( 'GFForms' ) ) {
	die();
}

class GF_Field_Survey extends GF_Field {

	public $type = 'survey';

	// # FORM EDITOR & FIELD MARKUP -------------------------------------------------------------------------------------

	/**
	 * Return the field title, for use in the form editor.
	 *
	 * @return string
	 */
	public function get_form_editor_field_title() {
		return esc_attr__( 'Survey', 'gravityformssurvey' );
	}

	/**
	 * Assign the Survey button to the Advanced Fields group.
	 *
	 * @return array
	 */
	public function get_form_editor_button() {
		return array(
			'group' => 'advanced_fields',
			'text'  => $this->get_form_editor_field_title(),
		);
	}

	/**
	 * Return the settings which should be available on the field in the form editor.
	 *
	 * @return array
	 */
	function get_form_editor_field_settings() {
		return array(
			'gsurvey-setting-question',
			'gsurvey-setting-field-type',
			'conditional_logic_field_setting',
			'prepopulate_field_setting',
			'error_message_setting',
			'admin_label_setting',
			'visibility_setting',
			'description_setting',
			'css_class_setting',
			'label_placement_setting',
		);
	}
}

GF_Fields::register( new GF_Field_Survey() );


text:
<?php

namespace JJSoft\SigesCore\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class FieldsServiceProvider
 * @package JJSoft\SigesCore\Providers
 */
class FieldsServiceProvider extends ServiceProvider
{
    /**
     * The system Field types
     * @var array
     */
    public $defaultTypes = [
        'text' => \JJSoft\SigesCore\Field\Text\TextFieldType::class,
        'email' => \JJSoft\SigesCore\Field\Email\EmailFieldType::class,
        'textarea' => \JJSoft\SigesCore\Field\TextArea\TextAreaFieldType::class,
        'date' => \JJSoft\SigesCore\Field\Date\DateFieldType::class,
        'select' => \JJSoft\SigesCore\Field\Select\SelectFieldType::class
    ];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('field.types', 'JJSoft\SigesCore\Field\FieldTypes');
        $this->setDefaultTypes();
    }

    /**
     * Set the default Field Types
     */
    public function setDefaultTypes()
    {
        $types = $this->app->make('field.types');
        foreach ($this->defaultTypes as $alias => $fieldType) {
            $types->addFieldType([
                'type' => $alias,
                'class' => $fieldType
            ]);
        }
    }
}


text:
Imports RibbonLib
Imports RibbonLib.Controls
Imports RibbonLib.Interop
Imports RibbonLib.Controls.Events

Namespace _16_RecentItems
	Public Enum RibbonMarkupCommands As UInteger
		cmdApplicationMenu = 1000
		cmdButtonNew = 1001
		cmdButtonOpen = 1002
		cmdButtonSave = 1003
		cmdButtonExit = 1004
		cmdRecentItems = 1005
	End Enum

	Partial Public Class Form1
		Inherits Form
		Private _ribbonRecentItems As RibbonRecentItems

		Private _recentItems As List(Of RecentItemsPropertySet)

		Public Sub New()
			InitializeComponent()

			_ribbonRecentItems = New RibbonRecentItems(_ribbon, CUInt(RibbonMarkupCommands.cmdRecentItems))

			AddHandler _ribbonRecentItems.ExecuteEvent, AddressOf _recentItems_ExecuteEvent
		End Sub

		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
			InitRecentItems()
		End Sub

		Private Sub InitRecentItems()
			' prepare list of recent items
			_recentItems = New List(Of RecentItemsPropertySet)()
			_recentItems.Add(New RecentItemsPropertySet() With {.Label = "Recent item 1", .LabelDescription = "Recent item 1 description", .Pinned = True})
			_recentItems.Add(New RecentItemsPropertySet() With {.Label = "Recent item 2", .LabelDescription = "Recent item 2 description", .Pinned = False})

			_ribbonRecentItems.RecentItems = _recentItems
		End Sub

		Private Sub _recentItems_ExecuteEvent(ByVal sender As Object, ByVal e As ExecuteEventArgs)
			If e.Key.PropertyKey = RibbonProperties.RecentItems Then
				' go over recent items
				Dim objectArray() As Object = CType(e.CurrentValue.PropVariant.Value, Object())
				For i As Integer = 0 To objectArray.Length - 1
					Dim propertySet As IUISimplePropertySet = TryCast(objectArray(i), IUISimplePropertySet)

					If propertySet IsNot Nothing Then
						Dim propLabel As PropVariant
						propertySet.GetValue(RibbonProperties.Label, propLabel)
						Dim label As String = CStr(propLabel.Value)

						Dim propLabelDescription As PropVariant
						propertySet.GetValue(RibbonProperties.LabelDescription, propLabelDescription)
						Dim labelDescription As String = CStr(propLabelDescription.Value)

						Dim propPinned As PropVariant
						propertySet.GetValue(RibbonProperties.Pinned, propPinned)
						Dim pinned As Boolean = CBool(propPinned.Value)

						' update pinned value
						_recentItems(i).Pinned = pinned
					End If
				Next i
			ElseIf e.Key.PropertyKey = RibbonProperties.SelectedItem Then
				' get selected item index
				Dim selectedItem As UInteger = CUInt(e.CurrentValue.PropVariant.Value)

				' get selected item label
				Dim propLabel As PropVariant
				e.CommandExecutionProperties.GetValue(RibbonProperties.Label, propLabel)
				Dim label As String = CStr(propLabel.Value)

				' get selected item label description
				Dim propLabelDescription As PropVariant
				e.CommandExecutionProperties.GetValue(RibbonProperties.LabelDescription, propLabelDescription)
				Dim labelDescription As String = CStr(propLabelDescription.Value)

				' get selected item pinned value
				Dim propPinned As PropVariant
				e.CommandExecutionProperties.GetValue(RibbonProperties.Pinned, propPinned)
				Dim pinned As Boolean = CBool(propPinned.Value)
			End If
		End Sub
	End Class
End Namespace


text:
package uk.ac.ebi.embl.flatfile.reader.embl;

import uk.ac.ebi.embl.flatfile.EmblTag;
import uk.ac.ebi.embl.flatfile.reader.LineReader;
import uk.ac.ebi.embl.flatfile.reader.SingleLineBlockReader;

/** Reader for the flat file AH lines.
 */
public class AHReader extends SingleLineBlockReader {

	public AHReader(LineReader lineReader) {
		super(lineReader);
	}

	@Override
	public String getTag() {
		return EmblTag.AH_TAG;
	}

	@Override
	protected void read(String block) {
		return;
	}
}


text:
var fs     = require('fs');
var path   = require('path');
var rimraf = require('rimraf');

// Creates an HTML page out of a documentation object, and writes it to disk.
// tree: a component object generated by Super.parse().
module.exports = function(data) {
  // Get a Handlebars instance
  var handlebars = this.options.handlebars || require('handlebars');

  // Fetch template code
  var fileData = fs.readFileSync(this.options.template);

  // Compile it into Handlebars templates
  var template = handlebars.compile(fileData.toString(), {noEscape: true});

  // Render a template with the component's data and write it to disk
  var output = '';

  // Catch Handlebars errors, because they won't show up in the Gulp console
  try {
    output = template(data);
  }
  catch(e) {
    throw new Error('Handlebars error: ' + e.message);
  }

  return output;
}


text:
@implementation TestableEntity

@synthesize insertExpectation;
@synthesize deleteExpectation;
@synthesize updateExpectation;
@synthesize moveExpectation;

@end


text:
<?php

namespace Sabre\Xml;

interface XmlDeserializable {

    /**
     * The deserialize method is called during xml parsing.
     *
     * This method is called statically, this is because in theory this method
     * may be used as a type of constructor, or factory method.
     *
     * Often you want to return an instance of the current class, but you are
     * free to return other data as well.
     *
     * You are responsible for advancing the reader to the next element. Not
     * doing anything will result in a never-ending loop.
     *
     * If you just want to skip parsing for this element altogether, you can
     * just call $reader->next();
     *
     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
     * the next element.
     *
     * @param Reader $reader
     * @return mixed
     */
    static function xmlDeserialize(Reader $reader);

}


text:
using namespace NBsc;
using ::testing::Return;
using ::testing::AtLeast;
//using ::testing::TypedEq;

std::string messageREQ = "{\"ptl_ver\":{\"major\":1,\"minor\":0},\"msg_type\":\"REQ\",\"msg_id\":9,\"method\":\"getNavData\",\"parameters\":{\"a\":\"b\",\"c\":\"d\"}}";
std::string messageRESP = "{\"ptl_ver\":{\"major\":1,\"minor\":0},\"msg_type\":\"RESP\",\"msg_id\":0,\"method\":\"\",\"resp_code\":1}";

class MyThreadSP : public CPThread
{
public:
  void *run()
  {
    printf("thread %lu running\n",  (long unsigned int)self());

    std::string instance = "SP: ";
    std::cout << instance + " thread start at LocalTimeStamp():" << CLtpTimestampedLocation::GetLocalTimeStamp() << std::endl;

    // Create SP connection = create client socket, then connect to server socket.
    CLtpConnection* pSPconnection = new CLtpConnection(instance, ESocketType_IP);

    // One time socket write().
    pSPconnection->blockSocketSendMessage(instance, messageREQ);

    delete pSPconnection;

    printf("thread done %lu\n", (long unsigned int)self());
    return NULL;
  }
};

class MyThreadHU : public CPThread
{
public:
  void *run()
  {
    printf("thread %lu running\n",  (long unsigned int)self());

    std::string instance = "HU: ";
    std::cout << instance + " thread start at LocalTimeStamp():" << CLtpTimestampedLocation::GetLocalTimeStamp() << std::endl;

    CConnectionListenerMock HuConnectionListenerMock;
    // Create HU connection = create server socket, then bind()/listen() for the client socket.
    CLtpConnection* pHUconnection = new CLtpConnection(instance, ESocketType_IP);
    pHUconnection->registerListener(instance, HuConnectionListenerMock);

    // When SP write a string to HU, low level socket write API will auto append "\n" to string end(if the original string is not end with "\n"),
    // this "\n" is required for Android socket read API as a message ending.
    EXPECT_CALL(HuConnectionListenerMock, messageReceived(messageREQ+"\n"))
      .Times(AtLeast(1))
      .WillRepeatedly(Return());

    // Wait for one time socket read().
    // We don't want HU socket server entering a infinity accept() -> read()/write() loop, so just specify that it will just do this loop once.
    pHUconnection->startConnectorSocketServerLoop(1);

    // Wait for a short time to prevent disconnect(destruct pHUconnection will disconnect) before SP read() RESP from socket.
    std::cout << "sleep(2) after startConnectorSocketServerLoop(1)" << std::endl;
    sleep(2);

    delete pHUconnection;

    printf("thread done %lu\n", (long unsigned int)self());
    return NULL;
  }
};

class CLtpConnectionTest: public ::testing::Test
{
};

TEST_F(CLtpConnectionTest, CLtpConnectionConstructorAndDestructor)
{
  CLtpConnection* pconnectionImpl = new CLtpConnection("HU: ", ESocketType_IP);

  EXPECT_TRUE(pconnectionImpl != NULL);

  delete pconnectionImpl;
}

TEST_F(CLtpConnectionTest, CLtpConnectionblockSocketSendReceiveMessages)
{
  std::cout << "CLtpConnectionTest unit testing Start!!!" << std::endl;
  std::cout << "LocalTimeStamp():" << CLtpTimestampedLocation::GetLocalTimeStamp() << std::endl;

  MyThreadHU* threadHU = new MyThreadHU();
  MyThreadSP* threadSP = new MyThreadSP();

  threadHU->start();

  // Wait for HU thread ready and running.
  std::cout << "sleep(1)" << std::endl;
  sleep(1);

  threadSP->start();

  // Wait for everything done.
  std::cout << "sleep(1)" << std::endl;
  sleep(1);

  //threadHU->join();
  //threadSP->join();

  std::cout << "CLtpConnectionTest unit testing Done!!!" << std::endl;
}


text:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import 'rxjs/Rx'; // get everything from Rx (overkill replace with barrel)
// My app
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);


text:
{% load static %}

<!doctype html>

        <title>Imperial Blog</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
        <link rel="stylesheet" href="{% static 'css/galactic.css' %}">
        <link href='http://fonts.googleapis.com/css?family=Trade+Winds|Waiting+for+the+Sunrise|Orbitron|Rock+Salt|Montserrat+Subrayada:400,700|Slackey' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="{% static 'css/elusive-webfont.css' %}">

                    <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
                        Toggle navigation

                    </button>
                    Imperial Blog

                            Archives

                            Kindle Notes

                            Categories

                            Projects

                        {% if user.is_authenticated %}

                            Sidious

                        {% endif %}

                            About

        {% block content %}
        {% endblock %}


text:
package com.onegravity.rteditor.spans;

import com.onegravity.rteditor.api.media.RTAudio;

/**
 * An ImageSpan representing an embedded audio file.
 */
public class AudioSpan extends MediaSpan {

    public AudioSpan(RTAudio audio, boolean isSaved) {
        super(audio, isSaved);
    }

    public RTAudio getAudio() {
        return (RTAudio) mMedia;
    }

}


text:
<?php

namespace metalguardian\i18n\components;

use metalguardian\i18n\Module;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\i18n\DbMessageSource;

/**
 * Class I18n
 */
class I18n extends \yii\i18n\I18N
{
    /**
     * Configuration of the message sources
     *
     * @var array
     */
    public $messageSourceConfig = [];

    /**
     * Handle missing translations or not
     *
     * @var bool
     */
    public $handleMissing = true;

    /**
     * List of categories to handle by message source. If not an array category * will be used to handle all sources
     *
     * @var array
     */
    public $only = [
        'app',
        '*',
    ];

    /**
     * Override existing source messages or not
     *
     * @var bool
     */
    public $override = true;

    /**
     * List of supported languages
     *
     * @var
     */
    public $languages;

    /**
     * @throws InvalidConfigException
     */
    public function init()
    {
        parent::init();

        if ($this->languages instanceof \Closure) {
            $this->languages = call_user_func($this->languages);
        }

        if (!is_array($this->languages)) {
            throw new InvalidConfigException('\metalguardian\i18n\components\I18n::languages have to be array.');
        }

        if (empty($this->languages)) {
            throw new InvalidConfigException('\metalguardian\i18n\components\I18n::languages have to contains at least 1 item.');
        }

        $config = $this->getMessageSourceConfig();

        if (is_array($this->only)) {
            foreach ($this->only as $item) {
                if ($this->override || (!isset($this->translations[$item]) && !isset($this->translations[$item . '*']))) {
                    $this->translations[$item] = $config;
                }
            }
        } else {
            if ($this->override) {
                $this->translations = [
                    '*' => $config,
                ];
            }
        }
    }

    /**
     * @return array
     */
    protected function getMessageSourceConfig()
    {
        $defaults = [
            'class' => DbMessageSource::className(),
        ];
        if ($this->handleMissing) {
            $defaults['on missingTranslation'] = [
                'metalguardian\i18n\components\TranslationEventHandler',
                'handleMissingTranslation',
            ];
        }

        return ArrayHelper::merge($defaults, $this->messageSourceConfig);
    }

    public function getSourceMessageTable()
    {
        $config = $this->getMessageSourceConfig();

        /** @var \yii\i18n\DbMessageSource $messageSource */
        $messageSource = Yii::createObject($config);

        if (!($messageSource instanceof \yii\i18n\DbMessageSource)) {
            throw new \yii\base\InvalidConfigException(Module::t('I18n message source have to be instance of \yii\i18n\DbMessageSource'));
        }

        return $messageSource->sourceMessageTable;
    }

    public function getMessageTable()
    {
        $config = $this->getMessageSourceConfig();

        /** @var \yii\i18n\DbMessageSource $messageSource */
        $messageSource = Yii::createObject($config);

        if (!($messageSource instanceof \yii\i18n\DbMessageSource)) {
            throw new \yii\base\InvalidConfigException(Module::t('I18n message source have to be instance of \yii\i18n\DbMessageSource'));
        }

        return $messageSource->messageTable;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Implier.SpreadMatrix;
using QuickFix;

namespace Implier.FIXApplication
{
    internal partial class FixApplication : Application
    {
        #region Fields
        /// <summary>
        /// accumulator for messages
        /// </summary>
        private readonly StringBuilder consoleText = new StringBuilder();
        /// <summary>
        /// sync object for thread-safe access to consoleText
        /// </summary>
        private readonly object lockObject = new object();

        private bool isTimerAdjusted;

        readonly SocketInitiator initiator;

        private SessionSettings settings;
        private FileStoreFactory storeFactory;
        private FileLogFactory logFactory;
        private MessageFactory messageFactory;
        private int logonCount = 0;

        //SpreadMatrixData SMData = null;
        SpreadMatrixCollection spreadMatrixCollection = new SpreadMatrixCollection();

        #endregion

        #region Delegaes and Events
        public delegate void MessageRecieveHandler(object sender, Message message);
        public delegate void AddTextHandler(object sender, string text);
        public event AddTextHandler OnTextAdded;
        public event EventHandler Logon;
        public event EventHandler Logout;
        #endregion

        #region Properties

        public int LogonCount
        {
            get { return logonCount; }
        }

        public string ConsoleText
        {
            get
            {
                lock (lockObject)
                {
                    return consoleText.ToString();
                }
            }
        }

        private int PriceSessionIndex{ get; set; }
        private int OrderSessionIndex{ get; set; }

        internal SpreadMatrixCollection SpreadMatrixCollection
        {
            get { return spreadMatrixCollection; }
        }

        //internal SpreadMatrixData SpreadMatrixData
        //{
        //    get
        //    {
        //        return spreadMatrixCollection.IsEmpty ? null : spreadMatrixCollection.First;
        //    }
        //}
        public static FixApplication Current
        {
            get;
            private set;
        }
        #endregion

        #region Constructor
        public FixApplication(String configFile)
        {
            try
            {
                logonCount = 0;
                Current = this;
                settings = new SessionSettings(configFile);
                storeFactory = new FileStoreFactory(settings);
                logFactory = new FileLogFactory(settings);
                messageFactory = new DefaultMessageFactory();
                SetSessionIndexes(configFile);

                initiator = new SocketInitiator(this, storeFactory, settings, logFactory, messageFactory);
                initiator.start();
                AddText("Created initiator." + Environment.NewLine);
            }
            catch (Exception exception)
            {
                AddText(exception.Message + Environment.NewLine);
                throw;
            }
        }
        #endregion

        #region Methods

        private void SetSessionIndexes(String configFile)
        {
            List<string> targetCompIDs = GetSessionTargetCompIDs(configFile);
            int priceIndex = 0;
            int orderIndex = 1;

            PriceSessionIndex = settings.getSessions().Cast<SessionID>().ToArray().ToList().FindIndex(
                sessionId => sessionId.getTargetCompID().Equals(targetCompIDs[priceIndex]));

            OrderSessionIndex = settings.getSessions().Cast<SessionID>().ToArray().ToList().FindIndex(
                sessionId => sessionId.getTargetCompID().Equals(targetCompIDs[orderIndex]));
        }

        private List<string> GetSessionTargetCompIDs(String configFile)
        {
            List<string> targetCompIDs = new List<string>();

             using(TextReader tr = new StreamReader(configFile))
             {
                 while (tr.Peek() >= 0)
                 {
                     string line = tr.ReadLine();

                     if (line.Contains("TargetCompID"))
                         targetCompIDs.Add(line.Split('=')[1]);
                 }
             }
            return targetCompIDs;
        }

        private void AddText(string text)
        {
            lock (lockObject)
            {
                consoleText.Append(text);
            }
            if (OnTextAdded != null)
                OnTextAdded(this, text);
        }

        public void StopFix()
        {
            try
            {
                initiator.stop();
                initiator.Dispose();
                AddText("Stopped initiator." + Environment.NewLine);
                SpreadMatrixCollection.Clear();
                AddText("Matrix is cleared." + Environment.NewLine);
                Current = null;
                logonCount = 0;
            }
            catch (Exception exception)
            {
                AddText(exception.Message + Environment.NewLine);
                throw;
            }
        }

        public SessionID GetOrderSession()
        {
            return settings.getSessions()[OrderSessionIndex] as SessionID;
        }

        public SessionID GetPriceSession()
        {
            return settings.getSessions()[PriceSessionIndex] as SessionID;
        }

        #endregion

        #region QuickFix.Application implementation
        public void onCreate(SessionID sessionID)
        {
            AddText("onCreate " + sessionID + Environment.NewLine);
        }

        public void onLogon(SessionID sessionID)
        {
            AddText("onLogon " + sessionID + Environment.NewLine);

            if(logonCount<2)
                logonCount ++;

            if (Logon != null)
                Logon(this, new EventArgs<SessionID>(sessionID));
        }

        public void onLogout(SessionID sessionID)
        {
            AddText("onLogout " + sessionID + Environment.NewLine);

            if(logonCount>0)
                logonCount --;

            if (Logout != null)
                Logout(this, new EventArgs<SessionID>(sessionID));
        }

        public void RequestLogon()
        {
            foreach (SessionID sessionId in settings.getSessions())
                RequestLogon(sessionId);
        }

        public void RequestLogon(SessionID sessionId)
        {
            QuickFix42.Logon logon = new QuickFix42.Logon(new EncryptMethod(EncryptMethod.NONE), new HeartBtInt(30));
            logon.set(new ResetSeqNumFlag(true));

            Session.sendToTarget(logon, sessionId);
        }

        public void RequestLogout(SessionID sessionId)
        {
            QuickFix42.Logout logout = new QuickFix42.Logout();
            Session.sendToTarget(logout, sessionId);
        }

        public void toAdmin(Message message, SessionID sessionID)
        {
            // This is only for the TT dev environment.  The production FIX Adapter does not require a password
            MsgType msgType = new MsgType();
            message.getHeader().getField(msgType);

            TargetCompID targetCompID = new TargetCompID();
            message.getHeader().getField(targetCompID);

            if (msgType.ToString() == MsgType.Logon &&
                (targetCompID.ToString() == "TTDEV9P" || targetCompID.ToString() == "TTDEV9O"))
            {
                const string password = "12345678";
                RawData rawData = new RawData(password);
                message.getHeader().setField(rawData);
            }
            // End TT Dev environment case

            //AddText("toAdmin " + message + Environment.NewLine);
        }

        public void fromAdmin(Message message, SessionID sessionID)
        {
            if(!isTimerAdjusted)
            {
                SendingTime sendingTime = new SendingTime();
                message.getHeader().getField(sendingTime);
                Utils.AdjustTime(sendingTime.getValue());
                isTimerAdjusted = true;
            }

            //AddText("fromAdmin " + message + Environment.NewLine);
        }

        public void toApp(Message message, SessionID sessionID)
        {
            //AddText("toApp " + message + Environment.NewLine);
        }

        public void fromApp(Message message, SessionID sessionID)
        {
            try
            {
                crack(message, sessionID);
            }
            catch (UnsupportedMessageType exception)
            {
                AddText("fromApp " + exception + Environment.NewLine);
                AddText("fromApp " + message + Environment.NewLine);
                throw;
            }
        }
        #endregion
    }
}


text:
//
#ifndef ANDROID_IINTERFACE_H
#define ANDROID_IINTERFACE_H

#include <binder/Binder.h>

#if defined(__linux__)  // M3E: add
#include <memory>  // std::unique_ptr
#endif //  M3E

namespace android {

// ----------------------------------------------------------------------

class IInterface : public virtual RefBase
{
public:
            IInterface();
            static sp<IBinder>  asBinder(const IInterface*);
            static sp<IBinder>  asBinder(const sp<IInterface>&);

protected:
    virtual                     ~IInterface();
    virtual IBinder*            onAsBinder() = 0;
};

// ----------------------------------------------------------------------

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    return INTERFACE::asInterface(obj);
}

// ----------------------------------------------------------------------

template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder
{
public:
    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
    virtual const String16&     getInterfaceDescriptor() const;

protected:
    typedef INTERFACE           BaseInterface;
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------

template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
    explicit                    BpInterface(const sp<IBinder>& remote);

protected:
    typedef INTERFACE           BaseInterface;
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------

#define DECLARE_META_INTERFACE(INTERFACE)                               \
public:                                                                 \
    static const ::android::String16 descriptor;                        \
    static ::android::sp<I##INTERFACE> asInterface(                     \
            const ::android::sp<::android::IBinder>& obj);              \
    virtual const ::android::String16& getInterfaceDescriptor() const;  \
    I##INTERFACE();                                                     \
    virtual ~I##INTERFACE();                                            \
    static bool setDefaultImpl(std::unique_ptr<I##INTERFACE> impl);     \
    static const std::unique_ptr<I##INTERFACE>& getDefaultImpl();       \
private:                                                                \
    static std::unique_ptr<I##INTERFACE> default_impl;                  \
public:                                                                 \

#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
    const ::android::String16 I##INTERFACE::descriptor(NAME);           \
    const ::android::String16&                                          \
            I##INTERFACE::getInterfaceDescriptor() const {              \
        return I##INTERFACE::descriptor;                                \
    }                                                                   \
    ::android::sp<I##INTERFACE> I##INTERFACE::asInterface(              \
            const ::android::sp<::android::IBinder>& obj)               \
    {                                                                   \
        ::android::sp<I##INTERFACE> intr;                               \
        if (obj != nullptr) {                                           \
            intr = static_cast<I##INTERFACE*>(                          \
                obj->queryLocalInterface(                               \
                        I##INTERFACE::descriptor).get());               \
            if (intr == nullptr) {                                      \
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    std::unique_ptr<I##INTERFACE> I##INTERFACE::default_impl;           \
    bool I##INTERFACE::setDefaultImpl(std::unique_ptr<I##INTERFACE> impl)\
    {                                                                   \
        if (!I##INTERFACE::default_impl && impl) {                      \
            I##INTERFACE::default_impl = std::move(impl);               \
            return true;                                                \
        }                                                               \
        return false;                                                   \
    }                                                                   \
    const std::unique_ptr<I##INTERFACE>& I##INTERFACE::getDefaultImpl() \
    {                                                                   \
        return I##INTERFACE::default_impl;                              \
    }                                                                   \
    I##INTERFACE::I##INTERFACE() { }                                    \
    I##INTERFACE::~I##INTERFACE() { }                                   \

#define CHECK_INTERFACE(interface, data, reply)                         \
    do {                                                                \
      if (!(data).checkInterface(this)) { return PERMISSION_DENIED; }   \
    } while (false)                                                     \

// ----------------------------------------------------------------------
// No user-serviceable parts after this...

template<typename INTERFACE>
inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
        const String16& _descriptor)
{
    if (_descriptor == INTERFACE::descriptor) return this;
    return nullptr;
}

template<typename INTERFACE>
inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const
{
    return INTERFACE::getInterfaceDescriptor();
}

template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
    return this;
}

template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
    : BpRefBase(remote)
{
}

template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
    return remote();
}

// ----------------------------------------------------------------------

}; // namespace android

#endif // ANDROID_IINTERFACE_H


text:
<?php

return [
    'input_filters' => [
        /*
         * An array of service name => config pairs.
         *
         * Service names must be unique, and will be the name by which the
         * input filter will be retrieved. The configuration is any valid
         * configuration for an input filter, as shown in the manual:
         *
         * - http://zf2.readthedocs.org/en/latest/modules/zend.input-filter.intro.html
         */
    ],
    'service_manager' => [
        'abstract_factories' => [
            'ZF\ContentValidation\InputFilter\InputFilterAbstractServiceFactory',
        ],
        'factories' => [
            'ZF\ContentValidation\ContentValidationListener' => 'ZF\ContentValidation\ContentValidationListenerFactory',
        ],
    ],
    'zf-content-validation' => [
        /*
         * An array of controller service name => config pairs.
         *
         * The configuration *must* include:
         *
         * - input_filter: the name of an input filter service to use with the
         *   given controller
         *
         * In the future, additional options may be added, such as the ability
         * to restrict by HTTP method, define validation groups by HTTP method,
         * etc.
         */
    ],
];


text:
#include "common/config.h"

#include "tbb/parallel_for.h"
#include "tbb/global_control.h"

#include "common/test.h"
#include "common/utils.h"
#include "common/utils_concurrency_limit.h"

#include <atomic>
#include <condition_variable>
#include <thread>
#include <vector>

//! \file test_eh_thread.cpp
//! \brief Test for [internal] functionality

// On Windows there is no real thread number limit beside available memory.
// Therefore, the test for thread limit is unreasonable.
// TODO: enable limitThreads with sanitizer under docker
#if TBB_USE_EXCEPTIONS && !_WIN32 && !__ANDROID__

#include <limits.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>

void limitThreads(size_t limit)
{
    rlimit rlim;

    int ret = getrlimit(RLIMIT_NPROC, &rlim);
    CHECK_MESSAGE(0 == ret, "getrlimit has returned an error");

    rlim.rlim_cur = (rlim.rlim_max == (rlim_t)RLIM_INFINITY) ? limit : utils::min(limit, rlim.rlim_max);

    ret = setrlimit(RLIMIT_NPROC, &rlim);
    CHECK_MESSAGE(0 == ret, "setrlimit has returned an error");
}

size_t getThreadLimit() {
    rlimit rlim;

    int ret = getrlimit(RLIMIT_NPROC, &rlim);
    CHECK_MESSAGE(0 == ret, "getrlimit has returned an error");
    return rlim.rlim_cur;
}

static void* thread_routine(void*)
{
    return nullptr;
}

class Thread {
    pthread_t mHandle{};
    bool mValid{};
public:
    Thread() {
        mValid = false;
        pthread_attr_t attr;
        // Limit the stack size not to consume all virtual memory on 32 bit platforms.
        std::size_t stacksize = utils::max(128*1024, PTHREAD_STACK_MIN);
        if (pthread_attr_init(&attr) == 0 && pthread_attr_setstacksize(&attr, stacksize) == 0) {
            mValid = pthread_create(&mHandle, &attr, thread_routine, /* arg = */ nullptr) == 0;
        }
    }
    bool isValid() const { return mValid; }
    void join() {
        pthread_join(mHandle, nullptr);
    }
};

//! Test for exception when too many threads
//! \brief \ref resource_usage
TEST_CASE("Too many threads") {
    if (utils::get_platform_max_threads() < 2) {
        // The test expects that the scheduler will try to create at least one thread.
        return;
    }

    // Some systems set really big limit (e.g. >45К) for the number of processes/threads
    limitThreads(1);
    if (getThreadLimit() == 1) {
        for (int attempt = 0; attempt < 5; ++attempt) {
            Thread thread;
            if (thread.isValid()) {
                WARN_MESSAGE(false, "We were able to create a thread. setrlimit seems having no effect");
                thread.join();
                return;
            }
        }
        bool g_exception_caught = false;
        try {
            // Initialize the library to create worker threads
            tbb::parallel_for(0, 2, [](int) {});
        } catch (const std::exception & e) {
            g_exception_caught = true;
            // Do not CHECK to avoid memory allocation (we can be out of memory)
            if (e.what()== nullptr) {
                FAIL("Exception does not have description");
            }
        }
        // Do not CHECK to avoid memory allocation (we can be out of memory)
        if (!g_exception_caught) {
            FAIL("No exception was thrown on library initialization");
        }
    } else {
        WARN_MESSAGE(false, "setrlimit seems having no effect");
    }
}
#endif


text:
package com.thinkgem.jeesite.modules.sys.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.security.Digests;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.Encodes;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.Menu;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemRealm;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 系统管理,安全相关实体的管理类,包括用户、角色、菜单.
 * @author ThinkGem
 * @version 2013-4-19
 */
@Service
@Transactional(readOnly = true)
public class SystemService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(SystemService.class);

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;

	@Autowired
	private UserDao userDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private SystemRealm systemRealm;

	//-- User Service --//

	public User getUser(Long id) {
		return userDao.findOne(id);
	}

	public Page<User> findUser(Page<User> page, User user) {
		DetachedCriteria dc = userDao.createDetachedCriteria();

		if (StringUtils.isNotEmpty(user.getLoginName())){
			dc.add(Restrictions.like("loginName", "%"+user.getLoginName()+"%"));
		}
		if (StringUtils.isNotEmpty(user.getName())){
			dc.add(Restrictions.like("name", "%"+user.getName()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", User.DEL_FLAG_NORMAL));
		if (!StringUtils.isNotEmpty(page.getOrderBy())){
			dc.addOrder(Order.desc("id"));
		}
		return userDao.find(page, dc);
	}

	public User getUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

	@Transactional(readOnly = false)
	public void saveUser(User user) {
		userDao.clear();
		userDao.save(user);
		systemRealm.clearCachedAuthorizationInfo(user.getLoginName());
	}

	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		userDao.deleteById(id);
	}

	@Transactional(readOnly = false)
	public void updatePasswordById(Long id, String loginName, String newPassword) {
		userDao.updatePasswordById(entryptPassword(newPassword), id);
		systemRealm.clearCachedAuthorizationInfo(loginName);
	}

	@Transactional(readOnly = false)
	public void updateUserLoginInfo(Long id) {
		userDao.updateLoginInfo(SecurityUtils.getSubject().getSession().getHost(), new Date(), id);
	}

	/**
	 * 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}

	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
	}

	//-- Menu Service --//

	public Menu getMenu(Long id) {
		return menuDao.findOne(id);
	}

	public List<Menu> findAllMenu(){
		return UserUtils.getMenuList();
	}

}


text:
'use strict';

var gulp = require('gulp');

// plugins
var autoprefixer = require('gulp-autoprefixer');
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var vulcanize = require('gulp-vulcanize');
var del = require('del');

gulp.task('help', function() {
	console.log('This are the following available tasks:');
	console.log('');
	console.log('  build:      builds the distribution version (default)');
	console.log('  serve:      serves a development version of the program');
	console.log('  serve-dist: serves the distribution version (w/o livereload)');
	console.log('  clean:      clean temporary and distribution files');
});

// configuration
var config = {
	src: 'src',
	tmp: '.tmp',
	dist: 'www',
	port: 9649,
	liveport: 19649,
	winport: 9648,
	distport: 9647,
};

// Common tasks
/////////////////////////////////////////////////////////////////////////////

gulp.task('clean', function(done) {
	del([
		config.tmp,
		config.dist+'/**/*',
		'!'+config.dist+'/.git',
	], done);
});

gulp.task('jshint', function() {
	return gulp.src(['gulpfile.js', config.src+'/**/*.js'])
		.pipe(jshint())
		.pipe(jshint.reporter('default'))
		//.pipe(jshint.reporter('fail'))
		.pipe(connect.reload());
});

// Develop tasks
/////////////////////////////////////////////////////////////////////////////

gulp.task('dev-styles', ['jshint', 'clean'], function() {
	return gulp.src(config.src+'/**/*.scss')
		.pipe(sass({expand: true}))
		.pipe(autoprefixer({browsers: ['last 2 version', 'ie 9']}))
		.pipe(gulp.dest(config.tmp))
		.pipe(connect.reload());
});

gulp.task('dev-htmls', function() {
	return gulp.src(config.src+'/**/*.html')
		.pipe(connect.reload());
});

gulp.task('serve', ['jshint','dev-styles'], function() {
	connect.server({
		root: [ config.tmp, config.src, '.' ],
		port: config.port,
		livereload: {port: config.livereload},
		hostname: '0.0.0.0',
	});

	gulp.watch(['gulpfile.js', config.src+'/**/*.js'], ['jshint']);
	gulp.watch([config.src+'/**/*.scss'], ['dev-styles']);
	gulp.watch([config.src+'/**/*.html'], ['dev-htmls']);
});

gulp.task('serve-win', ['jshint','dev-styles'], function() {
	connect.server({
		root: [ config.tmp, config.src, '.' ],
		port: config.winport,
		livereload: false,
		hostname: '0.0.0.0',
	});
});

// Distibution tasks
/////////////////////////////////////////////////////////////////////////////

gulp.task('dist-copy-src', ['jshint','clean'], function() {
	return gulp.src(config.src+'/**/*.{js,html}')
		.pipe(gulp.dest(config.tmp));
});

gulp.task('dist-copy-bc', ['clean'], function() {
	return gulp.src('bower_components/**/*')
		.pipe(gulp.dest(config.tmp+'/bower_components'));
});

gulp.task('vulcanize-carousel', ['dist-copy-src','dev-styles'], function(done) {
	gulp.src(config.tmp+'/carousel/carousel.html')
		.pipe(vulcanize({
			dest: config.tmp+'/carousel',
			strip: true,
			inline: true,
			excludes: {
				imports: [
					'polymer.html',
				],
			},
		}))
		.pipe(gulp.dest(config.tmp+'/carousel'))
		// workaround becaus reason gulp do not detect end of task when return used, http://stackoverflow.com/questions/23584962/gulp-js-starts-sass-task-but-doesnt-finish
		.pipe({
			emit: function() {},
			on: function() {if (done) { done(); done = null;}},
		});
		//setTimeout(done, 400);
});

gulp.task('vulcanize-polymer', ['dist-copy-bc'], function(done) {
	gulp.src(config.tmp+'/bower_components/polymer/polymer.html')
		.pipe(vulcanize({
			dest: config.tmp+'/bower_components/polymer',
			strip: true,
			inline: true,
		}))
		.pipe(gulp.dest(config.tmp+'/bower_components/polymer'))

		// workaround becaus reason gulp do not detect end of task when return used, http://stackoverflow.com/questions/23584962/gulp-js-starts-sass-task-but-doesnt-finish
		.pipe({
			emit: function() {},
			on: function() {if (done) { done(); done = null;}},
		});
		//setTimeout(done, 400);
});

gulp.task('dist-copy-vcarousel', ['vulcanize-carousel'], function() {
	return gulp.src(config.tmp+'/carousel/carousel.html')
		.pipe(gulp.dest(config.dist+'/carousel'));
});

gulp.task('dist-copy-vpolymer', ['vulcanize-polymer'], function() {
	return gulp.src(config.tmp+'/bower_components/polymer/polymer.html')
		.pipe(gulp.dest(config.dist+'/bower_components/polymer'));
});

gulp.task('dist-copy', ['vulcanize-carousel','vulcanize-polymer'], function() {
	return gulp.src([
			config.tmp+'/index.html',
			config.tmp+'/**/webcomponents.min.js',
			config.tmp+'/**/polymer.html',
			config.tmp+'/**/carousel.html',
		])
		.pipe(gulp.dest(config.dist));
});

gulp.task('build', ['dist-copy'], function() {
});

gulp.task('serve-dist', ['build'], function() {
	connect.server({
		root: [ config.dist ],
		port: config.distport,
		livereload: false,
		hostname: '0.0.0.0',
	});
});

// Default Task
/////////////////////////////////////////////////////////////////////////////

gulp.task('default', ['build']);


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>OmniBlocks - Home Page</title>
    <meta name="Author" content="Artur Janik"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href='https://fonts.googleapis.com/css?family=Ubuntu:400,500,700,300&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="./assets/css/style.css">
    <link rel="stylesheet" href="./assets/css/font-awesome.min.css">

    content

        © 2016 OmniBlocks
        Visit on github


text:
// ```ts
/* tslint:disable */

interface Type<TValue> {
  readonly kind: string
  isTypeOf (value: mixed): value is TValue
}

// TODO: Could this just be an either type?
interface NullableType<
  TNullValue,
  TNotNullValue,
> extends Type<TNullValue | TNotNullValue> {
  readonly kind: 'NULLABLE'
  readonly nonNullType: Type<TNotNullValue>
  isNull (value: TNullValue | TNotNullValue): value is TNullValue
  isNotNull (value: TNullValue | TNotNullValue): value is TNotNullValue
}

interface ListType<
  TValue,
  TItemValue,
> extends Type<TValue> {
  readonly kind: 'LIST'
  readonly itemType: Type<TItemValue>
  getLength (value: TValue): number
  getItemAt (value: TValue, index: number): TItemValue | undefined
  intoArray? (value: TValue): Array<TItemValue>
  fromArray (array: Array<TItemValue>): TValue
}

interface NamedType<TValue> extends Type<TValue> {
  readonly name: string
  readonly description?: string | undefined
}

interface AliasType<TValue> extends NamedType<TValue> {
  readonly kind: 'ALIAS'
  readonly baseType: Type<TValue>
}

interface EnumType<TValue> extends NamedType<TValue> {
  readonly kind: 'ENUM'
  readonly variants: Set<TValue>
  getName (variant: TValue): string
}

interface ObjectType<TValue> extends NamedType<TValue> {
  readonly kind: 'OBJECT'
  readonly fields: Map<string, ObjectType.Field<TValue, mixed>>
  fromFields (fieldValues: Map<string, mixed>): TValue
}

namespace ObjectType {
  export interface Field<TObjectValue, TValue> {
    readonly description?: string | undefined
    readonly type: Type<TValue>
    getValue (objectValue: TObjectValue): TValue
  }
}

type SwitchTypeCases<T> = {
  nullable: (type: NullableType<mixed, mixed>) => T,
  list: (type: ListType<mixed, mixed>) => T,
  alias: (type: AliasType<mixed>) => T,
  enum: (type: EnumType<mixed>) => T,
  object: (type: ObjectType<mixed>) => T,
}

function switchType <T>(type: Type<mixed>, cases: SwitchTypeCases<T>): T
function switchType <T>(cases: SwitchTypeCases<T>): (type: Type<mixed>) => T
function switchType <T>(typeOrCases: Type<mixed> | SwitchTypeCases<T>, maybeCases?: SwitchTypeCases<T>): T | ((type: Type<mixed>) => T) {
  if (typeof typeOrCases['kind'] === 'string' && maybeCases)
    return switchType(maybeCases)(typeOrCases as any)

  const cases = typeOrCases as SwitchTypeCases<T>

  return (type: Type<mixed>): T => {
    switch (type.kind) {
      case 'NULLABLE': return cases.nullable(type as any)
      case 'LIST': return cases.list(type as any)
      case 'ALIAS': return cases.alias(type as any)
      case 'ENUM': return cases.enum(type as any)
      case 'OBJECT': return cases.object(type as any)
      default: throw new Error(`Type of kind '${type.kind}' is unrecognized.`)
    }
  }
}

const getNamedType: (type: Type<mixed>) => NamedType<mixed> = switchType<NamedType<mixed>>({
  nullable: type => getNamedType(type.nonNullType),
  list: type => getNamedType(type.itemType),
  alias: type => type,
  enum: type => type,
  object: type => type,
})

// ```


text:
package org.biacode.jcronofy.api.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;
import java.util.Date;

/**
 * User: Arthur Asatryan
 * Date: 10/4/16
 * Time: 6:38 PM
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class FreeBusyModel implements Serializable {
    private static final long serialVersionUID = -9149242550146191351L;

    //region Properties
    @JsonProperty("calendar_id")
    private String calendarId;

    @JsonProperty("start")
    private Date start;

    @JsonProperty("end")
    private Date end;

    @JsonProperty("free_busy_status")
    private FreeBusyStatusModel status;
    //endregion

    //region Constructors
    public FreeBusyModel() {
    }

    public FreeBusyModel(final String calendarId,
                         final Date start,
                         final Date end,
                         final FreeBusyStatusModel status) {
        this.calendarId = calendarId;
        this.start = ObjectUtils.clone(start);
        this.end = ObjectUtils.clone(end);
        this.status = status;
    }
    //endregion

    //region Equals, HashCode and ToString
    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof FreeBusyModel)) {
            return false;
        }
        final FreeBusyModel that = (FreeBusyModel) o;
        return new EqualsBuilder()
                .append(calendarId, that.calendarId)
                .append(start, that.start)
                .append(end, that.end)
                .append(status, that.status)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(calendarId)
                .append(start)
                .append(end)
                .append(status)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("calendarId", calendarId)
                .append("start", start)
                .append("end", end)
                .append("status", status)
                .toString();
    }
    //endregion

    //region Properties getters and setters
    public String getCalendarId() {
        return calendarId;
    }

    public void setCalendarId(final String calendarId) {
        this.calendarId = calendarId;
    }

    public Date getStart() {
        return ObjectUtils.clone(start);
    }

    public void setStart(final Date start) {
        this.start = ObjectUtils.clone(start);
    }

    public Date getEnd() {
        return ObjectUtils.clone(end);
    }

    public void setEnd(final Date end) {
        this.end = ObjectUtils.clone(end);
    }

    public FreeBusyStatusModel getStatus() {
        return status;
    }

    public void setStatus(final FreeBusyStatusModel status) {
        this.status = status;
    }
    //endregion
}


text:
{% extends parentLayout ?? '_layouts/cp' %}

{% do view.registerAssetBundle('verbb\\assetcount\\assetbundles\\AssetCountAsset') %}

{% if title is not defined %}
    {% set title = 'Asset Count' | t('asset-count') %}
{% endif %}

{% set content %}

    {% block blockContent %}

    {% endblock %}

            {% block footerButton %}

            {% endblock %}

                Made with ♥ by

                            {% include 'verbb-base/_svg/verbb-logo.svg' %}

{% endset %}


text:
from mod_pywebsocket import msgutil
import urllib

import time

def web_socket_do_extra_handshake(request):
	pass

def web_socket_transfer_data(request):
	time.sleep(2)
	msgutil._write(request, urllib.unquote(request.ws_location.split('?', 1)[1]).decode("string-escape"))


text:
require "google/cloud/recaptcha_enterprise/v1beta1/recaptcha_enterprise_service"
require "google/cloud/recaptcha_enterprise/v1beta1/version"

module Google
  module Cloud
    module RecaptchaEnterprise
      ##
      # To load this package, including all its services, and instantiate a client:
      #
      # @example
      #
      #     require "google/cloud/recaptcha_enterprise/v1beta1"
      #     client = ::Google::Cloud::RecaptchaEnterprise::V1beta1::RecaptchaEnterpriseService::Client.new
      #
      module V1beta1
      end
    end
  end
end

helper_path = ::File.join __dir__, "v1beta1", "_helpers.rb"
require "google/cloud/recaptcha_enterprise/v1beta1/_helpers" if ::File.file? helper_path


text:
package com.android.tools.build.bundletool.validation;

import static com.android.tools.build.bundletool.model.BundleModule.ABI_SPLITTER;
import static com.android.tools.build.bundletool.model.BundleModule.APEX_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.ASSETS_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.DEX_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.LIB_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.MANIFEST_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.MANIFEST_FILENAME;
import static com.android.tools.build.bundletool.model.BundleModule.RESOURCES_DIRECTORY;
import static com.android.tools.build.bundletool.model.BundleModule.ROOT_DIRECTORY;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;

import com.android.tools.build.bundletool.model.AbiName;
import com.android.tools.build.bundletool.model.BundleModule.SpecialModuleEntry;
import com.android.tools.build.bundletool.model.ZipPath;
import com.android.tools.build.bundletool.model.exceptions.InvalidBundleException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import java.util.regex.Pattern;

/** Validates files inside a bundle. */
public class BundleFilesValidator extends SubValidator {

  private static final Pattern CLASSES_DEX_PATTERN = Pattern.compile("classes[0-9]*\\.dex");

  private static final ImmutableSet<ZipPath> RESERVED_ROOT_APK_ENTRIES =
      ImmutableSet.of(
          // Special directories.
          // The below is temporarily commented and should be revisited in the future: re-enabled
          // or permanently deleted.
          // ASSETS_DIRECTORY,
          LIB_DIRECTORY,
          RESOURCES_DIRECTORY,
          // Special files in the binary APKs.
          ZipPath.create("AndroidManifest.xml"),
          ZipPath.create("resources.arsc"),
          // Special files in the proto APKs (created by the 'split-module' command).
          ZipPath.create(MANIFEST_FILENAME),
          SpecialModuleEntry.RESOURCE_TABLE.getPath());

  @Override
  public void validateModuleFile(ZipPath file) {
    String fileName = file.getFileName().toString();

    if (file.startsWith(ASSETS_DIRECTORY)) {
      // No restrictions.

    } else if (file.startsWith(DEX_DIRECTORY)) {
      if (!fileName.endsWith(".dex")) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Files under %s/ must have %s extension, found '%s'.", DEX_DIRECTORY, ".dex", file)
            .build();
      }
      if (!CLASSES_DEX_PATTERN.matcher(fileName).matches()) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Files under %s/ must match the 'classes[0-9]*.dex' pattern, found '%s'.",
                DEX_DIRECTORY, file)
            .build();
      }
      if (file.getNameCount() != 2) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "The %s/ directory cannot contain directories, found '%s'.", DEX_DIRECTORY, file)
            .build();
      }
    } else if (file.startsWith(LIB_DIRECTORY)) {
      if (file.getNameCount() != 3) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Native library files need to have paths in form '%s/<single-directory>/<file>.so'"
                    + " but found '%s'.",
                LIB_DIRECTORY, file)
            .build();
      }

      // See https://developer.android.com/ndk/guides/wrap-script#packaging_wrapsh
      if (!fileName.endsWith(".so") && !fileName.equals("wrap.sh")) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Files under %s/ must have %s extension, found '%s'.", LIB_DIRECTORY, ".so", file)
            .build();
      }

      String subDirName = file.getName(1).toString();
      if (!AbiName.fromLibSubDirName(subDirName).isPresent()) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Unrecognized native architecture for directory '%s'.", file.subpath(0, 2))
            .build();
      }

    } else if (file.startsWith(MANIFEST_DIRECTORY)) {
      if (!fileName.equals("AndroidManifest.xml")) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Only '%s' is accepted under directory '%s/' but found file '%s'.",
                MANIFEST_FILENAME, MANIFEST_DIRECTORY, file)
            .build();
      }

    } else if (file.startsWith(RESOURCES_DIRECTORY)) {
      // No restrictions.

    } else if (file.startsWith(ROOT_DIRECTORY)) {
      ZipPath nameUnderRoot = file.getName(1);
      if (isReservedRootApkEntry(nameUnderRoot)) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "File '%s' uses reserved file or directory name '%s'.", file, nameUnderRoot)
            .build();
      }

    } else if (file.startsWith(APEX_DIRECTORY)) {
      if (file.getNameCount() != 2) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "APEX image files need to have paths in form '%s/<file>.img' but found '%s'.",
                APEX_DIRECTORY, file)
            .build();
      }

      if (!fileName.endsWith(".img") && !fileName.endsWith(".build_info.pb")) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Files under %s/ must have %s extension, found '%s'.", APEX_DIRECTORY, ".img", file)
            .build();
      }

      validateMultiAbiFileName(file);

    } else {
      throw InvalidBundleException.builder()
          .withUserMessage(
              "Module files can be only in pre-defined directories, but found '%s'.", file)
          .build();
    }
  }

  private static boolean isReservedRootApkEntry(ZipPath name) {
    return RESERVED_ROOT_APK_ENTRIES.contains(name)
        || CLASSES_DEX_PATTERN.matcher(name.toString()).matches();
  }

  private static void validateMultiAbiFileName(ZipPath file) {
    if (!file.toString().endsWith(".img")) {
      return;
    }
    ImmutableList<String> tokens =
        ImmutableList.copyOf(ABI_SPLITTER.splitToList(file.getFileName().toString()));
    int nAbis = tokens.size() - 1;

    ImmutableList<Optional<AbiName>> abis =
        // Do not include the suffix "img".
        tokens.stream().limit(nAbis).map(AbiName::fromPlatformName).collect(toImmutableList());
    if (!abis.stream().allMatch(Optional::isPresent)) {
      throw InvalidBundleException.builder()
          .withUserMessage("Unrecognized native architecture for file '%s'.", file)
          .build();
    }

    ImmutableSet<AbiName> uniqueAbis = abis.stream().map(Optional::get).collect(toImmutableSet());
    if (uniqueAbis.size() != nAbis) {
      throw InvalidBundleException.builder()
          .withUserMessage("Repeating architectures in APEX system image file '%s'.", file)
          .build();
    }
  }
}


text:
package org.assertj.core.api.floatarray;

import org.assertj.core.api.FloatArrayAssert;
import org.assertj.core.api.FloatArrayAssertBaseTest;

import static org.mockito.Mockito.verify;

/**
 * Tests for <code>{@link FloatArrayAssert#hasSize(int)}</code>.
 *
 * @author Alex Ruiz
 */
public class FloatArrayAssert_hasSize_Test extends FloatArrayAssertBaseTest {

  @Override
  protected FloatArrayAssert invoke_api_method() {
    return assertions.hasSize(6);
  }

  @Override
  protected void verify_internal_effects() {
    verify(arrays).assertHasSize(getInfo(assertions), getActual(assertions), 6);
  }
}


text:
Helper for define exception classes (PHP).

[![Latest Stable Version](https://img.shields.io/packagist/v/axy/errors.svg?style=flat-square)](https://packagist.org/packages/axy/errors)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.1-8892BF.svg?style=flat-square)](https://php.net/)
[![Build Status](https://img.shields.io/travis/axypro/errors/master.svg?style=flat-square)](https://travis-ci.org/axypro/errors)
[![Coverage Status](https://coveralls.io/repos/axypro/errors/badge.svg?branch=master&service=github)](https://coveralls.io/github/axypro/errors?branch=master)
[![License](https://poser.pugx.org/axy/errors/license)](LICENSE)

* The library does not require any dependencies (except composer packages).
* Tested on PHP 5.4+, PHP 7, HHVM (on Linux), PHP 5.5 (on Windows).
* Install: `composer require axy/errors`.
* License: [MIT](LICENSE).

### Legacy (PHP5.4+, branch php5)

[![Latest Stable Version](https://img.shields.io/packagist/v/axy/errors.svg?style=flat-square)](https://packagist.org/packages/axy/errors)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%205.4-8892BF.svg?style=flat-square)](https://php.net/)
[![Build Status](https://img.shields.io/travis/axypro/errors/php5.svg?style=flat-square)](https://travis-ci.org/axypro/errors)

* Install: `composer require axy/errors=^1.
* Tested on PHP 5.4+, PHP 7, HHVM (on Linux), PHP 5.5 (on Windows).

### Documentation

* [Common organization of exceptions](doc/org.md)
* [Some number of basic classes](doc/errors.md)
* [Default message](doc/message.md)
* [Truncate backtrace](doc/backtrace.md)
* [Global options](doc/Opts.md)


text:
var compare = require('dom-compare').compare;
var reporter = require('dom-compare').GroupingReporter;
var jsdom = require("jsdom");

module.exports = function() {
  return {
    compare: function(actual, expected) {
      if (typeof actual !== 'object') {
        actual = jsdom.jsdom(actual);
      }

      if (typeof expected !== 'object') {
        expected = jsdom.jsdom(expected);
      }

      var result = compare(expected, actual, {stripSpaces: true});

      return {
        pass: result.getResult(),
        message: result.getResult()
          ? "Expected HTML not to match"
          : "Expected HTML to match: " + reporter.report(result)
      };
    }
  };
};