text:
#include <Framework/Controls/ScrollViewer.h>
#include <Framework/Controls/ScrollBar.h>
#include <Framework/Presenter/ScrollContentPresenter.h>

#include <Framework/Animation/AnimationAsSeries.h>

#include <System/Tools/EventHelper.h>
#include <System/Tools/CommandOp.h>
#include <System/Input/KeyboardNavigation.h>

#include <Framework/Controls/Popup.h>
#include <System/Tools/VisualTreeOp.h>

namespace suic
{

ImplementRTTIOfClass(ScrollViewer, ContentControl)

const int ScrollViewer::scScrollLineDelta = 16;
const int ScrollViewer::scMouseWheelDelta = 48;

DpProperty* ScrollViewer::CanContentScrollProperty;
DpProperty* ScrollViewer::SmoothingScrollProperty;
//DpProperty* ScrollViewer::ContentHorizontalOffsetProperty;
//DpProperty* ScrollViewer::ContentVerticalOffsetProperty;
//DpProperty* ScrollViewer::ExtentHeightProperty;
//DpProperty* ScrollViewer::ExtentWidthProperty;
//DpProperty* ScrollViewer::ScrollableWidthProperty;
//DpProperty* ScrollViewer::ScrollableHeightProperty;
//DpProperty* ScrollViewer::ViewportHeightProperty;
//DpProperty* ScrollViewer::ViewportWidthProperty;
DpProperty* ScrollViewer::HorizontalOffsetProperty;
DpProperty* ScrollViewer::HorizontalScrollBarVisibilityProperty;

DpProperty* ScrollViewer::VerticalOffsetProperty;
DpProperty* ScrollViewer::VerticalScrollBarVisibilityProperty;

DpProperty* ScrollViewer::ComputedHorizontalScrollBarVisibilityProperty;
DpProperty* ScrollViewer::ComputedVerticalScrollBarVisibilityProperty;

//DpProperty* ScrollViewer::ComputedHorizontalScrollBarVisibilityProperty;
//DpProperty* ScrollViewer::ComputedVerticalScrollBarVisibilityProperty;

RoutedEvent* ScrollViewer::ScrollChangedEvent;

static String HorizontalScrollBarTemplateName = _U("PART_HorizontalScrollBar");
static String VerticalScrollBarTemplateName = _U("PART_VerticalScrollBar");
static String ScrollContentPresenterTemplateName = _U("PART_ScrollContentPresenter");

enum Flags
{
    Unknow = 0,
    InMeasure = 1,
    InChildInvalidateMeasure = 2,
    RequestComputeMeasure = 4,
    HandlesMouseWheelScrolling = 8,
    ForceNextManipulationComplete = 0x10,

    ManipulationBindingsInitialized = 0x20,
    CompleteScrollManipulation = 0x40,
    ScrollChangedDirty = 0x60,
};

AutoObj SBVisibilityConvert::ConvertValue(DpProperty* dp, Object* val)
{
    String strVal(val->ToString());
    if (strVal.Equals(_U("Auto")))
    {
        return Integer::GetPosInt(ScrollBarVisibility::sbvAutoScroll);
    }
    else if (strVal.Equals(_U("Disabled")))
    {
        return Integer::GetPosInt(ScrollBarVisibility::sbvDisabled);
    }
    else if (strVal.Equals(_U("Hidden")))
    {
        return Integer::GetPosInt(ScrollBarVisibility::sbvHidden);
    }
    else if (strVal.Equals(_U("Collapsed")))
    {
        return Integer::GetPosInt(ScrollBarVisibility::sbvCollapsed);
    }
    else
    {
        return Integer::GetPosInt(ScrollBarVisibility::sbvVisible);
    }
}

SBVisibilityConvert* SBVisibilityConvert::Convert = new SBVisibilityConvert();

ScrollViewer::ScrollViewer()
    : _scrollInfo(NULL)
{
    _xSize = 0;
    _ySize = 0;
    _xExtent = 0;
    _yExtent = 0;
    _flags = 0;
    _horiVisible = Visibility::Visible;
    _vertVisible = Visibility::Visible;

    _horiScroll = NULL;
    _vertScroll = NULL;

    WriteDoFlag(ViewFlags::IsClipToBoundsVF, true);
}

ScrollViewer::~ScrollViewer()
{
}

void ScrollViewer::OnVerticalOffsetPropChanged(DpObject* d, DpPropChangedEventArg* e)
{
    ScrollViewer* scrollView = DynamicCast<ScrollViewer>(d);
    if (scrollView != NULL)
    {
        scrollView->ScrollToVerticalOffset(e->GetNewValue()->ToInt());
        scrollView->RefleshLayout(false);
    }
}

void ScrollViewer::OnHorizontalOffsetPropChanged(DpObject* d, DpPropChangedEventArg* e)
{
    ScrollViewer* scrollView = RTTICast<ScrollViewer>(d);
    if (scrollView != NULL)
    {
        scrollView->ScrollToHorizontalOffset(e->GetNewValue()->ToInt());
        scrollView->RefleshLayout(false);
    }
}

void ScrollViewer::StaticInit()
{
    if (NULL == CanContentScrollProperty)
    {
        KeyboardNavigation::StaticInit();
        ContentControl::StaticInit();
        ScrollBar::StaticInit();

        ClipToBoundsProperty->OverrideMetadata(RTTIType(), DpPropMemory::GetPropMeta(Boolean::True, PropMetadataOptions::AffectsParentMeasure, &Element::OnClipToBoundsPropChanged));

        CanContentScrollProperty = DpProperty::RegisterAttached(_U("CanContentScroll"), RTTIType(), Boolean::RTTIType()
            , DpPropMemory::GetPropMeta(Boolean::True, PropMetadataOptions::AffectsArrange));
        SmoothingScrollProperty = DpProperty::Register(_U("SmoothingScroll"), RTTIType(), Boolean::RTTIType()
            , DpPropMemory::GetPropMeta(Boolean::False, PropMetadataOptions::AffectsNone));

        //ContentHorizontalOffsetProperty = DpProperty::Register(_U("ContentHorizontalOffset"), RTTIType(), Integer::RTTIType()
        //    , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));
        //ContentVerticalOffsetProperty = DpProperty::Register(_U("ContentVerticalOffset"), RTTIType(), Integer::RTTIType()
        //    , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));
        /*ExtentHeightProperty = DpProperty::Register(_U("ExtentHeight"), RTTIType(), Integer::RTTIType()
        , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));
        ExtentWidthProperty = DpProperty::Register(_U("ExtentWidth"), RTTIType(), Integer::RTTIType()
        , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));

        ScrollableWidthProperty = DpProperty::Register(_U("ScrollableWidth"), RTTIType(), OFloat::RTTIType()
        , DpPropMemory::GetPropMeta(OFloat::GetZeroFloat(), PropMetadataOptions::AffectsNone));
        ScrollableHeightProperty = DpProperty::Register(_U("ScrollableHeight"), RTTIType(), OFloat::RTTIType()
        , DpPropMemory::GetPropMeta(OFloat::GetZeroFloat(), PropMetadataOptions::AffectsNone));

        ViewportHeightProperty = DpProperty::RegisterAttached(_U("ViewportHeight"), RTTIType(), Integer::RTTIType()
        , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));
        ViewportWidthProperty = DpProperty::RegisterAttached(_U("ViewportWidth"), RTTIType(), Integer::RTTIType()
        , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange));*/

        ComputedHorizontalScrollBarVisibilityProperty = DpProperty::RegisterAttached(_U("ComputedHorizontalScrollBarVisibility"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(VisibilityBox::VisibleBox, PropMetadataOptions::AffectsArrange));
        ComputedVerticalScrollBarVisibilityProperty = DpProperty::RegisterAttached(_U("ComputedVerticalScrollBarVisibility"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(VisibilityBox::VisibleBox, PropMetadataOptions::AffectsArrange));

        HorizontalOffsetProperty = DpProperty::Register(_U("HorizontalOffset"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange, &ScrollViewer::OnHorizontalOffsetPropChanged));
        VerticalOffsetProperty = DpProperty::Register(_U("VerticalOffset"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(Integer::GetZeroInt(), PropMetadataOptions::AffectsArrange, &ScrollViewer::OnVerticalOffsetPropChanged));

        HorizontalScrollBarVisibilityProperty = DpProperty::RegisterAttached(_U("HorizontalScrollBarVisibility"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(new Integer(ScrollBarVisibility::sbvAutoScroll), PropMetadataOptions::AffectsArrange));
        VerticalScrollBarVisibilityProperty = DpProperty::RegisterAttached(_U("VerticalScrollBarVisibility"), RTTIType(), Integer::RTTIType()
            , DpPropMemory::GetPropMeta(new Integer(ScrollBarVisibility::sbvAutoScroll), PropMetadataOptions::AffectsArrange));

        HorizontalScrollBarVisibilityProperty->SetConvertValueCb(SBVisibilityConvert::Convert);
        VerticalScrollBarVisibilityProperty->SetConvertValueCb(SBVisibilityConvert::Convert);

        ComputedHorizontalScrollBarVisibilityProperty->SetConvertValueCb(VisibilityConvert::Convert);
        ComputedVerticalScrollBarVisibilityProperty->SetConvertValueCb(VisibilityConvert::Convert);

        ScrollChangedEvent = EventHelper::RegisterRoutedEvent(_U("ScrollChanged"), RoutingStrategy::Bubble, ScrollChangedEventHandler::RTTIType(), RTTIType());

        Control::IsTabStopProperty->OverrideMetadata(RTTIType(), DpPropMemory::GetPropMeta(Boolean::False));
        KeyboardNavigation::DirectionalNavigationProperty->OverrideMetadata(RTTIType(), DpPropMemory::GetPropMeta(Integer::GetPosInt(KNavMode::knLocal)));

        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToVerticalOffsetCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToHorizontalOffsetCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));

        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::LineUpCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::LineDownCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));

        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::LineLeftCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::LineRightCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));

        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToTopCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToBottomCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));

        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToLeftCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
        CommandOp::RegisterClassCommandHandler(RTTIType(),
            ScrollBar::ScrollToRightCommand, ExecutedRoutedEventHandler(ScrollViewer::OnScrollCommand));
    }
}

void ScrollViewer::OnScrollCommand(Object* target, ExecutedRoutedEventArg* e)
{
    e->SetHandled(true);

    ScrollViewer* scrollView = RTTICast<ScrollViewer>(target);

    if (e->GetCommand() == ScrollBar::ScrollToVerticalOffsetCommand)
    {
        scrollView->ScrollToVerticalOffset(e->GetParams()->ToInt());
    }
    else if (e->GetCommand() == ScrollBar::ScrollToHorizontalOffsetCommand)
    {
        scrollView->ScrollToHorizontalOffset(e->GetParams()->ToInt());
    }
    else if (e->GetCommand() == ScrollBar::ScrollToLeftCommand)
    {
        scrollView->ScrollToLeft();
    }
    else if (e->GetCommand() == ScrollBar::ScrollToRightCommand)
    {
        scrollView->ScrollToRight();
    }
    else if (e->GetCommand() == ScrollBar::ScrollToTopCommand)
    {
        scrollView->ScrollToTop();
    }
    else if (e->GetCommand() == ScrollBar::ScrollToBottomCommand)
    {
        scrollView->ScrollToBottom();
    }
    else if (e->GetCommand() == ScrollBar::LineLeftCommand)
    {
        scrollView->LineLeft();
    }
    else if (e->GetCommand() == ScrollBar::LineRightCommand)
    {
        scrollView->LineRight();
    }
    else if (e->GetCommand() == ScrollBar::LineUpCommand)
    {
        scrollView->LineUp();
    }
    else if (e->GetCommand() == ScrollBar::LineDownCommand)
    {
        scrollView->LineDown();
    }
    else
    {
        return;
    }

    scrollView->RefleshLayout(false);
}

void ScrollViewer::SetFlagValue(int flag, bool value)
{
    if (value)
    {
        _flags |= flag;
    }
    else
    {
        _flags &= ~flag;
    }
}

bool ScrollViewer::GetInMeasure() const
{
    return ((_flags & Flags::InMeasure) == Flags::InMeasure);
}

void ScrollViewer::SetInMeasure(bool val)
{
    SetFlagValue(Flags::InMeasure, val);
}

bool ScrollViewer::GetInChildInvalidateMeasure() const
{
    return ((_flags & Flags::InChildInvalidateMeasure) == Flags::InChildInvalidateMeasure);
}

void ScrollViewer::SetInChildInvalidateMeasure(bool val)
{
    SetFlagValue(Flags::InChildInvalidateMeasure, val);
}

bool ScrollViewer::GetRequestComputeMeasure() const
{
    return ((_flags & Flags::RequestComputeMeasure) == Flags::RequestComputeMeasure);
}

void ScrollViewer::SetRequestComputeMeasure(bool val)
{
    SetFlagValue(Flags::RequestComputeMeasure, val);
}

ScrollBarVisibility ScrollViewer::GetHorizontalScrollBarVisibility()
{
    return (ScrollBarVisibility)(GetValue(HorizontalScrollBarVisibilityProperty)->ToInt());
}

void ScrollViewer::SetHorizontalScrollBarVisibility(ScrollBarVisibility val)
{
    SetValue(HorizontalScrollBarVisibilityProperty, new Integer(val));
}

ScrollBarVisibility ScrollViewer::GetVerticalScrollBarVisibility()
{
    return (ScrollBarVisibility)(GetValue(VerticalScrollBarVisibilityProperty)->ToInt());
}

void ScrollViewer::SetVerticalScrollBarVisibility(ScrollBarVisibility val)
{
    SetValue(VerticalScrollBarVisibilityProperty, new Integer(val));
}

void ScrollViewer::AddScrollChanged(ScrollChangedEventHandler* ev)
{
    AddHandler(ScrollChangedEvent, ev);
}

void ScrollViewer::RemoveScrollChanged(ScrollChangedEventHandler* ev)
{
    RemoveHandler(ScrollChangedEvent, ev);
}

IScrollInfo* ScrollViewer::GetScrollInfo()
{
    return _scrollInfo;
}

void ScrollViewer::SetScrollInfo(IScrollInfo* scrollInfo)
{
    _scrollInfo = scrollInfo;
    if (NULL != _scrollInfo)
    {
        bool hDisableScroll = GetHorizontalScrollBarVisibility() == ScrollBarVisibility::sbvDisabled;
        bool vDisableScroll = GetVerticalScrollBarVisibility() == ScrollBarVisibility::sbvDisabled;
        scrollInfo->SetCanHorizontalScroll(!hDisableScroll);
        scrollInfo->SetCanVerticalScroll(!vDisableScroll);
    }
}

void ScrollViewer::SetScrollChangedDirty(bool val)
{
    if (val)
    {
        _flags |= ScrollChangedDirty;
    }
    else
    {
        _flags &= ~ScrollChangedDirty;
    }
}

bool ScrollViewer::IsScrollChangedDirty() const
{
    return (_flags & ScrollChangedDirty) == ScrollChangedDirty;
}

void ScrollViewer::RaiseScrollChanged()
{
    if (IsScrollChangedDirty())
    {
        SetScrollChangedDirty(false);

        if (NULL != _scrollInfo)
        {
            Float horz = GetHorizontalOffset();
            Float vert = GetVerticalOffset();
            Float viewX = GetViewportWidth();
            Float viewY = GetViewportHeight();
            Float extentX = GetExtentWidth();
            Float extentY = GetExtentHeight();

            ScrollChangedEventArg e(horz, vert, viewX, viewY, extentX, extentY);
            e.SetRoutedEvent(ScrollChangedEvent);
            e.SetSource(this);
            e.OnOverrideOriginalSource(this);

            OnScrollChanged(&e);
        }
    }
}

bool ScrollViewer::CanContentScroll()
{
    return GetValue(CanContentScrollProperty)->ToBool();
}

bool ScrollViewer::GetSmoothingScroll()
{
    return GetValue(SmoothingScrollProperty)->ToBool();
}

void ScrollViewer::SetSmoothingScroll(bool val)
{
    SetValue(SmoothingScrollProperty, BOOLTOBOOLEAN(val));
}

int ScrollViewer::GetScrollableHeight()
{
    return max(0, GetExtentHeight() - GetViewportHeight());
}

int ScrollViewer::GetScrollableWidth()
{
    return max(0, GetExtentWidth() - GetViewportWidth());
}

int ScrollViewer::GetViewportHeight()
{
    return _ySize;
}

int ScrollViewer::GetViewportWidth()
{
    return _xSize;
}

int ScrollViewer::GetHorizontalOffset()
{
    if (NULL == _scrollInfo)
    {
        return 0;
    }
    else
    {
        return _scrollInfo->GetComputeHorizontalOffset();
    }
}

int ScrollViewer::GetVerticalOffset()
{
    if (NULL == _scrollInfo)
    {
        return 0;
    }
    else
    {
        return _scrollInfo->GetComputeVerticalOffset();
    }
}

void ScrollViewer::SetHorizontalOffset(int val)
{
    CoerceHorizontalPos(val);
    SetValue(HorizontalOffsetProperty, new Integer(val));
}

void ScrollViewer::SetVerticalOffset(int val)
{
    CoerceVerticalPos(val);
    SetValue(VerticalOffsetProperty, new Integer(val));
}

void ScrollViewer::ScrollToHorizontalOffset(int iPos)
{
    iPos = max(0, iPos);

    if (NULL != _scrollInfo)
    {
        _scrollInfo->SetHorizontalOffset(iPos);
    }

    if (_horiScroll)
    {
        _horiScroll->SetValue(iPos);
        SetScrollChangedDirty(true);
    }
}

void ScrollViewer::ScrollToVerticalOffset(int iPos)
{
    iPos = max(0, iPos);

    if (NULL != _scrollInfo)
    {
        _scrollInfo->SetVerticalOffset(iPos);
    }

    if (_vertScroll)
    {
        _vertScroll->SetValue(iPos);
        SetScrollChangedDirty(true);
    }
}

void ScrollViewer::CoerceHorizontalPos(int& iPos)
{
    iPos = max(0, iPos);
    iPos = min(iPos, GetScrollableWidth());
}

void ScrollViewer::CoerceVerticalPos(int& iPos)
{
    iPos = max(0, iPos);
    iPos = min(iPos, GetScrollableHeight());
}

void ScrollViewer::SetHoriScrollBarVisibility(Visibility val)
{
    _horiVisible = val;
    if (_horiScroll)
    {
        _horiScroll->SetVisibility(val);
    }
}

void ScrollViewer::SetVertScrollBarVisibility(Visibility val)
{
    _vertVisible = val;
    if (_vertScroll)
    {
        _vertScroll->SetVisibility(val);
    }
}

void ScrollViewer::PageDown()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->PageDown();
    }
}

void ScrollViewer::PageLeft()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->PageLeft();
    }
}

void ScrollViewer::PageRight()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->PageRight();
    }
}

void ScrollViewer::PageUp()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->PageUp();
    }
}

void ScrollViewer::LineUp()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->LineUp();
    }
}

void ScrollViewer::LineDown()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->LineDown();
    }
}

void ScrollViewer::LineLeft()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->LineLeft();
    }
}

void ScrollViewer::LineRight()
{
    if (_scrollInfo != NULL)
    {
        _scrollInfo->LineRight();
    }
}

void ScrollViewer::ScrollToEnd(AxisDirection axis)
{
    int iHori = 0;
    int iVert = 0;

    if (NULL != _scrollInfo)
    {
        bool byAxis = (axis == AxisDirection::xyAxis || axis == AxisDirection::yAxis);
        bool bxAxis = (axis == AxisDirection::xyAxis || axis == AxisDirection::xAxis);

        for (int i = 0; i < 9; ++i)
        {
            iHori = GetExtentWidth();
            iVert = GetExtentHeight();

            if (byAxis)
            {
                ScrollToVerticalOffset(iVert);
            }

            if (bxAxis)
            {
                ScrollToHorizontalOffset(iHori);
            }

            InvalidateMeasure();
            UpdateArrange();

            if ((!bxAxis || iHori == GetExtentWidth()) && (!byAxis || iVert == GetExtentHeight()))
            {
                break;
            }
        }

        RefleshLayout(true);
    }
}

void ScrollViewer::ScrollToHome(AxisDirection axis)
{
    int iHori = 0;
    int iVert = 0;

    if (NULL != _scrollInfo)
    {
        bool byAxis = (axis == AxisDirection::xyAxis || axis == AxisDirection::yAxis);
        bool bxAxis = (axis == AxisDirection::xyAxis || axis == AxisDirection::xAxis);

        if (byAxis)
        {
            ScrollToVerticalOffset(iVert);
        }

        if (bxAxis)
        {
            ScrollToHorizontalOffset(iHori);
        }

        RefleshLayout(true);
    }
}

void ScrollViewer::ScrollToLeft()
{
    ScrollToHome(AxisDirection::xAxis);
}

void ScrollViewer::ScrollToRight()
{
    ScrollToEnd(AxisDirection::xAxis);
}

void ScrollViewer::ScrollToBottom()
{
    ScrollToEnd(AxisDirection::yAxis);
}

void ScrollViewer::ScrollToTop()
{
    ScrollToHome(AxisDirection::yAxis);
}

void ScrollViewer::RefleshLayout(bool bOnlyRender)
{
    Element* fte = RTTICast<Element>(GetTemplatedParent());

    if (fte)
    {
        PopupRoot* pPopup = RTTICast<PopupRoot>(VisualTreeOp::GetVisualRoot(this));

        if (pPopup != NULL)
        {
            fte = pPopup;
        }
    }
    else
    {
        fte = this;
    }

    static DWORD dwTime = 0;
    DWORD currTime = Environment::GetSystemTick();

    dwTime = currTime;
    if (fte)
    {
        if (bOnlyRender)
        {
            fte->InvalidateArrange();
            fte->InvalidateVisual();
        }
        else
        {
            fte->UpdateLayout();
        }
    }
}

void ScrollViewer::BindToTemplatedParent(DpProperty* property)
{
}

Size ScrollViewer::OnMeasure(const Size& constraint)
{
    IScrollInfo* scrollInfo = GetScrollInfo();
    Point offset;
    Size desiredSize;
    int iHori = 0;
    int iVert = 0;

    SetRequestComputeMeasure(false);

    desiredSize = RecalcMeasure(constraint);
    scrollInfo = GetScrollInfo();

    offset.x = max(0, _xExtent - _xSize);
    offset.y = max(0, _yExtent - _ySize);

    if (NULL != scrollInfo)
    {
        iHori = scrollInfo->GetHorizontalOffset();
        iVert = scrollInfo->GetVerticalOffset();
    }

    if (GetRequestComputeMeasure() || (offset.x < iHori || offset.y < iVert))
    {
        ScrollToHorizontalOffset(min(offset.x, scrollInfo->GetHorizontalOffset()));
        ScrollToVerticalOffset(min(offset.y, scrollInfo->GetVerticalOffset()));
        desiredSize = RecalcMeasure(constraint);
    }

    SetRequestComputeMeasure(false);

    return desiredSize;
}

Size ScrollViewer::RecalcMeasure(const Size& constraint)
{
    SetInChildInvalidateMeasure(false);

    IScrollInfo* scrollInfo = GetScrollInfo();
    Element* element = NULL;
    ScrollBarVisibility vertScrollBarVisible = GetVerticalScrollBarVisibility();
    ScrollBarVisibility horiScrollBarVisible = GetHorizontalScrollBarVisibility();

    if (GetVisualChildrenCount() > 0)
    {
        element = GetVisualChild(0);
    }

    if (element == NULL)
    {
        return Size();
    }

    SetInMeasure(true);

    element->WriteFlag(CoreFlags::IsInvalidateLocked, true);
    //_horiScroll->WriteFlag(CoreFlags::IsInvalidateLocked, true);
    //_vertScroll->WriteFlag(CoreFlags::IsInvalidateLocked, true);

    bool vertAuto = vertScrollBarVisible == ScrollBarVisibility::sbvAutoScroll;
    bool horiAuto = horiScrollBarVisible == ScrollBarVisibility::sbvAutoScroll;
    bool hDisableScroll = horiScrollBarVisible == ScrollBarVisibility::sbvDisabled;
    bool vDisableScroll = vertScrollBarVisible == ScrollBarVisibility::sbvDisabled;

    Visibility vertVisible = Visibility::Visible;
    Visibility horiVisible = Visibility::Visible;

    switch (vertScrollBarVisible)
    {
    case ScrollBarVisibility::sbvVisible:
        vertVisible = Visibility::Visible;
        break;

    case ScrollBarVisibility::sbvHidden:
        vertVisible = Visibility::Hidden;
        break;

    default:
        vertVisible = Visibility::Collapsed;
    }

    switch (horiScrollBarVisible)
    {
    case ScrollBarVisibility::sbvVisible:
        horiVisible = Visibility::Visible;
        break;

    case ScrollBarVisibility::sbvHidden:
        horiVisible = Visibility::Hidden;
        break;

    default:
        horiVisible = Visibility::Collapsed;
    }

    if (_vertVisible != vertVisible)
    {
        SetVertScrollBarVisibility(vertVisible);
    }

    if (_horiVisible != horiVisible)
    {
        SetHoriScrollBarVisibility(horiVisible);
    }

    if (scrollInfo != NULL)
    {
        scrollInfo->SetCanHorizontalScroll(!hDisableScroll);
        scrollInfo->SetCanVerticalScroll(!vDisableScroll);
    }

    MeasureChild(element, constraint);
    scrollInfo = GetScrollInfo();

    // Èç¹ûÐèÒª×Ô¶¯¼ÆËã¹ö¶¯Ìõ
    // ÐèÒªÅжÏÂß¼´óСÊÇ·ñ³¬¹ý¿ÉÊÓ·¶Î§£¬Èç¹û³¬¹ýÐèÒªÏÔʾ¹ö¶¯Ìõ
    if ((scrollInfo != NULL) && (horiAuto || vertAuto))
    {
        bool horiGreat = horiAuto && scrollInfo->GetExtentWidth() > scrollInfo->GetViewportWidth();
        bool vertGreat = vertAuto && scrollInfo->GetExtentHeight() > scrollInfo->GetViewportHeight();

        if (horiGreat && (_horiVisible != Visibility::Visible))
        {
            SetHoriScrollBarVisibility(Visibility::Visible);
        }

        if (vertGreat && (_vertVisible != Visibility::Visible))
        {
            SetVertScrollBarVisibility(Visibility::Visible);
        }

        // ¹ö¶¯ÌõÐèÒªÏÔʾ£¬ÖØмÆËã
        if (horiGreat || vertGreat)
        {
            SetInChildInvalidateMeasure(true);
            element->Measure(constraint);
        }

        // ´¹Ö±ºÍˮƽ¹ö¶¯Ìõ¶¼ÐèÒª×Ô¶¯¼ÆË㣬¶øÇÒ´¹Ö±ºÍˮƽ֮ÖÐÓÐÒ»¸ö
        // Âß¼´óС´óÓÚ¿ÉÊÓÇøÓò·¶Î§£¬ÔòÐèÒªµ÷Õû¹ö¶¯Ìõ
        if ((horiAuto && vertAuto) && (horiGreat != vertGreat))
        {
            bool recalcHori = !horiGreat && (scrollInfo->GetExtentWidth() > scrollInfo->GetViewportWidth());
            bool recalcVert = !vertGreat && (scrollInfo->GetExtentHeight() > scrollInfo->GetViewportHeight());

            if (recalcHori)
            {
                if (_horiVisible != Visibility::Visible)
                {
                    SetHoriScrollBarVisibility(Visibility::Visible);
                }
            }
            else if (recalcVert && (_vertVisible != Visibility::Visible))
            {
                SetVertScrollBarVisibility(Visibility::Visible);
            }

            if (recalcHori || recalcVert)
            {
                SetInChildInvalidateMeasure(true);
                MeasureChild(element, constraint);
            }
        }
    }

    SetInMeasure(false);
    SetInChildInvalidateMeasure(false);

    return element->GetDesiredSize();
}

void ScrollViewer::OnArrange(const Size& arrangeSize)
{
    ContentControl::OnArrange(arrangeSize);
    RaiseScrollChanged();
}

void ScrollViewer::OnApplyTemplate()
{
    ContentControl::OnApplyTemplate();

    // ´ÓÄ£°åÕÒµ½Ë®Æ½¹ö¶¯Ìõ
    _horiScroll = DynamicCast<ScrollBar>(GetTemplateChild("PART_HorizontalScrollBar"));

    if (_horiScroll != NULL)
    {
        _horiScroll->SetIsStandalone(false);
    }

    _vertScroll = DynamicCast<ScrollBar>(GetTemplateChild("PART_VerticalScrollBar"));

    if (_vertScroll != NULL)
    {
        _vertScroll->SetIsStandalone(false);
    }
}

void ScrollViewer::OnPreApplyTemplate()
{
    ContentControl::OnPreApplyTemplate();

    if (GetTemplatedParent() != NULL)
    {
        //BindToTemplatedParent(HorizontalScrollBarVisibilityProperty);
        //BindToTemplatedParent(VerticalScrollBarVisibilityProperty);
        //BindToTemplatedParent(CanContentScrollProperty);
    }
}

void ScrollViewer::OnScrollChanged(ScrollChangedEventArg* e)
{
    RaiseEvent(e);
}

void ScrollViewer::OnRequestBringIntoView(RequestBringIntoViewEventArg* e)
{
    Element* child = NULL;
    FrameworkElement* fe = NULL;

    e->SetHandled(true);

    if (GetVisualChildrenCount() > 0)
    {
        child = this->GetVisualChild(0);
        fe = (FrameworkElement*)e->GetOriginalSource();
    }
}

void ScrollViewer::ScrollToVerticalOffsetByAnimation(int iStart, int iOffset, int duration, IEasingFunction* func)
{
    ObjectPtr cacheObj = func;

    if (NULL != _scrollInfo)
    {
        if (iStart < 0)
        {
            iStart = _scrollInfo->GetComputeVerticalOffset();
        }

        if (duration < 10)
        {
            duration = 200;
        }

        int iEnd = iStart + iOffset;

        Int32Animation* intAni = NULL;

        CoerceVerticalPos(iStart);
        CoerceVerticalPos(iEnd);

        if (iEnd != iStart)
        {
            intAni = new Int32Animation(iStart, iEnd, Duration(duration), FillBehavior::fbHoldEnd);
            intAni->SetDecelerationRatio(1);
            if (func != NULL)
            {
                intAni->SetEasingFunction(func);
            }
            BeginAnimation(VerticalOffsetProperty, intAni);
        }
    }
}

void ScrollViewer::OnMouseWheel(MouseWheelEventArg* e)
{
    if (!e->IsHandled() && NULL != _scrollInfo)
    {
        int iExtentHei = _scrollInfo->GetExtentHeight();
        int iViewportHei = _scrollInfo->GetViewportHeight();
        ScrollBarVisibility vertScrollBarVisible = GetVerticalScrollBarVisibility();

        int iDuration = 500;
        int iDeta = e->GetDelta() * -1 / WHEEL_DELTA;

        if (ScrollBarVisibility::sbvDisabled != vertScrollBarVisible && iExtentHei > iViewportHei)
        {
            if (iDeta > 0)
            {
                if (GetSmoothingScroll())
                {
                    ScrollToVerticalOffsetByAnimation(-1, GetViewportHeight() * 0.8, iDuration, NULL);
                }
                else
                {
                    _scrollInfo->MouseWheelDown();
                }
            }
            else
            {
                if (GetSmoothingScroll())
                {
                    ScrollToVerticalOffsetByAnimation(-1, GetViewportHeight() * -0.8, iDuration, NULL);
                }
                else
                {
                    _scrollInfo->MouseWheelUp();
                }
            }

            UpdateLayout();
            e->SetHandled(true);
        }
    }
}

void ScrollViewer::DoLayoutUpdated(Object* sender, EventArg* e)
{
}

void ScrollViewer::InvalidateScrollInfo(bool bRaised)
{
    bool _needRaised = false;
    IScrollInfo* scrollInfo = GetScrollInfo();

    if (NULL != scrollInfo)
    {
        if (_xSize != scrollInfo->GetViewportWidth() || _xExtent != scrollInfo->GetExtentWidth())
        {
            _xSize = scrollInfo->GetViewportWidth();
            _xExtent = scrollInfo->GetExtentWidth();

            if (_horiScroll)
            {
                _horiScroll->SetViewportSize(GetViewportWidth());
                _horiScroll->SetMaximum(GetScrollableWidth());
            }

            _needRaised = true;
        }

        if (_ySize != scrollInfo->GetViewportHeight() || _yExtent != scrollInfo->GetExtentHeight())
        {
            _ySize = scrollInfo->GetViewportHeight();
            _yExtent = scrollInfo->GetExtentHeight();

            if (_vertScroll)
            {
                _vertScroll->SetViewportSize(GetViewportHeight());
                _vertScroll->SetMaximum(GetScrollableHeight());
            }

            _needRaised = true;
        }

        if (bRaised)
        {
            SetScrollChangedDirty(true);
            RaiseScrollChanged();
        }

        //SetScrollChangedDirty(true);
    }
}

}


text:
<?php
error_reporting(0);
?>

<?php

    $host = 'localhost';
    $dbname='forum';
    $username = 'root';
    $password = '';

    $db = new mysqli($host, $username, $password,$dbname);
    if (mysqli_connect_errno()) {
		//echo 'Warning: Database Error.';
		//echo mysql_errno($db) . ": " . mysql_error($db) . "\n";
        include('database_error.php');
        exit();
    }
   // else echo 'Connect was successful';
?>

redpajama_set_name: RedPajamaGithub


text:
package me.mattem.formation.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FormationInclude {

	/**
	 * The name for this Object to be used by Formation.
	 * If left blank, then the Class name is used
	 */
	String name() default "";

	/**
	 * If inherit is set to {@code true}, then the class hierarchy is searched for suitable methods
	 * (only ignoring those on {@code Object.class}).
	 *
	 * When {@code false}, only the annotated object is considered.
	 */
	boolean inherit() default true;

	/**
	 * A list of type categories that are used when a Formation Type annotation is on a abstract or interface setter.
	 */
	String[] typeCategories() default {};

}


text:
require 'spec_helper'

module Thredded
  describe PrivatePostsController do
    routes { Thredded::Engine.routes }

    let(:user) { create(:user) }
    let(:private_topic) { create(:private_topic, users: [user, other_user]) }
    let(:private_post) { create(:private_post, postable: private_topic) }
    let(:other_user) { create(:user) }

    before do
      allow(controller).to receive_messages(the_current_user: user)
    end

    describe 'POST mark_as_read' do
      subject(:do_post_request) { post :mark_as_read, params: { id: private_post.id } }

      it 'marks as read' do
        expect(UserPrivateTopicReadState).to receive(:touch!).with(user.id, private_post)
        do_post_request
      end

      context 'json format' do
        subject(:do_post_request) do
          post :mark_as_read, params: { id: private_post.id, format: :json }
        end

        it 'returns changed status' do
          expect(UserPrivateTopicReadState).to receive(:touch!).with(user.id, private_post)
          do_post_request
          expect(JSON.parse(response.body)).to include('read' => true)
        end
      end
    end

    describe 'POST mark_as_unread' do
      subject(:do_post_request) do
        post :mark_as_unread, params: { id: private_post.id }
      end

      it 'marks as unread' do
        UserPrivateTopicReadState.touch!(user.id, private_post)
        expect { do_post_request }.to change(UserPrivateTopicReadState, :count).by(-1)
      end

      context 'json format' do
        subject(:do_post_request) do
          post :mark_as_unread, params: { id: private_post.id, format: :json }
        end

        it 'returns changed status' do
          do_post_request
          expect(JSON.parse(response.body)).to include('read' => false)
        end
      end
    end
  end
end


text:
    <title>voxel share</title>
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />
    <link rel="stylesheet" href="style.css">

Press Ctrl + S to take a snapshot. Then upload and post to twitter.

grass

dirt

obsidian

plank


text:
from rest_framework import viewsets

from lims.permissions.permissions import IsInAdminGroupOrRO
from lims.shared.mixins import AuditTrailViewMixin

from .models import FileTemplate
from .serializers import FileTemplateSerializer

class FileTemplateViewSet(AuditTrailViewMixin, viewsets.ModelViewSet):
    queryset = FileTemplate.objects.all()
    serializer_class = FileTemplateSerializer
    filter_fields = ('name', 'file_for',)
    permission_classes = (IsInAdminGroupOrRO,)


text:
'use strict';
exports.socketsCreated = 0;


text:
import sys
import re

import numpy as np
from scipy.sparse import csr_matrix, lil_matrix
from sklearn.utils.testing import (assert_almost_equal, assert_array_equal,
                                   assert_true)

from sklearn.datasets import load_digits
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.neural_network import BernoulliRBM
from sklearn.utils.validation import assert_all_finite

np.seterr(all='warn')

Xdigits = load_digits().data
Xdigits -= Xdigits.min()
Xdigits /= Xdigits.max()

def test_fit():
    X = Xdigits.copy()

    rbm = BernoulliRBM(n_components=64, learning_rate=0.1,
                       batch_size=10, n_iter=7, random_state=9)
    rbm.fit(X)

    assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0)

    # in-place tricks shouldn't have modified X
    assert_array_equal(X, Xdigits)

def test_transform():
    X = Xdigits[:100]
    rbm1 = BernoulliRBM(n_components=16, batch_size=5,
                        n_iter=5, random_state=42)
    rbm1.fit(X)

    Xt1 = rbm1.transform(X)
    Xt2 = rbm1._mean_hiddens(X)

    assert_array_equal(Xt1, Xt2)

def test_small_sparse():
    """BernoulliRBM should work on small sparse matrices."""
    X = csr_matrix(Xdigits[:4])
    BernoulliRBM().fit(X)       # no exception

def test_sample_hiddens():
    rng = np.random.RandomState(0)
    X = Xdigits[:100]
    rbm1 = BernoulliRBM(n_components=2, batch_size=5,
                        n_iter=5, random_state=42)
    rbm1.fit(X)

    h = rbm1._mean_hiddens(X[0])
    hs = np.mean([rbm1._sample_hiddens(X[0], rng) for i in range(100)], 0)

    assert_almost_equal(h, hs, decimal=1)

def test_fit_gibbs():
    """
    Gibbs on the RBM hidden layer should be able to recreate [[0], [1]]
    from the same input
    """
    rng = np.random.RandomState(42)
    X = np.array([[0.], [1.]])
    rbm1 = BernoulliRBM(n_components=2, batch_size=2,
                        n_iter=42, random_state=rng)
                        # you need that much iters
    rbm1.fit(X)
    assert_almost_equal(rbm1.components_,
                        np.array([[0.02649814], [0.02009084]]), decimal=4)
    assert_almost_equal(rbm1.gibbs(X), X)
    return rbm1

def test_fit_gibbs_sparse():
    """
    Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] from
    the same input even when the input is sparse, and test against non-sparse
    """
    rbm1 = test_fit_gibbs()
    rng = np.random.RandomState(42)
    from scipy.sparse import csc_matrix
    X = csc_matrix([[0.], [1.]])
    rbm2 = BernoulliRBM(n_components=2, batch_size=2,
                        n_iter=42, random_state=rng)
    rbm2.fit(X)
    assert_almost_equal(rbm2.components_,
                        np.array([[0.02649814], [0.02009084]]), decimal=4)
    assert_almost_equal(rbm2.gibbs(X), X.toarray())
    assert_almost_equal(rbm1.components_, rbm2.components_)

def test_gibbs_smoke():
    """ just seek if we don't get NaNs sampling the full digits dataset """
    rng = np.random.RandomState(42)
    X = Xdigits
    rbm1 = BernoulliRBM(n_components=42, batch_size=10,
                        n_iter=20, random_state=rng)
    rbm1.fit(X)
    X_sampled = rbm1.gibbs(X)
    assert_all_finite(X_sampled)

def test_score_samples():
    """Test score_samples (pseudo-likelihood) method."""
    # Assert that pseudo-likelihood is computed without clipping.
    # http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression
    rng = np.random.RandomState(42)
    X = np.vstack([np.zeros(1000), np.ones(1000)])
    rbm1 = BernoulliRBM(n_components=10, batch_size=2,
                        n_iter=10, random_state=rng)
    rbm1.fit(X)
    assert_true((rbm1.score_samples(X) < -300).all())

    # Sparse vs. dense should not affect the output. Also test sparse input
    # validation.
    rbm1.random_state = 42
    d_score = rbm1.score_samples(X)
    rbm1.random_state = 42
    s_score = rbm1.score_samples(lil_matrix(X))
    assert_almost_equal(d_score, s_score)

def test_rbm_verbose():
    rbm = BernoulliRBM(n_iter=2, verbose=10)
    old_stdout = sys.stdout
    sys.stdout = StringIO()
    try:
        rbm.fit(Xdigits)
    finally:
        sys.stdout = old_stdout

def test_sparse_and_verbose():
    """
    Make sure RBM works with sparse input when verbose=True
    """
    old_stdout = sys.stdout
    sys.stdout = StringIO()
    from scipy.sparse import csc_matrix
    X = csc_matrix([[0.], [1.]])
    rbm = BernoulliRBM(n_components=2, batch_size=2, n_iter=1,
                       random_state=42, verbose=True)
    try:
        rbm.fit(X)
        s = sys.stdout.getvalue()
        # make sure output is sound
        assert_true(re.match(r"\[BernoulliRBM\] Iteration 1,"
                             r" pseudo-likelihood = -?(\d)+(\.\d+)?,"
                             r" time = (\d|\.)+s",
                             s))
    finally:
        sio = sys.stdout
        sys.stdout = old_stdout


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pertusaria subviridis var. albescens Erichsen

### Remarks
null


text:
<?php
/**
 * Doydoy
 *
 * @brief	Remplacement du Zend_View_Helper_FormRadio pour pouvoir mettre ou non
 * 				un Label et si oui, mieux le gérer que celui d'origine
 *
 *
 * @category   Doydoy
 * @package    Doydoy/View
 * @subpackage Helper
 *
 * @extends    Zend_View_Helper_FormElement
 *
 * @author    Doydoy
 * @version   1.0
 *
 * @example $langues = new Zend_Form_Element_Radio('langue', array('escape' => false));
 *					$langues->setSeparator('')
 *									->setAttrib('class', 'radio')
 *									/////////////////////////////////////////////////
 *									//->setAttrib('label_placement', 'prepend')												// On le label après le radioset
 *									//->setAttrib('label_placement', 'append')												// On le label avant le radioset
 *									//->setAttrib('label_tag', false)																	// On ne veut pas de label
 *									/////////////////////////////////////////////////
 *									->setDecorators(array('ViewHelper',
 *																				 array(array('td' => 'HtmlTag'),
 *																						   array('tag'=> 'div', 'id' => 'radiolanguebutton')
 *																							),
 *																				)
 *																)
 *									->addDecorators($decorators)
 *									/////////////////////////////////////////////////
 *									// Rajout d'un décorateur pour corriger le bug Zend sur les bouton radio
 *									->addDecorators(array(
 *																				array('ViewHelper',
 *																							array('helper' => 'formRadioDoydoy')		//Indication qu'on prend l'aide Doydoy_Helper_FormRadioDoydoy
 *																							),
 *																				)
 *																)
 *									/////////////////////////////////////////////////
 *								->removeDecorator('Errors');
 *
 */

/**
 * Abstract class for extension
 */
require_once 'Zend/View/Helper/FormElement.php';

class Doydoy_View_Helper_FormRadioDoydoy extends Zend_View_Helper_FormElement
{
    /**
     * Input type to use
     * @var string
     */
    protected $_inputType = 'radio';

    /**
     * Whether or not this element represents an array collection by default
     * @var bool
     */
    protected $_isArray = false;

    /**
     * Generates a set of radio button elements.
     *
     * @access public
     *
     * @param string|array $name If a string, the element name.  If an
     * array, all other parameters are ignored, and the array elements
     * are extracted in place of added parameters.
     *
     * @param mixed $value The radio value to mark as 'checked'.
     *
     * @param array $options An array of key-value pairs where the array
     * key is the radio value, and the array value is the radio text.
     *
     * @param array|string $attribs Attributes added to each radio.
     *
     * @return string The radio buttons XHTML.
     */
    public function formRadioDoydoy($name, $value = null, $attribs = null,
        $options = null, $listsep = "
\n")
    {

        $info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
        extract($info); // name, value, attribs, options, listsep, disable

        // retrieve attributes for labels (prefixed with 'label_' or 'label')
        $label_attribs = array();
        foreach ($attribs as $key => $val) {
            $tmp    = false;
            $keyLen = strlen($key);
            if ((6 < $keyLen) && (substr($key, 0, 6) == 'label_')) {
                $tmp = substr($key, 6);
            } elseif ((5 < $keyLen) && (substr($key, 0, 5) == 'label')) {
                $tmp = substr($key, 5);
            }

            if ($tmp) {
                // make sure first char is lowercase
                $tmp[0] = strtolower($tmp[0]);
                $label_attribs[$tmp] = $val;
                unset($attribs[$key]);
            }
        }

        $labelPlacement = 'append';
        $labelTag				= true;

        foreach ($label_attribs as $key => $val) {
            switch (strtolower($key)) {
                case 'placement':
                    unset($label_attribs[$key]);
                    $val = strtolower($val);
                    if (in_array($val, array('prepend', 'append'))) {
                        $labelPlacement = $val;
                    }
                    break;
                case 'tag':
                    unset($label_attribs[$key]);
                    if (is_bool($val)) {
                        $labelTag = $val;
                    }
                    break;
            }
        }

        // the radio button values and labels
        $options = (array) $options;

        // build the element
        $xhtml = '';
        $list  = array();

        // should the name affect an array collection?
        $name = $this->view->escape($name);
        if ($this->_isArray && ('[]' != substr($name, -2))) {
            $name .= '[]';
        }

        // ensure value is an array to allow matching multiple times
        $value = (array) $value;

        // XHTML or HTML end tag?
        $endTag = ' />';
        if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
            $endTag= '>';
        }

        // add radio buttons to the list.
        require_once 'Zend/Filter/Alnum.php';
        $filter = new Zend_Filter_Alnum();
        foreach ($options as $opt_value => $opt_label) {

            // Should the label be escaped?
            if ($escape) {
                $opt_label = $this->view->escape($opt_label);
            }

            // is it disabled?
            $disabled = '';
            if (true === $disable) {
                $disabled = ' disabled="disabled"';
            } elseif (is_array($disable) && in_array($opt_value, $disable)) {
                $disabled = ' disabled="disabled"';
            }

            // is it checked?
            $checked = '';
            if (in_array($opt_value, $value)) {
                $checked = ' checked="checked"';
            }

            // generate ID
            $optId = $id . '-' . $filter->filter($opt_value);

            // Wrap the radios in labels
            $label = '';
            if ($labelTag)
            	$label = '_htmlAttribs($label_attribs) . ' for="' . $optId . '">';
              $label .= $opt_label;
            if ($labelTag)
            	$label .= '';

            // Create the radio button
            $radio = '<input type="' . $this->_inputType . '"'
                    . ' name="' . $name . '"'
                    . ' id="' . $optId . '"'
                    . ' value="' . $this->view->escape($opt_value) . '"'
                    . $checked
                    . $disabled
                    . $this->_htmlAttribs($attribs)
                    . $endTag;

            // Combine the label and the radio button
            if ('prepend' == $labelPlacement) {
                $radio = $label . $radio;
            } else {
                $radio = $radio . $label;
            }
            // add to the array of radio buttons
            $list[] = $radio;
        }

        // done!
        $xhtml .= implode($listsep, $list);

        return $xhtml;
    }
}


text:
Ext.define("Tiegan.view.ViewportArticle", {
    extend: "Ext.container.Viewport",
    layout: "fit",
    style: 'background-color: white;',
    items: {
        xtype: "articlelist"
    }
});

//end file


text:
Django Metrics Dashboard Pypispy Users
======================================

A widget for the django-metrics-dashboard that displays the user count of
pypispy.com

Installation
------------

To get the latest stable release from PyPi::

    $ pip install md-pypispy-users

To get the latest commit from GitHub::

    $ pip install -e git://github.com/bitmazk/md-pypispy-users.git#egg=md_pypispy_users

Add the app to your ``INSTALLED_APPS``::

    INSTALLED_APPS = [
        ...
        'md_pypispy_users',
    ]

Run the south migrations to create the app's database tables::

    $ ./manage.py migrate md_pypispy_users

Contribute
----------

If you want to contribute to this project, please perform the following steps::

    # Fork this repository
    # Clone your fork
    $ mkvirtualenv -p python2.7 md-pypispy-users
    $ pip install -r requirements.txt

    $ git co -b feature_branch master
    # Implement your feature and tests
    $ git add . && git commit
    $ git push -u origin feature_branch
    # Send us a pull request for your feature branch

Testing
-------

If you want to contribute to this project you can run the tests without setting
up a Django project. Just clone this repository and execute the
``runtests.py``::

    $ ./md_pypispy_users/tests/runtests.py

Sometimes a new feature needs new South migrations, in this case you should
do the following::

    $ rm db.sqlite
    $ ./manage.py syncdb --migrate
    $ ./manage.py schemamigration md_pypispy_users --auto

Discuss
-------

If you have questions or issues, please open an issue on GitHub.

If we don't react quickly, please don't hesitate to ping me on Twitter
(`@mbrochh <https://twitter.com/mbrochh>`_)


text:
(function() {
  function addURLLink(event) {
    var contentDoc=event.target;

    var contentWin=contentDoc.defaultView;
    if(contentDoc.documentURI.match(/^about:neterror/) && contentWin == contentWin.top){
      var errorPageContainer = contentDoc.getElementById('errorPageContainer');
      var errorPageBody = contentDoc.body;

      // Add 'Go To Homepage' button
      var btnChildren = contentDoc.querySelector('#errorPageContainer > button');
      if (btnChildren && btnChildren.style.display !== 'none') {
        var goToHomePageBtn = contentDoc.createElement('button');
        goToHomePageBtn.id = 'goToHomePage';
        var stringBundle = document.getElementById('ceerrorpage-strings');
        goToHomePageBtn.textContent = stringBundle.getString('goToHomePage');
        goToHomePageBtn.addEventListener('click', function () {
          contentWin.location = 'http://e.firefoxchina.cn/?from_err_btn';
        });
        if (btnChildren) {
          errorPageContainer.insertBefore(goToHomePageBtn, btnChildren);
        } else {
          errorPageContainer.appendChild(goToHomePageBtn);
        }
      }

      // Reset the default error page css
      var domWindowUtils = contentWin.QueryInterface(Ci.nsIInterfaceRequestor).
        getInterface(Ci.nsIDOMWindowUtils);
      var cssUri = Services.io.newURI('chrome://ceerrorpage/skin/overlay.css', null, null);
      domWindowUtils.loadSheet(cssUri, Ci.nsIDOMWindowUtils.AUTHOR_SHEET);

      // Add site recomandation iframe to the default error page
      if (window.navigator.onLine) {
        var recomendIframe = contentDoc.createElement('iframe');
        recomendIframe.id = 'recomendIframe';
        recomendIframe.height = '0px';
        errorPageBody.appendChild(recomendIframe);
        recomendIframe.src = 'http://newtab.firefoxchina.cn/error-tab-rec.html';
        recomendIframe.addEventListener('load', function(){
          if (recomendIframe.contentWindow.document.URL.match(/^about:neterror/)) {
            errorPageBody.removeChild(recomendIframe);
          } else {
            recomendIframe.height = '330px';
          }
        }, false);
        var timer = 0;
        var interval = setInterval(function(){
          if(timer < 150 && recomendIframe.contentDocument) {
            if(recomendIframe.contentDocument.readyState == 'complete' || recomendIframe.contentDocument.readyState == 'interactive') {
              if (recomendIframe.contentWindow.document.URL.match(/^about:neterror/)) {
                errorPageBody.removeChild(recomendIframe);
              } else {
                recomendIframe.height = '330px';
              }
              timer = 0;
              clearInterval(interval);
            } else {
              timer++;
            }
          } else {
            timer = 0;
            clearInterval(interval);
          }
        }, 200);
      }
    }
  }

  window.addEventListener('load', function() {
    window.setTimeout(function() {
      document.getElementById('appcontent').addEventListener('DOMContentLoaded', addURLLink, false);
    }, 1000);
  }, false);
})();


text:
{% extends "master.html" %}

{% set active_page = "configs" %}

{% set run = runlist.getRun(runId) %}

{% block moresidebar %}

 Config Summary

Config Details

{% endblock %}

{% block content %}

OpSim Configuration Summary

<object width=600px height=700px type="text/plain" data="{{ run.configSummary }}" border="0" >
</object>

OpSim Configuration Details

<object width=600px height=700px type="text/plain" data="{{ run.configDetails }}" border="0" >
</object>

{% endblock %}


text:
module.exports = function(RED) {
    "use strict";
    var nodemailer = require("nodemailer");
    var Imap = require('imap');

    //console.log(nodemailer.Transport.transports.SMTP.wellKnownHosts);

    try {
        var globalkeys = RED.settings.email || require(process.env.NODE_RED_HOME+"/../emailkeys.js");
    } catch(err) {
    }

    function EmailNode(n) {
        RED.nodes.createNode(this,n);
        this.topic = n.topic;
        this.name = n.name;
        this.outserver = n.server;
        this.outport = n.port;
        var flag = false;
        if (this.credentials && this.credentials.hasOwnProperty("userid")) {
            this.userid = this.credentials.userid;
        } else {
            if (globalkeys) {
                this.userid = globalkeys.user;
                flag = true;
            } else {
                this.error("No e-mail userid set");
            }
        }
        if (this.credentials && this.credentials.hasOwnProperty("password")) {
            this.password = this.credentials.password;
        } else {
            if (globalkeys) {
                this.password = globalkeys.pass;
                flag = true;
            } else {
                this.error("No e-mail password set");
            }
        }
        if (flag) {
            RED.nodes.addCredentials(n.id,{userid:this.userid, password:this.password, global:true});
        }
        var node = this;

        var smtpTransport = nodemailer.createTransport({
            host: node.outserver,
            port: node.outport,
            secure: true,
            auth: {
                user: node.userid,
                pass: node.password
            }
        });

        this.on("input", function(msg) {
            if (smtpTransport) {
                node.status({fill:"blue",shape:"dot",text:"sending"});
                var payload = RED.util.ensureString(msg.payload);
                if (msg.to && node.name) {
                    node.warn("Deprecated: msg properties should not override set node properties. See bit.ly/nr-override-msg-props");
                }
                smtpTransport.sendMail({
                    from: node.userid, // sender address
                    to: msg.to || node.name, // comma separated list of addressees
                    subject: msg.topic, // subject line
                    text: payload // plaintext body
                }, function(error, info) {
                    if (error) {
                        node.error(error);
                        node.status({fill:"red",shape:"ring",text:"send failed"});
                    } else {
                        node.log("Message sent: " + info.response);
                        node.status({});
                    }
                });
            }
            else { node.warn("No Email credentials found. See info panel."); }
        });
    }
    RED.nodes.registerType("e-mail",EmailNode,{
        credentials: {
            userid: {type:"text"},
            password: {type: "password"},
            global: { type:"boolean"}
        }
    });

    function EmailInNode(n) {
        RED.nodes.createNode(this,n);
        this.name = n.name;
        this.repeat = n.repeat * 1000 || 300000;
        this.inserver = n.server || globalkeys.server || "imap.gmail.com";
        this.inport = n.port || globalkeys.port || "993";
        var flag = false;

        if (this.credentials && this.credentials.hasOwnProperty("userid")) {
            this.userid = this.credentials.userid;
        } else {
            if (globalkeys) {
                this.userid = globalkeys.user;
                flag = true;
            } else {
                this.error("No e-mail userid set");
            }
        }
        if (this.credentials && this.credentials.hasOwnProperty("password")) {
            this.password = this.credentials.password;
        } else {
            if (globalkeys) {
                this.password = globalkeys.pass;
                flag = true;
            } else {
                this.error("No e-mail password set");
            }
        }
        if (flag) {
            RED.nodes.addCredentials(n.id,{userid:this.userid, password:this.password, global:true});
        }

        var node = this;
        this.interval_id = null;
        var oldmail = {};

        var imap = new Imap({
            user: node.userid,
            password: node.password,
            host: node.inserver,
            port: node.inport,
            tls: true,
            tlsOptions: { rejectUnauthorized: false },
            connTimeout: node.repeat,
            authTimeout: node.repeat
        });

        if (!isNaN(this.repeat) && this.repeat > 0) {
            node.log("repeat = "+this.repeat);
            this.interval_id = setInterval( function() {
                node.emit("input",{});
            }, this.repeat );
        }

        this.on("input", function(msg) {
            imap.once('ready', function() {
                node.status({fill:"blue",shape:"dot",text:"fetching"});
                var pay = {};
                imap.openBox('INBOX', true, function(err, box) {
                    if (box.messages.total > 0) {
                        var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM SUBJECT DATE)','TEXT'] });
                        f.on('message', function(msg, seqno) {
                            node.log('message: #'+ seqno);
                            var prefix = '(#' + seqno + ') ';
                            msg.on('body', function(stream, info) {
                                var buffer = '';
                                stream.on('data', function(chunk) {
                                    buffer += chunk.toString('utf8');
                                });
                                stream.on('end', function() {
                                    if (info.which !== 'TEXT') {
                                        pay.from = Imap.parseHeader(buffer).from[0];
                                        pay.topic = Imap.parseHeader(buffer).subject[0];
                                        pay.date = Imap.parseHeader(buffer).date[0];
                                    } else {
                                        var parts = buffer.split("Content-Type");
                                        for (var p = 0; p < parts.length; p++) {
                                            if (parts[p].indexOf("text/plain") >= 0) {
                                                pay.payload = parts[p].split("\n").slice(1,-2).join("\n").trim();
                                            }
                                            if (parts[p].indexOf("text/html") >= 0) {
                                                pay.html = parts[p].split("\n").slice(1,-2).join("\n").trim();
                                            }
                                        }
                                        //pay.body = buffer;
                                    }
                                });
                            });
                            msg.on('end', function() {
                                //node.log('Finished: '+prefix);
                            });
                        });
                        f.on('error', function(err) {
                            node.warn('fetch error: ' + err);
                            node.status({fill:"red",shape:"ring",text:"fetch error"});
                        });
                        f.on('end', function() {
                            if (JSON.stringify(pay) !== oldmail) {
                                node.send(pay);
                                oldmail = JSON.stringify(pay);
                                node.log('received new email: '+pay.topic);
                            }
                            else { node.log('duplicate not sent: '+pay.topic); }
                            //node.status({fill:"green",shape:"dot",text:"ok"});
                            node.status({});
                            imap.end();
                        });
                    }
                    else {
                        node.log("you have achieved inbox zero");
                        //node.status({fill:"green",shape:"dot",text:"ok"});
                        node.status({});
                        imap.end();
                    }
                });
            });
            node.status({fill:"grey",shape:"dot",text:"connecting"});
            imap.connect();
        });

        imap.on('error', function(err) {
            node.log(err);
            node.status({fill:"red",shape:"ring",text:"connect error"});
        });

        this.on("error", function(err) {
            node.log("error: ",err);
        });

        this.on("close", function() {
            if (this.interval_id != null) {
                clearInterval(this.interval_id);
            }
            if (imap) { imap.destroy(); }
        });

        node.emit("input",{});
    }
    RED.nodes.registerType("e-mail in",EmailInNode,{
        credentials: {
            userid: {type:"text"},
            password: {type: "password"},
            global: { type:"boolean"}
        }
    });
};


text:
package com.audacious_software.passive_data_kit.generators.communication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.audacious_software.passive_data_kit.PassiveDataKit;
import com.audacious_software.passive_data_kit.PhoneUtililties;
import com.audacious_software.passive_data_kit.activities.generators.DataPointViewHolder;
import com.audacious_software.passive_data_kit.activities.generators.RequestPermissionActivity;
import com.audacious_software.passive_data_kit.diagnostics.DiagnosticAction;
import com.audacious_software.passive_data_kit.generators.Generator;
import com.audacious_software.passive_data_kit.generators.Generators;
import com.audacious_software.pdk.passivedatakit.R;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import androidx.core.content.ContextCompat;

import humanize.Humanize;

@SuppressWarnings("SimplifiableIfStatement")
public class TextMessages extends Generator {
    private static final String GENERATOR_IDENTIFIER = "pdk-text-messages";

    private static final String ENABLED = "com.audacious_software.passive_data_kit.generators.communication.TextMessages.ENABLED";
    private static final boolean ENABLED_DEFAULT = true;

    private static final String DATA_RETENTION_PERIOD = "com.audacious_software.passive_data_kit.generators.communication.TextMessages.DATA_RETENTION_PERIOD";
    private static final long DATA_RETENTION_PERIOD_DEFAULT = (60L * 24L * 60L * 60L * 1000L);

    private static final Uri SMS_INBOX_URI = Uri.parse("content://sms/inbox");
    private static final Uri SMS_SENT_URI = Uri.parse("content://sms/sent");

    private static final String SMS_DATE = "date";
    private static final String SMS_BODY = "body";
    private static final String SMS_NUMBER_NAME = "person";
    private static final String SMS_NUMBER = "address";
    private static final String SMS_LENGTH = "length";
    private static final String SMS_DIRECTION = "direction";

    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_HISTORY = "history";
    private static final String HISTORY_OBSERVED = "observed";
    private static final String HISTORY_DIRECTION = "direction";
    private static final String HISTORY_LENGTH = "length";
    private static final String HISTORY_BODY = "body";
    private static final String HISTORY_NUMBER_NAME = "number_name";
    private static final String HISTORY_NUMBER = "number";
    private static final String HISTORY_DIRECTION_INCOMING = "incoming";
    private static final String HISTORY_DIRECTION_OUTGOING = "outgoing";

    private static TextMessages sInstance = null;

    private Handler mHandler = null;
    private Context mContext = null;

    private static final String DATABASE_PATH = "pdk-text-messages.sqlite";

    private SQLiteDatabase mDatabase = null;
    private long mSampleInterval = 60000;

    @SuppressWarnings("unused")
    public static String generatorIdentifier() {
        return TextMessages.GENERATOR_IDENTIFIER;
    }

    @SuppressWarnings("WeakerAccess")
    public static TextMessages getInstance(Context context) {
        if (TextMessages.sInstance == null) {
            TextMessages.sInstance = new TextMessages(context.getApplicationContext());
        }

        return TextMessages.sInstance;
    }

    @SuppressWarnings("WeakerAccess")
    public TextMessages(Context context) {
        super(context);

        this.mContext = context.getApplicationContext();
    }

    @SuppressWarnings("unused")
    public static void start(final Context context) {
        TextMessages.getInstance(context).startGenerator();
    }

    @SuppressLint("ObsoleteSdkInt")
    private void startGenerator() {
        final TextMessages me = this;

        if (this.mHandler != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                this.mHandler.getLooper().quitSafely();
            } else {
                this.mHandler.getLooper().quit();
            }

            this.mHandler = null;
        }

        final Runnable checkLogs = new Runnable() {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void run() {
                boolean approved = false;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(me.mContext, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED){
                        approved = true;
                    }
                } else {
                    approved = true;
                }

                if (approved) {
                    long lastObserved = 0;

                    Cursor lastCursor = me.mDatabase.query(TextMessages.TABLE_HISTORY, null, null, null, null, null, TextMessages.HISTORY_OBSERVED + " DESC");

                    if (lastCursor.moveToNext()) {
                        lastObserved = lastCursor.getLong(lastCursor.getColumnIndex(TextMessages.HISTORY_OBSERVED));
                    }

                    lastCursor.close();

                    ArrayList<ContentValues> toTransmit = new ArrayList<>();

                    String where = TextMessages.SMS_DATE + " > ?";
                    String[] args = {"" + lastObserved};

                    Cursor c = me.mContext.getContentResolver().query(TextMessages.SMS_INBOX_URI, null, where, args, TextMessages.SMS_DATE);

                    while (c.moveToNext()) {
                        ContentValues values = new ContentValues();
                        values.put(TextMessages.HISTORY_OBSERVED, c.getLong(c.getColumnIndex(TextMessages.SMS_DATE)));

                        String body = c.getString(c.getColumnIndex(TextMessages.SMS_BODY));

                        values.put(TextMessages.HISTORY_LENGTH, body.length());
                        values.put(TextMessages.HISTORY_BODY, body);

                        String name = c.getString(c.getColumnIndex(TextMessages.SMS_NUMBER_NAME));
                        String number = c.getString(c.getColumnIndex(TextMessages.SMS_NUMBER));

                        if (name == null) {
                            name = number;
                        }

                        values.put(TextMessages.HISTORY_NUMBER_NAME, name);
                        values.put(TextMessages.HISTORY_NUMBER, number);

                        values.put(TextMessages.HISTORY_DIRECTION, TextMessages.HISTORY_DIRECTION_INCOMING);

                        toTransmit.add(values);
                    }

                    c.close();

                    c = me.mContext.getContentResolver().query(TextMessages.SMS_SENT_URI, null, where, args, TextMessages.SMS_DATE);

                    while (c.moveToNext()) {
                        ContentValues values = new ContentValues();
                        values.put(TextMessages.HISTORY_OBSERVED, c.getLong(c.getColumnIndex(TextMessages.SMS_DATE)));

                        String body = c.getString(c.getColumnIndex(TextMessages.SMS_BODY));

                        values.put(TextMessages.HISTORY_LENGTH, body.length());
                        values.put(TextMessages.HISTORY_BODY, body);

                        String name = c.getString(c.getColumnIndex(TextMessages.SMS_NUMBER_NAME));
                        String number = c.getString(c.getColumnIndex(TextMessages.SMS_NUMBER));

                        if (name == null) {
                            name = number;
                        }

                        values.put(TextMessages.HISTORY_NUMBER_NAME, name);
                        values.put(TextMessages.HISTORY_NUMBER, number);

                        values.put(TextMessages.HISTORY_DIRECTION, TextMessages.HISTORY_DIRECTION_OUTGOING);

                        toTransmit.add(values);
                    }

                    c.close();

                    Collections.sort(toTransmit, new Comparator<ContentValues>() {
                        @Override
                        public int compare(ContentValues one, ContentValues two) {
                            Long oneTime = one.getAsLong(TextMessages.HISTORY_OBSERVED);
                            Long twoTime = two.getAsLong(TextMessages.HISTORY_OBSERVED);

                            return oneTime.compareTo(twoTime);
                        }
                    });

                    for (ContentValues values : toTransmit) {
                        String[] sensitiveFields = {
                                TextMessages.HISTORY_NUMBER_NAME,
                                TextMessages.HISTORY_NUMBER,
                                TextMessages.HISTORY_BODY,
                        };

                        for (String field : sensitiveFields) {
                            if (values.containsKey(field)) {
                                String value = values.getAsString(field);

                                if (field.equals(TextMessages.HISTORY_NUMBER)) {
                                    value = PhoneUtililties.normalizedPhoneNumber(value);
                                }

                                try {
                                    values.put(field, new String(Hex.encodeHex(DigestUtils.sha256(value))));
                                } catch (NullPointerException ex) {
                                    values.put(field, "null");
                                }
                            }
                        }

                        Bundle bundle = new Bundle();
                        bundle.putLong(TextMessages.SMS_DATE, values.getAsLong(TextMessages.HISTORY_OBSERVED));
                        bundle.putInt(TextMessages.SMS_LENGTH, values.getAsInteger(TextMessages.HISTORY_LENGTH));
                        bundle.putString(TextMessages.SMS_NUMBER_NAME, values.getAsString(TextMessages.HISTORY_NUMBER_NAME));
                        bundle.putString(TextMessages.SMS_NUMBER, values.getAsString(TextMessages.HISTORY_NUMBER));
                        bundle.putString(TextMessages.SMS_DIRECTION, values.getAsString(TextMessages.HISTORY_DIRECTION));
                        bundle.putString(TextMessages.SMS_BODY, values.getAsString(TextMessages.HISTORY_BODY));

                        me.mDatabase.insert(TextMessages.TABLE_HISTORY, null, values);

                        Generators.getInstance(me.mContext).notifyGeneratorUpdated(TextMessages.GENERATOR_IDENTIFIER, bundle);
                    }
                }

                if (me.mHandler != null) {
                    me.mHandler.postDelayed(this, me.mSampleInterval);
                }
            }
        };

        File path = PassiveDataKit.getGeneratorsStorage(this.mContext);

        path = new File(path, TextMessages.DATABASE_PATH);

        this.mDatabase = SQLiteDatabase.openOrCreateDatabase(path, null);

        int version = this.getDatabaseVersion(this.mDatabase);

        switch (version) {
            case 0:
                this.mDatabase.execSQL(this.mContext.getString(R.string.pdk_generator_text_messages_create_history_table));
        }

        if (version != TextMessages.DATABASE_VERSION) {
            this.setDatabaseVersion(this.mDatabase, TextMessages.DATABASE_VERSION);
        }

        Runnable r = new Runnable() {
            @Override
            public void run() {
                Looper.prepare();

                me.mHandler = new Handler();

                Looper.loop();
            }
        };

        Thread t = new Thread(r);
        t.start();

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        me.mHandler.post(checkLogs);

        Generators.getInstance(this.mContext).registerCustomViewClass(TextMessages.GENERATOR_IDENTIFIER, TextMessages.class);

        this.flushCachedData();
    }

    @SuppressWarnings("unused")
    public static boolean isEnabled(Context context) {
        SharedPreferences prefs = Generators.getInstance(context).getSharedPreferences(context);

        return prefs.getBoolean(TextMessages.ENABLED, TextMessages.ENABLED_DEFAULT);
    }

    @SuppressWarnings({"unused"})
    public static boolean isRunning(Context context) {
        if (TextMessages.sInstance == null) {
            return false;
        }

        return TextMessages.sInstance.mHandler != null;
    }

    @SuppressWarnings("unused")
    public static ArrayList<DiagnosticAction> diagnostics(final Context context) {
        ArrayList<DiagnosticAction> actions = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED){
                final Handler handler = new Handler(Looper.getMainLooper());

                actions.add(new DiagnosticAction(context.getString(R.string.diagnostic_sms_log_permission_required_title), context.getString(R.string.diagnostic_sms_log_permission_required), new Runnable() {

                    @Override
                    public void run() {
                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                Intent intent = new Intent(context, RequestPermissionActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.putExtra(RequestPermissionActivity.PERMISSION, Manifest.permission.READ_SMS);

                                context.startActivity(intent);
                            }
                        });
                    }
                }));
            }
        }

        return actions;
    }

    @SuppressWarnings("unused")
    public static void bindViewHolder(DataPointViewHolder holder) {
       final Context context = holder.itemView.getContext();

        long lastTimestamp = 0;
        int lastLength = 0;

        long totalIncoming = 0;
        long totalOutgoing = 0;
        long total = 0;

        TextMessages generator = TextMessages.getInstance(holder.itemView.getContext());
        String lastDirection = null;

        Cursor c = generator.mDatabase.query(TextMessages.TABLE_HISTORY, null, null, null, null, null, TextMessages.HISTORY_OBSERVED + " DESC");

        while (c.moveToNext()) {
            if (lastTimestamp == 0) {
                lastTimestamp = c.getLong(c.getColumnIndex(TextMessages.HISTORY_OBSERVED));
                lastDirection = c.getString(c.getColumnIndex(TextMessages.HISTORY_DIRECTION));
                lastLength = c.getInt(c.getColumnIndex(TextMessages.HISTORY_LENGTH));
            }

            total += 1;

            String direction = c.getString(c.getColumnIndex(TextMessages.HISTORY_DIRECTION));

            if (TextMessages.HISTORY_DIRECTION_INCOMING.equals(direction)) {
                totalIncoming += 1;
            } else if (TextMessages.HISTORY_DIRECTION_OUTGOING.equals(direction)) {
                totalOutgoing += 1;
            }
        }

        c.close();

        View cardContent = holder.itemView.findViewById(R.id.card_content);
        View cardEmpty = holder.itemView.findViewById(R.id.card_empty);
        TextView dateLabel = holder.itemView.findViewById(R.id.generator_data_point_date);

        if (total > 0) {
            cardContent.setVisibility(View.VISIBLE);
            cardEmpty.setVisibility(View.GONE);

            long storage = generator.storageUsed();

            String storageDesc = context.getString(R.string.label_storage_unknown);

            if (storage >= 0) {
                storageDesc = Humanize.binaryPrefix(storage);
            }

            dateLabel.setText(context.getString(R.string.label_storage_date_card, Generator.formatTimestamp(context, lastTimestamp / 1000.0), storageDesc));

            PieChart pieChart = holder.itemView.findViewById(R.id.chart_text_messages);
            pieChart.getLegend().setEnabled(false);

            pieChart.setEntryLabelColor(android.R.color.transparent);
            pieChart.getDescription().setEnabled(false);
            pieChart.setDrawHoleEnabled(false);

            List<PieEntry> entries = new ArrayList<>();

            if (totalIncoming > 0) {
                entries.add(new PieEntry(totalIncoming, context.getString(R.string.generator_text_messages_incoming_label)));
            }

            if (totalOutgoing > 0) {
                entries.add(new PieEntry(totalOutgoing, context.getString(R.string.generator_text_messages_outgoing_label)));
            }

            PieDataSet set = new PieDataSet(entries, " ");

            int[] colors = {
                    R.color.generator_text_messages_incoming,
                    R.color.generator_text_messages_outgoing
            };

            set.setColors(colors, context);

            PieData data = new PieData(set);
            data.setValueTextSize(14);
            data.setValueTypeface(Typeface.DEFAULT_BOLD);
            data.setValueTextColor(0xffffffff);

            data.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return "" + ((Float) value).intValue();
                }
            });

            pieChart.setData(data);
            pieChart.invalidate();

            TextView latestField = holder.itemView.findViewById(R.id.field_latest_text_message);
            TextView lengthField = holder.itemView.findViewById(R.id.field_length);
            TextView directionField = holder.itemView.findViewById(R.id.field_direction);

            Date lateDate = new Date(lastTimestamp);
            String day = android.text.format.DateFormat.getMediumDateFormat(context).format(lateDate);
            String time = android.text.format.DateFormat.getTimeFormat(context).format(lateDate);

            latestField.setText(context.getString(R.string.format_full_timestamp_pdk, day, time));
            lengthField.setText(context.getResources().getQuantityString(R.plurals.generator_text_messages_length_format, lastLength, lastLength));
            directionField.setText(lastDirection);
        } else {
            cardContent.setVisibility(View.GONE);
            cardEmpty.setVisibility(View.VISIBLE);

            dateLabel.setText(R.string.label_never_pdk);
        }
    }

    @Override
    protected void flushCachedData() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);

        long retentionPeriod = prefs.getLong(TextMessages.DATA_RETENTION_PERIOD, TextMessages.DATA_RETENTION_PERIOD_DEFAULT);

        long start = System.currentTimeMillis() - retentionPeriod;

        String where = TextMessages.HISTORY_OBSERVED + " < ?";
        String[] args = { "" + start };

        this.mDatabase.delete(TextMessages.TABLE_HISTORY, where, args);
    }

    @Override
    public void setCachedDataRetentionPeriod(long period) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.mContext);
        SharedPreferences.Editor e = prefs.edit();

        e.putLong(TextMessages.DATA_RETENTION_PERIOD, period);

        e.apply();
    }

    @Override
    public List<Bundle> fetchPayloads() {
        return new ArrayList<>();
    }

    @SuppressWarnings("unused")
    public static View fetchView(ViewGroup parent)
    {
        return LayoutInflater.from(parent.getContext()).inflate(R.layout.card_generator_text_messages, parent, false);
    }

    @SuppressWarnings("unused")
    public static long latestPointGenerated(Context context) {
        long timestamp = 0;

        TextMessages me = TextMessages.getInstance(context);

        Cursor c = me.mDatabase.query(TextMessages.TABLE_HISTORY, null, null, null, null, null, TextMessages.HISTORY_OBSERVED + " DESC");

        if (c.moveToNext()) {
            timestamp = c.getLong(c.getColumnIndex(TextMessages.HISTORY_OBSERVED));
        }

        c.close();

        return timestamp;
    }

    @Override
    public String getIdentifier() {
        return TextMessages.GENERATOR_IDENTIFIER;
    }

    public long storageUsed() {
        File path = PassiveDataKit.getGeneratorsStorage(this.mContext);

        path = new File(path, TextMessages.DATABASE_PATH);

        if (path.exists()) {
            return path.length();
        }

        return -1;
    }
}


text:
<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| View Storage Paths
	|--------------------------------------------------------------------------
	|
	| Most templating systems load templates from disk. Here you may specify
	| an array of paths that should be checked for your views. Of course
	| the usual Laravel view path has already been registered for you.
	|
	*/

	'paths' => array(__DIR__.'/../views'),

	/*
	|--------------------------------------------------------------------------
	| Pagination View
	|--------------------------------------------------------------------------
	|
	| This view will be used to render the pagination link output, and can
	| be easily customized here to show any view you like. A clean view
	| compatible with Twitter's Bootstrap is given to you by default.
	|
	*/

	'pagination' => 'foundationpagination::slider-center',

);


text:
#ifndef ApplicationUI_HPP_
#define ApplicationUI_HPP_

#include <QObject>

namespace bb
{
    namespace cascades
    {
        class Application;
        class LocaleHandler;
        class DataModel;
    }
}

class QTranslator;
class FileDataListModel;

class ApplicationUI : public QObject
{
    Q_OBJECT

    Q_PROPERTY(bb::cascades::DataModel* model READ model CONSTANT)

public:
    ApplicationUI(bb::cascades::Application *app);
    virtual ~ApplicationUI();

    Q_INVOKABLE void loadLocalFiles();
    Q_INVOKABLE void loadRemoteFiles();

private slots:
    void onSystemLanguageChanged();

private:
    bb::cascades::DataModel* model() const;

    void setDir(const QString& path);
    void setDir();

    QTranslator* m_pTranslator;
    bb::cascades::LocaleHandler* m_pLocaleHandler;
    FileDataListModel* m_model;
};

#endif /* ApplicationUI_HPP_ */


text:
const { ipcRenderer } = require('electron')

window.addEventListener('pdf-loaded', function (event) {
  ipcRenderer.send('pdf-loaded', event.detail)
})


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.resources.fluent.models.ProviderInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** List of resource providers. */
@Fluent
public final class ProviderListResult {
    /*
     * An array of resource providers.
     */
    @JsonProperty(value = "value")
    private List<ProviderInner> value;

    /*
     * The URL to use for getting the next set of results.
     */
    @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY)
    private String nextLink;

    /**
     * Get the value property: An array of resource providers.
     *
     * @return the value value.
     */
    public List<ProviderInner> value() {
        return this.value;
    }

    /**
     * Set the value property: An array of resource providers.
     *
     * @param value the value value to set.
     * @return the ProviderListResult object itself.
     */
    public ProviderListResult withValue(List<ProviderInner> value) {
        this.value = value;
        return this;
    }

    /**
     * Get the nextLink property: The URL to use for getting the next set of results.
     *
     * @return the nextLink value.
     */
    public String nextLink() {
        return this.nextLink;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ARHITAC | <?php echo $title; ?></title>
    <link href="<?php echo base_url('assets/jquery-ui-1.11.4/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo base_url("assets/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo base_url('assets/css/font-awesome-4.6.3/css/font-awesome.min.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo base_url('assets/css/pageStyle.css'); ?>" rel="stylesheet" type="text/css" />

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            Toggle navigation

                        </button>
                        <a class="navbar-brand" href="<?php echo base_url(); ?>">ARHITAC

                                Registros

<a href="<?php echo base_url('empleado'); ?>">Empleados

<a href="<?php echo base_url('curso'); ?>">Cursos

<a href="<?php echo base_url('puesto'); ?>">Puestos

<a href="<?php echo base_url('departamento'); ?>">Departamentos

<a href="<?php echo base_url('institucion'); ?>">Instituciones

<a href="<?php echo base_url('edicion_curso'); ?>">Ediciones de Curso

                                <a href="<?php echo base_url('kardex'); ?>">Kardex


text:
<?php

namespace BankId\Merchant\Library;

class SamlStatus {
    /**
     * Status Success
     */
    public static $Success   = 'urn:oasis:names:tc:SAML:2.0:status:Success';
    /**
     * Status Requester
     */
    public static $Requester = 'urn:oasis:names:tc:SAML:2.0:status:Requester';
    /**
     * Status RequestDenied
     */
    public static $RequestDenied = 'urn:oasis:names:tc:SAML:2.0:status:RequestDenied';
    /**
     * Status RequestUnsupported
     */
    public static $RequestUnsupported = 'urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported';
    /**
     * Status InvalidAttrNameOrValue
     */
    public static $InvalidAttrNameOrValue = 'urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue';
    /**
     * Status MismatchWithIDx
     */
    public static $MismatchWithIDx = 'urn:nl:bvn:bankid:1.0:status:MismatchWithIDx';

    private $statusMessage;
    private $statusCodeFirstLevel;
    private $statusCodeSecondLevel;

    /**
     * Constructor used to create Saml Status objects
     */
    public function __construct($statusMessage, $statusCodeFirstLevel, $statusCodeSecondLevel) {
        $this->statusMessage = $statusMessage;
        $this->statusCodeFirstLevel = $statusCodeFirstLevel;
        $this->statusCodeSecondLevel = $statusCodeSecondLevel;
    }

    /**
     * The status message
     */
    public function getStatusMessage() {
        return $this->statusMessage;
    }

    /**
     * The status message
     */
    public function setStatusMessage($statusMessage) {
        $this->statusMessage = $statusMessage;
    }

    /**
     * The status code first level
     */
    public function getStatusCodeFirstLevel() {
        return $this->statusCodeFirstLevel;
    }

    /**
     * The status code first level
     */
    public function setStatusCodeFirstLevel($statusCodeFirstLevel) {
        $this->statusCodeFirstLevel = $statusCodeFirstLevel;
    }

    /**
     * The status code second level
     */
    public function getStatusCodeSecondLevel() {
        return $this->statusCodeSecondLevel;
    }

    /**
     * The status code second level
     */
    public function setStatusCodeSecondLevel($statusCodeSecondLevel) {
        $this->statusCodeSecondLevel = $statusCodeSecondLevel;
    }
}