text:
#include "Internal.hpp"
#include <LuminoEngine/UI/UIStyle.hpp>
#include <LuminoEngine/UI/UILayoutPanel.hpp>

namespace ln {

//==============================================================================
// UILayoutPanel2::Builder

LN_BUILDER_IMPLEMENT(UILayoutPanel2, UIElement);

UILayoutPanel2::Builder& UILayoutPanel2::Builder::children(std::initializer_list<UIElement::Builder> list)
{
	for (auto& p : list)
		detailsAs<Details>()->children.add(p);
	return *this;
}

Ref<Object> UILayoutPanel2::Builder::Details::build()
{
	auto ptr = makeObject<UILayoutPanel2>();
	for (auto& b : children)
		ptr->addChild(b.build());
	return ptr;
}

//==============================================================================
// UILayoutPanel2

UILayoutPanel2::UILayoutPanel2()
    : m_ownerItemsControl(nullptr)
{
	m_hitTestMode = detail::UIHitTestMode::InvisiblePanel;
}

void UILayoutPanel2::init()
{
    UIElement::init();
}

void UILayoutPanel2::removeChild(UIElement* child)
{
    if (LN_REQUIRE(child)) return;
    m_logicalChildren.remove(child);
    removeVisualChild(child);
}

void UILayoutPanel2::removeAllChildren()
{
    for (auto& child : m_logicalChildren) {
        removeVisualChild(child);
    }
    m_logicalChildren.clear();
}

void UILayoutPanel2::onDispose(bool explicitDisposing)
{
    removeAllChildren();
    UIElement::onDispose(explicitDisposing);
}

void UILayoutPanel2::onAddChild(UIElement* child)
{
    if (LN_REQUIRE(child)) return;
    m_logicalChildren.add(child);
    addVisualChild(child);
}

float UILayoutPanel2::getExtentWidth() const { return m_desiredSize.width; }
float UILayoutPanel2::getExtentHeight() const { return m_desiredSize.height; }
float UILayoutPanel2::getViewportWidth() const { return actualSize().width; }
float UILayoutPanel2::getViewportHeight() const { return actualSize().height; }
void UILayoutPanel2::setHorizontalOffset(float offset) { m_scrollOffset.x = offset; }
float UILayoutPanel2::getHorizontalOffset() const { return m_scrollOffset.x; }
void UILayoutPanel2::setVerticalOffset(float offset) { m_scrollOffset.y = offset; }
float UILayoutPanel2::getVerticalOffset() const { return m_scrollOffset.y; }

//==============================================================================
// UIFrameLayout2

UIFrameLayout2::UIFrameLayout2()
{
}

void UIFrameLayout2::init()
{
    UILayoutPanel2::init();
}

Size UIFrameLayout2::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
    //Size size = element->TElementBaseClass::measureOverride(constraint);

    //Size childMaxSize(0, 0);
    //for (UIElement* child : children)
    //{
    //    child->measureLayout(constraint);
    //    const Size& desiredSize = child->getDesiredSize();
    //    const Point& pos = child->getPositionInternal();

    //    childMaxSize.width = std::max(childMaxSize.width, pos.x + desiredSize.width);
    //    childMaxSize.height = std::max(childMaxSize.height, pos.y + desiredSize.height);
    //}

    //return Size::min(constraint, Size::max(size, childMaxSize));
    //return UIElement::measureOverride(constraint);
	return UIFrameLayout2::staticMeasureOverride(layoutContext, this, constraint);
}

Size UIFrameLayout2::arrangeOverride(UILayoutContext* layoutContext, const Size& finalSize)
{
#if 0
    //Thickness canvas;
    const Thickness& padding = element->getPadding();
    Point childrenOffset(padding.left, padding.top);
    Size childrenBoundSize(finalSize.width - padding.getWidth(), finalSize.height - padding.getHeight());

    for (UIElement* child : children)
    {
        const Size& desiredSize = child->getDesiredSize();
        Size size = desiredSize;

        Rect childRect(child->getPositionInternal(), size/*child->getSizeInternal()*/);
        Flags<AlignmentAnchor> anchor = child->getAnchorInternal();

        if (anchor != AlignmentAnchor::None)
        {
            const Thickness& margin = element->getMargineInternal();
            //float l = childRect.getLeft(), t = childRect.GetTop(), r = childRect.getRight(), b = childRect.getBottom();

            //if (anchor.TestFlag(AlignmentAnchor::LeftOffsets))
            //	l = margin.Left;
            //else if (anchor.TestFlag(AlignmentAnchor::LeftRatios))
            //	l = finalSize.width * margin.Left;

            //if (anchor.TestFlag(AlignmentAnchor::TopOffsets))
            //	t = margin.Top;
            //else if (anchor.TestFlag(AlignmentAnchor::TopRatios))
            //	t = finalSize.height * margin.Top;

            //if (anchor.TestFlag(AlignmentAnchor::RightOffsets))
            //	r = finalSize.width - margin.Right;
            //else if (anchor.TestFlag(AlignmentAnchor::RightRatios))
            //	r = finalSize.width - (finalSize.width * margin.Right);

            //if (anchor.TestFlag(AlignmentAnchor::BottomOffsets))
            //	b = finalSize.height - margin.Bottom;
            //else if (anchor.TestFlag(AlignmentAnchor::BottomRatios))
            //	b = finalSize.height - (finalSize.height * margin.Bottom);

            //if (anchor.TestFlag(AlignmentAnchor::HCenter))
            //	childRect.x = (finalSize.width - childRect.width) / 2;

            //if (anchor.TestFlag(AlignmentAnchor::VCenter))
            //	childRect.y = (finalSize.height - childRect.height) / 2;

            //childRect.Set(l, t, r - l, b - t);

            //child->arrangeLayout(childRect);
#if 1
            float l = NAN, t = NAN, r = NAN, b = NAN;
            if (anchor.isSet(AlignmentAnchor::LeftOffsets))
                l = margin.left;
            else if (anchor.isSet(AlignmentAnchor::LeftRatios))
                l = childrenBoundSize.width * margin.left;

            if (anchor.isSet(AlignmentAnchor::TopOffsets))
                t = margin.top;
            else if (anchor.isSet(AlignmentAnchor::TopRatios))
                t = childrenBoundSize.height * margin.top;

            if (anchor.isSet(AlignmentAnchor::RightOffsets))
                r = childrenBoundSize.width - margin.right;
            else if (anchor.isSet(AlignmentAnchor::RightRatios))
                r = childrenBoundSize.width - (childrenBoundSize.width * margin.right);

            if (anchor.isSet(AlignmentAnchor::BottomOffsets))
                b = childrenBoundSize.height - margin.bottom;
            else if (anchor.isSet(AlignmentAnchor::BottomRatios))
                b = childrenBoundSize.height - (childrenBoundSize.height * margin.bottom);

            if (anchor.isSet(AlignmentAnchor::HCenter))
                childRect.x = (childrenBoundSize.width - childRect.width) / 2;

            if (anchor.isSet(AlignmentAnchor::VCenter))
                childRect.y = (childrenBoundSize.height - childRect.height) / 2;

            if (!Math::isNaN(l) || !Math::isNaN(r))
            {
                if (!Math::isNaN(l) && Math::isNaN(r))
                {
                    childRect.x = l;
                }
                else if (Math::isNaN(l) && !Math::isNaN(r))
                {
                    childRect.x = r - childRect.width;
                }
                else
                {
                    childRect.x = l;
                    childRect.width = r - l;
                }
            }

            if (!Math::isNaN(t) || !Math::isNaN(b))
            {
                if (!Math::isNaN(t) && Math::isNaN(b))
                {
                    childRect.y = t;
                }
                else if (Math::isNaN(t) && !Math::isNaN(b))
                {
                    childRect.y = b - childRect.height;
                }
                else
                {
                    childRect.y = t;
                    childRect.height = b - t;
                }
            }

            childRect.x += childrenOffset.x;
            childRect.y += childrenOffset.y;
#endif
        }

        child->arrangeLayout(childRect);
    }
#endif

	return UIFrameLayout2::staticArrangeOverride(layoutContext, this, finalSize);
    //return finalSize;
}

Size UIFrameLayout2::staticMeasureChildrenAreaSize(UILayoutContext* layoutContext, UIElement* ownerElement, const Size& constraint)
{
    int childrenCount = ownerElement->getVisualChildrenCount();
    Size childMaxSize(0, 0);
    for (int i = 0; i < childrenCount; i++)
    {
        UIElement* child = ownerElement->getVisualChild(i);
		if (layoutContext->testLayoutEnabled(child)) {
			child->measureLayout(layoutContext, constraint);
			const Size& desiredSize = child->desiredSize();
			childMaxSize.width = std::max(childMaxSize.width, desiredSize.width);
			childMaxSize.height = std::max(childMaxSize.height, desiredSize.height);
		}
    }
    return childMaxSize;
}

Size UIFrameLayout2::staticMeasureOverride(UILayoutContext* layoutContext, UIElement* ownerElement, const Size& constraint)
{
    Size childMaxSize = staticMeasureChildrenAreaSize(layoutContext, ownerElement, constraint);

    return detail::LayoutHelper::measureElement(ownerElement, constraint, childMaxSize);

    //auto selfSize = ownerElement->UIElement::measureOverride(constraint);
    //return Size::max(selfSize, childMaxSize);

    //Size size = Size(ownerElement->width(), ownerElement->height());
    //size.width = Math::isNaN(size.width) ? 0.0 : size.width;
    //size.height = Math::isNaN(size.height) ? 0.0 : size.height;
    //return Size::min(constraint, Size::max(size, childMaxSize));
}

Size UIFrameLayout2::staticArrangeChildrenArea(UILayoutContext* layoutContext, UIElement* ownerElement, const Rect& finalArea)
{
    int childrenCount = ownerElement->getVisualChildrenCount();
    for (int i = 0; i < childrenCount; i++)
    {
        UIElement* child = ownerElement->getVisualChild(i);
		if (layoutContext->testLayoutEnabled(child)) {

			Rect slotRect;
			detail::LayoutHelper::adjustAlignment(finalArea, child->desiredSize(), ownerElement->m_finalStyle->horizontalContentAlignment, ownerElement->m_finalStyle->verticalContentAlignment, &slotRect);

			child->arrangeLayout(layoutContext, slotRect);
		}
    }
    return finalArea.getSize();
}

Size UIFrameLayout2::staticArrangeOverride(UILayoutContext* layoutContext, UIElement* ownerElement, const Size& finalSize)
{
    //const Thickness& padding = ownerElement->finalStyle()->padding;
    //Point childrenOffset(padding.left, padding.top);
    ////Size childrenBoundSize = finalSize;//(finalSize.width - padding.right, finalSize.height - padding.bottom);
    //Size childrenBoundSize(finalSize.width - padding.width(), finalSize.height - padding.height());
    //Rect bounds(childrenOffset, childrenBoundSize);
	Rect contentArea = detail::LayoutHelper::arrangeClientArea(ownerElement, finalSize);

    staticArrangeChildrenArea(layoutContext, ownerElement, contentArea);

    return finalSize;
}

//==============================================================================
// UIStackLayout2_Obsolete

Ref<UIStackLayout2_Obsolete> UIStackLayout2_Obsolete::create()
{
    return makeObject<UIStackLayout2_Obsolete>();
}

UIStackLayout2_Obsolete::UIStackLayout2_Obsolete()
    : m_orientation(Orientation::Vertical)
{
}

void UIStackLayout2_Obsolete::init()
{
    UILayoutPanel2::init();
}

void UIStackLayout2_Obsolete::addChild(UIElement* element, UILayoutLengthType type)
{
    UILayoutPanel2::addChild(element);
    CellDefinition cell;
    cell.type = type;
    m_cellDefinitions.add(cell);
}

Size UIStackLayout2_Obsolete::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
    int childCount = getVisualChildrenCount();

    // Create missing cells.
    if (m_cellDefinitions.size() < childCount) {
        m_cellDefinitions.resize(childCount);
    }

    Size size = constraint;

    if (m_orientation == Orientation::Horizontal) {
        // 横に並べる場合、幅の制限を設けない
        size.width = std::numeric_limits<float>::infinity();
    }
    else {
        // 縦に並べる場合、高さの制限を設けない
        size.height = std::numeric_limits<float>::infinity();
    }

    Size desiredSize;
    for (int i = 0; i < childCount; i++)
    {
        UIElement* child = getVisualChild(i);
        if (child->specialElementFlags().hasFlag(detail::UISpecialElementFlags::Popup)) {   // TODO: layoutcontext のメソッドで判定
            m_cellDefinitions[i].desiredSize = 0;
            continue;
        }
        child->measureLayout(layoutContext, size);

        const Size& childDesiredSize = child->getLayoutDesiredSize();
        if (isHorizontal()) {
            desiredSize.width += childDesiredSize.width;
            desiredSize.height = std::max(desiredSize.height, childDesiredSize.height);
            m_cellDefinitions[i].desiredSize = childDesiredSize.width;
        }
        else {
            desiredSize.width = std::max(desiredSize.width, childDesiredSize.width);
            desiredSize.height += childDesiredSize.height;
            m_cellDefinitions[i].desiredSize = childDesiredSize.height;
        }
    }

    return desiredSize;
}

Size UIStackLayout2_Obsolete::arrangeOverride(UILayoutContext* layoutContext, const Size& finalSize)
{
    const Thickness& padding = finalStyle()->padding;
    Size childrenBoundSize(finalSize.width - (padding.left + padding.right), finalSize.height - (padding.top + padding.bottom));

    float boundSize = 0.0f;
    if (isHorizontal())
        boundSize = childrenBoundSize.width;
    else
        boundSize = childrenBoundSize.height;

    // Fix size of 'Auto' and 'Direct', and count 'Ratio'
    float totalActualSize = 0.0f;
    float ratioCellCount = 0.0f;
    for (auto& cell : m_cellDefinitions) {
        if (cell.type == UILayoutLengthType::Ratio) {
            ratioCellCount += cell.size;
        }
        else {
            if (cell.type == UILayoutLengthType::Auto) {
                // measure で計算した desiredSize をそのまま使う
            }
            else if (cell.type == UILayoutLengthType::Direct) {
                cell.desiredSize = cell.size;
            }
            totalActualSize += cell.desiredSize;
        }
    }

    // "1*" 分のセルの領域を計算する
    float ratioUnit = (ratioCellCount != 0.0f) ? (boundSize - totalActualSize) / ratioCellCount : 0.0f;
    ratioUnit = std::max(0.0f, ratioUnit);	// 負値はダメ

    // "*" 指定である Row/Column の最終サイズを確定させ、
    // 全セルのオフセット (位置) も確定させる
    float totalOffset = 0.0f;
    for (int i = 0; i < m_cellDefinitions.size(); i++) {
        auto& cell = m_cellDefinitions[i];
        if (cell.type == UILayoutLengthType::Ratio) {
            cell.desiredSize = ratioUnit * cell.size;
        }

        cell.actualOffset = totalOffset;

        //if (i == m_cellDefinitions.size() - 1 && cell.type == UILayoutLengthType::Auto) {
        //    cell.actualSize = Math::clamp(boundSize - cell.actualOffset, cell.minSize, cell.maxSize);
        //}
        //else {
            cell.actualSize = Math::clamp(cell.desiredSize, cell.minSize, cell.maxSize);
        //}

        totalOffset += cell.actualSize;
    }

    // 子要素の最終位置・サイズを確定させる
    int childCount = getVisualChildrenCount();
    if (isHorizontal()) {
        for (int iChild = 0; iChild < childCount; iChild++) {
            auto* child = getVisualChild(iChild);
            if (child->specialElementFlags().hasFlag(detail::UISpecialElementFlags::Popup)) continue; // TODO: layoutcontext のメソッドで判定
            auto& cell = m_cellDefinitions[iChild];
            Rect childRect(cell.actualOffset, 0, cell.actualSize, finalSize.height);
            child->arrangeLayout(layoutContext, childRect);
        }
    }
    else {
        for (int iChild = 0; iChild < childCount; iChild++) {
            auto* child = getVisualChild(iChild);
            if (child->specialElementFlags().hasFlag(detail::UISpecialElementFlags::Popup)) continue; // TODO: layoutcontext のメソッドで判定
            auto& cell = m_cellDefinitions[iChild];
            Rect childRect(0, cell.actualOffset, finalSize.width, cell.actualSize);
            child->arrangeLayout(layoutContext, childRect);
        }
    }

    // 子要素のレイアウトは UIControl に任せず自分でやるので不要。そのベースを呼ぶ。
    Size selfSize = UIElement::arrangeOverride(layoutContext, finalSize);
    return selfSize;

#if 0
    float prevChildSize = 0;
    float rPos = 0;
    Rect childRect(padding.left, padding.top, 0, 0);
    int childCount = getVisualChildrenCount();
    for (int i = 0; i < childCount; i++)
    {
        UIElement* child = getVisualChild(i);
        const Size& childDesiredSize = child->getLayoutDesiredSize();

        switch (m_orientation)
        {
        case Orientation::Horizontal:
            childRect.x += prevChildSize;
            prevChildSize = childDesiredSize.width;
            childRect.width = prevChildSize;
            childRect.height = childrenBoundSize.height;
            break;
        case Orientation::Vertical:
            childRect.y += prevChildSize;
            prevChildSize = childDesiredSize.height;
            childRect.width = childrenBoundSize.width;
            childRect.height = prevChildSize;
            break;
        case Orientation::ReverseHorizontal:
            prevChildSize = childDesiredSize.width;
            rPos -= prevChildSize;
            childRect.x = childrenBoundSize.width + rPos;
            childRect.width = prevChildSize;
            childRect.height = childrenBoundSize.height;
            break;
        case Orientation::ReverseVertical:
            prevChildSize = childDesiredSize.height;
            rPos -= prevChildSize;
            childRect.y = childrenBoundSize.height + rPos;
            childRect.width = childrenBoundSize.width;
            childRect.height = prevChildSize;
            break;
        default:
            LN_UNREACHABLE();
            break;
        }

        child->arrangeLayout(childRect);
    }

    return finalSize;
#endif
}

//==============================================================================
// UIHBoxLayout2

void UIHBoxLayout2::init()
{
    UIStackLayout2_Obsolete::init();
    setOrientation(Orientation::Horizontal);
}

//==============================================================================
// UIVBoxLayout2

void UIVBoxLayout2::init()
{
    UIStackLayout2_Obsolete::init();
    setOrientation(Orientation::Vertical);
}

//==============================================================================
// UIBoxLayout3

UIBoxLayout3::UIBoxLayout3()
    : m_orientation(Orientation::Vertical)
{
}

void UIBoxLayout3::init()
{
    UILayoutPanel2::init();
}

Size UIBoxLayout3::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
    int childCount = getVisualChildrenCount();

    // Create missing cells.
    if (m_cellDefinitions.size() < childCount) {
        m_cellDefinitions.resize(childCount);
    }

    Size size = constraint;

    //if (m_orientation == Orientation::Horizontal) {
    //    // 横に並べる場合、幅の制限を設けない
    //    size.width = std::numeric_limits<float>::infinity();
    //}
    //else {
    //    // 縦に並べる場合、高さの制限を設けない
    //    size.height = std::numeric_limits<float>::infinity();
    //}

    Size desiredSize;
    for (int i = 0; i < childCount; i++)
    {
        UIElement* child = getVisualChild(i);
        child->measureLayout(layoutContext, size);

        const Size& childDesiredSize = child->getLayoutDesiredSize();
        if (isHorizontal()) {
            desiredSize.width += childDesiredSize.width;
            desiredSize.height = std::max(desiredSize.height, childDesiredSize.height);
            m_cellDefinitions[i].desiredSize = childDesiredSize.width;
        }
        else {
            desiredSize.width = std::max(desiredSize.width, childDesiredSize.width);
            desiredSize.height += childDesiredSize.height;
            m_cellDefinitions[i].desiredSize = childDesiredSize.height;
        }
    }

    return desiredSize;
}

Size UIBoxLayout3::arrangeOverride(UILayoutContext* layoutContext, const Size& finalSize)
{
    const Thickness& padding = finalStyle()->padding;
    Size childrenBoundSize(finalSize.width - (padding.left + padding.right), finalSize.height - (padding.top + padding.bottom));
    int actualCellCount = m_logicalChildren.size();

    float boundSize = 0.0f;
    if (isHorizontal())
        boundSize = childrenBoundSize.width;
    else
        boundSize = childrenBoundSize.height;

    // Fix final size of 'Auto' and 'Direct', and count 'Ratio'
    float totalActualSize = 0.0f;
    float ratioCellCount = 0.0f;
    for (int iCell = 0; iCell < actualCellCount; iCell++) {
        auto type = layoutType(iCell);
        if (type == UILayoutLengthType::Ratio) {
            ratioCellCount += layoutWeight(iCell);
        }
        else {
            if (type == UILayoutLengthType::Auto) {
                // measure で計算した desiredSize をそのまま使う
            }
            else if (type == UILayoutLengthType::Direct) {
                m_cellDefinitions[iCell].desiredSize = layoutDirectSize(iCell);
            }
            totalActualSize += m_cellDefinitions[iCell].desiredSize;
        }
    }

    // "1*" 分のセルの領域を計算する
    float ratioUnit = (ratioCellCount != 0.0f) ? (boundSize - totalActualSize) / ratioCellCount : 0.0f;
    ratioUnit = std::max(0.0f, ratioUnit);	// 負値はダメ

    // "*" 指定である Row/Column の最終サイズを確定させ、
    // 全セルのオフセット (位置) も確定させる
    float totalOffset = 0.0f;
    for (int iCell = 0; iCell < actualCellCount; iCell++) {
        auto& cell = m_cellDefinitions[iCell];
        if (layoutType(iCell) == UILayoutLengthType::Ratio) {
            cell.desiredSize = ratioUnit * layoutWeight(iCell);
        }

        float minSize, maxSize;
        getLayoutMinMaxSize(iCell, &minSize, &maxSize);

        cell.actualOffset = totalOffset;
        cell.actualSize = Math::clamp(cell.desiredSize, minSize, maxSize);
        totalOffset += cell.actualSize;
    }

    // 子要素の最終位置・サイズを確定させる
    int childCount = getVisualChildrenCount();
    if (isHorizontal()) {
        for (int iChild = 0; iChild < childCount; iChild++) {
            auto* child = getVisualChild(iChild);
            auto& cell = m_cellDefinitions[iChild];
            Rect childRect(cell.actualOffset, 0, cell.actualSize, finalSize.height);
            if (iChild == childCount - 1)  // 最終 Cell は余りサイズをすべて使う
                childRect.width = std::max(childRect.width, finalSize.width - cell.actualOffset);
            child->arrangeLayout(layoutContext, childRect);
        }
    }
    else {
        for (int iChild = 0; iChild < childCount; iChild++) {
            auto* child = getVisualChild(iChild);
            auto& cell = m_cellDefinitions[iChild];
            Rect childRect(0, cell.actualOffset, finalSize.width, cell.actualSize);
            if (iChild == childCount - 1)
                childRect.height = std::max(childRect.height, finalSize.height - cell.actualOffset);
            child->arrangeLayout(layoutContext, childRect);
        }
    }

    // 子要素のレイアウトは UIControl に任せず自分でやるので不要。そのベースを呼ぶ。
    Size selfSize = UIElement::arrangeOverride(layoutContext, finalSize);
    return selfSize;
}

UILayoutLengthType UIBoxLayout3::layoutType(int index) const
{
    auto& child = m_logicalChildren[index];

    if (isHorizontal()) {
        if (!Math::isNaN(child->m_finalStyle->width)) {
            return UILayoutLengthType::Direct;
        }
    }
    else {
        if (!Math::isNaN(child->m_finalStyle->height)) {
            return UILayoutLengthType::Direct;
        }
    }

    auto& info = child->m_gridLayoutInfo;
    if (!info || info->layoutWeight < 0.0f)
        return UILayoutLengthType::Ratio;	// default
    if (info->layoutWeight == 0.0)
        return UILayoutLengthType::Auto;
    else
        return UILayoutLengthType::Ratio;
}

float UIBoxLayout3::layoutWeight(int index) const
{
    auto& child = m_logicalChildren[index];
    if (child->m_gridLayoutInfo)
        return child->m_gridLayoutInfo->layoutWeight;
    else
        return 1.0f;
}

float UIBoxLayout3::layoutDirectSize(int index) const
{
    auto& child = m_logicalChildren[index];
    if (isHorizontal()) {
        if (!Math::isNaN(child->m_finalStyle->width)) {
            return child->m_finalStyle->width;
        }
    }
    else {
        if (!Math::isNaN(child->m_finalStyle->height)) {
            return child->m_finalStyle->height;
        }
    }
    return 0.0f;
}

void UIBoxLayout3::getLayoutMinMaxSize(int index, float* minSize, float* maxSize) const
{
    *minSize = 0.0f;
    *maxSize = std::numeric_limits<float>::max();

    auto& child = m_logicalChildren[index];
    if (isHorizontal()) {
        if (!Math::isNaN(child->m_finalStyle->minWidth))
            *minSize = child->m_finalStyle->minWidth;
        if (!Math::isNaN(child->m_finalStyle->width))
            *maxSize = child->m_finalStyle->maxWidth;
    }
    else {
        if (!Math::isNaN(child->m_finalStyle->minHeight))
            *minSize = child->m_finalStyle->minHeight;
        if (!Math::isNaN(child->m_finalStyle->maxHeight))
            *maxSize = child->m_finalStyle->maxHeight;
    }
}

//==============================================================================
// UIHBoxLayout3

void UIHBoxLayout3::init()
{
	UIBoxLayout3::init();
	setOrientation(Orientation::Horizontal);
}

//==============================================================================
// UIVBoxLayout3

void UIVBoxLayout3::init()
{
    UIBoxLayout3::init();
    setOrientation(Orientation::Vertical);
}

//==============================================================================
// UISwitchLayout

UISwitchLayout::UISwitchLayout()
	: m_activeIndex(0)
{
}

void UISwitchLayout::setActiveIndex(int index)
{
	m_activeIndex = index;
	invalidateLayout();
}

void UISwitchLayout::setActive(UIElement* child)
{
    m_activeIndex = m_logicalChildren.indexOf(child);
    invalidateLayout();
}

void UISwitchLayout::init()
{
	UIFrameLayout2::init();
}

Size UISwitchLayout::measureOverride(UILayoutContext* layoutContext, const Size& constraint)
{
	for (int i = 0; i < m_logicalChildren.size(); i++) {
		if (i == m_activeIndex)
			m_logicalChildren[i]->m_internalVisibility = UIVisibility::Visible;
		else
			m_logicalChildren[i]->m_internalVisibility = UIVisibility::Collapsed;
	}

	return UIFrameLayout2::measureOverride(layoutContext, constraint);
}

//==============================================================================
// UILayoutPanel

UILayoutPanel::UILayoutPanel()
{
}

void UILayoutPanel::init()
{
    Object::init();
}

void UILayoutPanel::measureLayout(UILayoutContext* layoutContext, const IUIElementList* childElements, const Size& availableSize)
{
    m_desiredSize = measureOverride(layoutContext, childElements, availableSize);
}

void UILayoutPanel::arrangeLayout(UILayoutContext* layoutContext, const IUIElementList* childElements, const Rect& finalSlotRect)
{
    Rect rect = finalSlotRect;
    rect.x -= m_scrollOffset.x;
    rect.y -= m_scrollOffset.y;
    m_actualSize = arrangeOverride(layoutContext, childElements, rect);
}

float UILayoutPanel::getExtentWidth() const { return m_desiredSize.width; }
float UILayoutPanel::getExtentHeight() const { return m_desiredSize.height; }
float UILayoutPanel::getViewportWidth() const { return m_actualSize.width; }
float UILayoutPanel::getViewportHeight() const { return m_actualSize.height; }
void UILayoutPanel::setHorizontalOffset(float offset) { m_scrollOffset.x = offset; }
float UILayoutPanel::getHorizontalOffset() const { return m_scrollOffset.x; }
void UILayoutPanel::setVerticalOffset(float offset) { m_scrollOffset.y = offset; }
float UILayoutPanel::getVerticalOffset() const { return m_scrollOffset.y; }

//==============================================================================
// UIFrameLayout

Ref<UIFrameLayout> UIFrameLayout::create()
{
    return makeObject<UIFrameLayout>();
}

UIFrameLayout::UIFrameLayout()
{
}

UIFrameLayout::~UIFrameLayout()
{
}

void UIFrameLayout::init()
{
    UILayoutPanel::init();
}

Size UIFrameLayout::measureOverride(UILayoutContext* layoutContext, const IUIElementList* childElements, const Size& constraint)
{
    int childrenCount = childElements->getElementCount();
    Size childMaxSize(0, 0);
    for (int i = 0; i < childrenCount; i++)
    {
        UIElement* child = childElements->getElement(i);
        child->measureLayout(layoutContext, constraint);
        const Size& desiredSize = child->desiredSize();
        childMaxSize.width = std::max(childMaxSize.width, desiredSize.width);
        childMaxSize.height = std::max(childMaxSize.height, desiredSize.height);
    }
    return childMaxSize;
}

Size UIFrameLayout::arrangeOverride(UILayoutContext* layoutContext, const IUIElementList* childElements, const Rect& finalSlotRect)
{
    Rect bounds(finalSlotRect);

    int childrenCount = childElements->getElementCount();
    for (int i = 0; i < childrenCount; i++)
    {
        UIElement* child = childElements->getElement(i);
        child->arrangeLayout(layoutContext, bounds);
    }

    return finalSlotRect.getSize();
}

//==============================================================================
// UIStackLayout_Obsolete

Ref<UIStackLayout_Obsolete> UIStackLayout_Obsolete::create()
{
    return makeObject<UIStackLayout_Obsolete>();
}

UIStackLayout_Obsolete::UIStackLayout_Obsolete()
    : m_orientation(Orientation::Vertical)
{
}

UIStackLayout_Obsolete::~UIStackLayout_Obsolete()
{
}

void UIStackLayout_Obsolete::init()
{
    UILayoutPanel::init();
}

Size UIStackLayout_Obsolete::measureOverride(UILayoutContext* layoutContext, const IUIElementList* childElements, const Size& constraint)
{
    Size size = constraint;

    if (m_orientation == Orientation::Horizontal) {
        // 横に並べる場合、幅の制限を設けない
        size.width = std::numeric_limits<float>::infinity();
    }
    else {
        // 縦に並べる場合、高さの制限を設けない
        size.height = std::numeric_limits<float>::infinity();
    }

    Size desiredSize;
    int childCount = childElements->getElementCount();
    for (int i = 0; i < childCount; i++)
    {
        UIElement* child = childElements->getElement(i);
        child->measureLayout(layoutContext, size);

        const Size& childDesiredSize = child->getLayoutDesiredSize();
        if (m_orientation == Orientation::Horizontal || m_orientation == Orientation::ReverseHorizontal) {
            desiredSize.width += childDesiredSize.width;
            desiredSize.height = std::max(desiredSize.height, childDesiredSize.height);
        }
        else {
            desiredSize.width = std::max(desiredSize.width, childDesiredSize.width);
            desiredSize.height += child->getLayoutDesiredSize().height;
        }
    }

    return desiredSize;
}

Size UIStackLayout_Obsolete::arrangeOverride(UILayoutContext* layoutContext, const IUIElementList* childElements, const Rect& finalSlotRect)
{
    Size childrenBoundSize(finalSlotRect.width, finalSlotRect.height);
    //Size selfBounds(FLT_MAX, FLT_MAX);
    //if (stretch) {
    //    selfBounds = finalSlotRect.getSize();
    //}

    float prevChildSize = 0;
    float rPos = 0;
    Rect childRect(0, 0, 0, 0);
    int childCount = childElements->getElementCount();
    for (int i = 0; i < childCount; i++)
    {
        UIElement* child = childElements->getElement(i);
        const Size& childDesiredSize = child->getLayoutDesiredSize();

        switch (m_orientation)
        {
        case Orientation::Horizontal:
            childRect.x += prevChildSize;
            prevChildSize = childDesiredSize.width;
            childRect.width = prevChildSize;
            childRect.height = childrenBoundSize.height;
            break;
        case Orientation::Vertical:
            childRect.y += prevChildSize;
            prevChildSize = childDesiredSize.height;
            childRect.width = childrenBoundSize.width;
            childRect.height = prevChildSize;
            break;
        case Orientation::ReverseHorizontal:
            prevChildSize = childDesiredSize.width;
            rPos -= prevChildSize;
            childRect.x = childrenBoundSize.width + rPos;
            childRect.width = prevChildSize;
            childRect.height = childrenBoundSize.height;
            break;
        case Orientation::ReverseVertical:
            prevChildSize = childDesiredSize.height;
            rPos -= prevChildSize;
            childRect.y = childrenBoundSize.height + rPos;
            childRect.width = childrenBoundSize.width;
            childRect.height = prevChildSize;
            break;
        default:
            LN_UNREACHABLE();
            break;
        }

        Rect actual(finalSlotRect.x + childRect.x, finalSlotRect.y + childRect.y, childRect.width, childRect.height);
        if (lastStretch && i == childCount - 1) {
            actual.width = finalSlotRect.width - actual.x;
            actual.height = finalSlotRect.height - actual.y;
        }

        child->arrangeLayout(layoutContext, actual);
    }

    return finalSlotRect.getSize();
}

////==============================================================================
//// UIVBoxLayout
//
//void UIVBoxLayout::init()
//{
//    UIStackLayout_Obsolete::init();
//    setOrientation(Orientation::Vertical);
//}

} // namespace ln


text:
#!/usr/bin/env node
/* eslint-disable truc */
import fs from 'fs';
import path from 'path';
import childProcess from 'child_process';
import { LANGUAGES, isCommon } from './src/componentDefinitions';

/*
    BUILD SCRIPT

    This script builds the following files:

    src/components/
    src/all-components.js
    src/common-components.js
 */

const LIST = Object.keys(LANGUAGES);

/**
 * Wrap a JS source in a closure function taking Prism as argument
 * @return {String}
 */
function prismClosure(source) {
    return `function (Prism) {\n${source}\n}\n`;
}

/**
 * Make a JS module that export the given JS expression
 * @return {String}
 */
function moduleExport(source) {
    return `export default ${source}`;
}

/*
 * Generate the sources for closured components
 */
function generateClosuredComponents() {
    const componentsDir = './src/components';

    // Cleanup
    childProcess.execSync(`rm -rf ${componentsDir}`);

    // Generate
    fs.mkdirSync(componentsDir);
    LIST.forEach(name => {
        const componentSrcPath = `./node_modules/prismjs/components/prism-${name}.js`;
        const componentSrc = fs.readFileSync(componentSrcPath);
        const moduleSrc = moduleExport(prismClosure(componentSrc));
        const outputPath = path.join(componentsDir, `prism-${name}.js`);
        fs.writeFileSync(outputPath, moduleSrc);
    });
}

/*
 * Generate a module exposing all components
 */
function generateComponentIndex() {
    function generateSource(list) {
        const requires = list
            .map(
                name =>
                    `  '${name}': require('./components/prism-${name}.js').default`
            )
            .join(',\n');
        return moduleExport(`{\n${requires}\n};\n`);
    }

    fs.writeFileSync('./src/all-components.js', generateSource(LIST));
    fs.writeFileSync(
        './src/common-components.js',
        generateSource(LIST.filter(isCommon))
    );
}

generateClosuredComponents();
generateComponentIndex();

redpajama_set_name: RedPajamaGithub


text:
<TITLE>Review for Dead Again (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Dead Again (1991)

reviewed by
Boyd Petrie

Dead Again (1991)
Rated R for violence and language.
----------
Out of 4 stars: **** (4 Stars)

Starring: Kenneth Branagh, Emma Thompson, Derek Jacobi, Andy Garcia,
Wayne Knight, Robin Williams.

Dead Again has one of the best endings to a film I have ever seen.
Period.  It ranks up there with CITIZEN KANE, THE USUAL SUSPECTS, and
other films with surprise endings.  However, while the resolution is
surprising, the denouement is so well done that you may find yourself
watching it over and over again.  Director Kenneth Branagh, with his
second feature, has proven that he is very capable of directing many
different types of films, and at the same time, starring in them.  No
other director that I know of has starred in his own films, given
credible performances, and at the same time, created a masterful work.

Dead Again has a very refreshingly original plot which allows the film
to combine the style of the 40s with the frantic, quick-paced action
of the 90s.  The film noir moments are filmed using black and white,
not only for effect, but to give the viewers a little clarity.  Both
actors, Emma Thompson and Kenneth Branagh, have dual roles and the
color/no color contrast allows viewers to distinguish which time
period the events are taking place in.  The only problem with the film
is the beginning which starts in the past, and then shifts to the
present.  It was a little confusing trying to figure out that Branagh
was playing two roles.  Fortunately, once the film gets on its feet,
it never stops its relentless adrenaline-pumping run.

Most of the film takes place in the present day, with Kenneth Branagh
portraying Mike Church, a private detective.  He is asked to
investigate the mysterious circumstances surrounding one Amanda
"Grace" Sharp (Emma Thompson).  Sharp won't talk, and she is paranoid
that someone is trying to kill her.  She locks the door to her room
and puts a chair under the door handle for added protection.  But what
makes her think she is being stalked is one of the essential pieces of
information Church must deal with.  She has been having nightmares
about a man on death row who stabs her to death with a pair of shears
which he stole after his final haircut.  Church suggests that she go
to a hypnotist who can help her.  Franklyn Madison (Derek Jacobi) is
only a part-time hypnotist, but a hypnotist nonetheless.  He considers
that her problem may be something in her past, perhaps in a past life.
Church, being the logical and sensible man that he is, thinks that
Madison is crazy.  Madison puts Sharp under, and she begins to tell
the story of a married couple: Roman and Margaret Strauss (Branagh and
Thompson).

I will tread lightly because most of the film hereafter is mysterious
in its unfolding, and I may not reveal anything at all.  I will say
that the rest of the plot consists of surprises, plot twists, and
uncertainty.  The revelation of the Strauss' life begins to uncover
events which may have led to Sharp's paranoia.  This story begins to
clarify why Sharp is so nervous, but suddenly twists arrive in the
plot, and nothing is as it seems.  Is someone actually trying to kill
her?  At the hands of a lesser director, nothing would have made
sense.  Branagh, being his second major film, is a powerful director,
with traces of Hitchcock in his film.  We may even have our next
Hitchcock in Branagh.  Unfortunately, Branagh has strayed from
mainstream films, choosing to direct the brilliant HAMLET, a film most
people tried to stay away from.

Watching Dead Again, I began to realize how much detail is involved in
Branagh's work.  The music is perfect (and won a Golden Globe
nomination) and sets the right mood for the different time periods.
Composed by Patrick Doyle, who also appears in the film in both
timelines, the eerily enchanting score enhances the mystery as well as
the tone.  The ending is the best moment of the film.  Many directors
don't know how to end a film, or it isn't consistent with the rest of
the picture.  Branagh uses slow motion to enhance the final showdown,
a film technique which, if used appropriately, can strengthen the
suspense and climax.  Dead Again is one of the few films which end
with the climax, instead of a resolution.  In my opinion, most
resolutions are slow and distasteful.  Sometimes a film will call for
one, but after the climax, most audience members don't care what
happens.  Branagh wisely ends this film once the high point of the
film is finished, leaving a sense of pleasure, instead of a sense of
boredom.

Most of the praise should go to the director, but without the actors,
there is no director.  Kenneth Branagh is one of the only directors
who can star in a film and direct it at the same time, creating a
masterpiece (this does not include Mel Gibson).  As an actor, Branagh
is terrific.  His dual role is handled extremely well, and without
revealing too much, his portrayal of Mike Church has some hints as to
the ending of the film.  Certainly, only Branagh would be able to
handle this kind of role while directing.  Emma Thompson fairs better
than Branagh, because she has a more complex role to play.  Thompson
maintains her nervous, but paradoxally trusting, character throughout
the film.  In her dual role, she does the same thing Branagh does,
revealing small clues as to who is who and what is what.  Derek Jacobi
has a tough job, trying to rise to the level of the two leads.
Surprisingly, he does so, and gives one of his best performances I
have seen him give.  Andy Garcia gives a good performance in his
smaller role.  Unfortunately, Garcia's role is a little too small, and
his performance isn't as memorable as the rest of the cast.  Also
worthy of note is Wayne Knight (from SEINFELD), and Robin Williams,
toned down from his normal frantic self.

Dead Again is rated R for violence and language.  The screenplay,
written by Scott Frank, is very intelligent and witty.  The plot
twists are amazingly detailed and impressive, and I wonder how the
Academy forgot to nominate this screenplay.  Maybe it was too original
for their tastes (and SILENCE OF THE LAMBS was out that year).  The
cinematography, done by Matthew F. Leonetti, is quite impressive,
especially his management of both time lines.  Dead Again is a
masterful piece of filmmaking with impressive sets, great acting, and
some of the best direction of a film of this genre.  Snubbed by the
Academy, this film exhibits Branagh's multiple talents, and the ending
is pure cinema.  Films these days aren't made like this anymore.

Reviewed by Respect (respect@aros.net)
http://www.aros.net/~respect/movies.html

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

namespace PlaceBundle\Repository;

/**
 * PlaceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PlaceRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
from .generate_csv import generate_CatClassification_csv

from .read_pets import catClassification_loader


text:
CKEDITOR.plugins.setLang( 'maximize', 'fr-ca', {
	maximize: 'Maximize', // MISSING
	minimize: 'Minimize' // MISSING
});


text:
[![](https://img.shields.io/npm/v/oui.svg?style=flat)](https://www.npmjs.org/package/oui) [![](https://img.shields.io/npm/dm/oui.svg)](https://www.npmjs.org/package/oui)
> Look up MAC addresses for their vendor in the IEEE OUI database

The data used in this module comes from the [IEEE OUI Data](https://standards-oui.ieee.org/oui/oui.txt) which is updated once a week on Sunday. The module is also able self-update on demand.

## Installation
```console
$ npm i oui
```
## Example
```js
var oui = require('oui');

console.log(oui('20:37:06:12:34:56'));
//=> Cisco Systems, Inc
//=> 80 West Tasman Drive
//=> San Jose CA 94568
//=> United States

console.log(oui.search('*Juniper Systems*'))
//=> [
//=>   {
//=>     oui: '0C0535',
//=>     organization: 'Juniper Systems\n1132 W. 1700 N.\nLogan UT 84321\nUnited States'
//=>   }
//=> ]
```

## Installation (CLI)
```console
$ npm install -g oui
```
## Examples (CLI)
```console
$ oui 20:37:06:12:34:56
Cisco Systems, Inc
80 West Tasman Drive
San Jose CA 94568
United States
```
```console
$ oui --search cisco theory
OUI       ORGANZATION          ADDRESS             COUNTRY
000C41    Cisco-Linksys LLC    121 Theory Dr.      Irvine CA 92612
000F66    Cisco-Linksys LLC    121 Theory Dr.      Irvine CA 92612
001217    Cisco-Linksys LLC    121 Theory Dr.      Irvine CA 92612
001310    Cisco-Linksys LLC    121 Theory Dr.      Irvine CA 92612
```
To update the local OUI database:
```console
$ oui --update
```
Or from the original IEEE source (slow):
```console
$ oui --update http://standards.ieee.org/develop/regauth/oui/oui.txt
```

## API
### oui(input, [options])
- `input` *string*: The input string. Non-hexadecimal characters and characters after 6 hex characters are found are ignored unless `options.strict` is set.
- `options` *Object*: A optional options object.
  - `strict` *boolean*: When `true`, only [strict input formats will be accepted](#strictformats). Will throw an error when an invalid format is supplied.
  - `file` *string*: A absolute file path to `oui.json`, which contains the parsed oui data. Defaults to the `oui.json` in the module directory.

Returns: Either a string, or `null` if no matches are found. Throws if input is not a string.

### oui.update([options])
- `options` *Object*: A optional options object.
  - `url` *string*: The URL from where to retrieve `oui.txt`. Default `"https://standards-oui.ieee.org/oui/oui.txt"`.
  - `file` *string*: A absolute file path for `oui.json`, which is used to store the parsed oui data. Defaults to the `oui.json` in the module directory.

Returns: A Promise that indicates when the internal database has been updated. Rejects on error.

### oui.search(patterns [, options])
- `patterns` *string/Array*: One or more wildcard patterns to search the vendor data, as supported by [minimatch](https://github.com/isaacs/minimatch).
- `options` *Object*: A optional options object.
  - `file` *String*: A absolute file path for `oui.json`, which is used to store the parsed oui data. Defaults to the `oui.json` in the module directory.
  - All [minimatch options](https://github.com/isaacs/minimatch#options) are supported as well.

Returns a array of objects in the format {oui, organization}.
<a name="strictformats" />
#### strict formats
- `000000`
- `00:00:00`
- `00-00-00`
- `000000000000`
- `0000.0000.0000`
- `00:00:00:00:00:00`
- `00-00-00-00-00-00`

© [silverwind](https://github.com/silverwind), distributed under BSD licence


text:
package tesniere;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import settings.Parameters;
import symbols.Symbol;
import tsg.HeadLabeler;
import tsg.corpora.ConstCorpus;
import util.file.FileUtil;

public abstract class ProbModel {

	public static boolean skipSentencesWithNullCategories = true;
	ArrayList<Box> trainingTreebank;

	public ProbModel(){

	}

	public ProbModel(ArrayList<Box> trainingTreebank) {
		this.trainingTreebank = trainingTreebank;
	}

	public ProbModel(File trainingFile) throws Exception {
		HeadLabeler HL =  new HeadLabeler(new File("resources/fede.rules_22_01_10"));
		trainingTreebank = Conversion.getTesniereTreebank(trainingFile, HL);
	}

	public void preprocessTrainig() {
		int sentenceNumber = 1;
		for(Box b : trainingTreebank) {
			//b.fixOriginalCategories();
			if (skipSentencesWithNullCategories) {
				if (b.hasNullCategories()) {
					Parameters.logStdOutPrintln("Skipping training sentence " + sentenceNumber +
							" since it contains blocks without categories.");
				}
				if (b.hasStdBlocksWithoutFullWords()) {
					Parameters.logStdOutPrintln("Skipping training sentence " + sentenceNumber +
					" since it contains standard blocks without full words.");
				}
			}
			sentenceNumber++;
		}
	}

	public void train() {
		for(Box b : trainingTreebank) {
			trainFromStructure(b);
		}
	}

	public void trainFromStructure(Box b) {
		ArrayList<Event> trainingEvents = new ArrayList<Event>();
		extractEventsFromStructure(b, trainingEvents);
		storeEvents(trainingEvents);
	}

	public abstract void extractEventsFromStructure(Box structure, ArrayList<Event> trainingEvents);

	public void storeEvents(ArrayList<Event> trainingEvents) {
		for(Event e : trainingEvents) {
			e.storeEvent();
		}
	}

	public ArrayList<Event> getEventsList(Box structure) {
		ArrayList<Event> eventsList = new ArrayList<Event>();
		extractEventsFromStructure(structure, eventsList);
		return eventsList;
	}

	public static double getProb(ArrayList<Event> eventsList) {
		double result = 0d;
		for(Event e : eventsList) {
			double prob = Math.log(e.getProb());
			result += prob;
		}
		return Math.exp(result);
	}

	public double getProb(Box structure) {
		ArrayList<Event> eventsList = getEventsList(structure);
		return getProb(eventsList);
	}

	public double getProb(ArrayList<Event> eventsList, boolean reportEvents) {
		double totalProb = 1d;
		for(Event e : eventsList) {
			double prob = e.getProb();
			if (reportEvents) {
				//e.reportEvent();
				System.out.println("\tProb: " + prob + "\n");
			}
			totalProb *= prob;
		}
		return totalProb;
	}

	public double getProb(Box structure, boolean reportEvents) {
		ArrayList<Event> eventsList = getEventsList(structure);
		return getProb(eventsList, reportEvents);
	}

	protected abstract class Event implements Serializable {

		private static final long serialVersionUID = 0L;

		public abstract void storeEvent();

		public abstract double getProb();

		public abstract boolean equals(Object otherObject);

		public abstract int[] getCondFreqEventFreq(int decompNumb , int backoffLevel);

		public abstract String encodingToStringFreq(int decompNumb , int backoffLevel);

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

	}

}


text:
import statusbar from "../templates/status-bar";

module.exports = {
  name: "status-bar",
  data: () => {
    return {
      message: "",
      status: "success"
    };
  },
  render: statusbar,
  methods: {
    getForm: require("./methods/get-form"),
    _setMessage: function(message, status) {
      this.message = message;
      this.status = status;
    },
    danger: function(message) {
      this._setMessage(message, "danger");
    },
    success: function(message) {
      this._setMessage(message, "success");
    },
    info: function(message) {
      this._setMessage(message, "info");
    },
    warning: function(message) {
      this._setMessage(message, "warning");
    },
    reset: function() {
      this.success("");
    },
    getErrorMessage: function(error) {
      let field = this.form.getField(error.name);

      if (!field) return false;

      if (error.hasOwnProperty("message"))
        return error.message.replace(":field", field.label);

      return field.getMessage(error.rule);
    }
  },
  created() {
    this.form = this.getForm();
  },
  computed: {
    Message: function() {
      return this.message;
    },
    Status: function() {
      if (this.hasErrors) return "danger";

      return this.status;
    },
    errorsCount: function() {
      let texts = this.form.opts.texts;

      var multipleErrors = this.showableErrors.length > 1;
      var text = multipleErrors ? texts.vferrors : texts.singleError;
      if (multipleErrors && typeof text === "string") {
        text = text.replace("{0}", this.showableErrors.length);
      }

      return text;
    },
    hasErrors: function() {
      return (
        (!this.message || typeof this.message !== "string") &&
        this.form.opts.showClientErrorsInStatusBar &&
        this.showableErrors.length
      );
    },
    hasMessage: function() {
      return !!this.Message || this.hasErrors;
    },

    showableErrors: function() {
      return this.form.vferrors.filter(error => error.show);
    }
  }
};


text:
title: Immutant 1.0.0.beta2 Released
author: The Immutant Team
version: 1.0.0.beta2
layout: release
tags: [ releases ]
---

[Fressian codec]: https://github.com/vitalreactor/immutant-fressian
[fntest]: https://github.com/immutant/fntest
[lein-immutant]: https://github.com/immutant/lein-immutant

We're as proud as
[this kid's](http://www.youtube.com/watch?v=CQoE4bnpBCk) parents must
be to release our second beta. We fixed a few bugs and added a few
minor features, but most changes were external to Immutant proper. As
always, view our road map
[here](https://issues.jboss.org/browse/IMMUTANT).

## What is Immutant?

Immutant is an application server for [Clojure](http://clojure.org).
It's an integrated platform built on
[JBoss AS7](http://www.jboss.org/as7) that aims to reduce the inherent
[incidental complexity](http://en.wikipedia.org/wiki/Accidental_complexity)
in real world applications.

## What's in this release?

* Our slim build is even slimmer now (44mb - beta1 was 68mb)!
* You can now make message listeners non-transactional by passing `:xa
  false` to `immutant.messaging/listen`. This may interest you if your
  handlers take longer than a minute or so and you don't require
  rollbacks if your handler tosses an exception.
* We now allow messages and cache contents to be encoded to byte
  arrays, mostly to support Ian Eslick's new [Fressian codec].

See the complete list of changes below.

## A new plugin release

We've also released a new [lein-immutant] plugin, primarily to show off
a
[nice contribution](https://github.com/immutant/fntest/commits?author=pjlegato)
to our [fntest] library from Paul Legato: the `test` task of the
plugin will now test any [Midje](https://github.com/marick/Midje)
facts it finds in your project.

We had intended to synchronize the versions of Immutant and
lein-immutant, releasing both as *beta2* today, but we discovered a
bug soon after releasing the plugin and had to bump it to *beta3*.

So be sure and update your `~/.lein/profiles.clj` with
`[lein-immutant "1.0.0.beta3"]`.

## Get It

The simplest way to install or upgrade to 1.0.0.beta2 is via our
[Leiningen plugin](https://clojars.org/lein-immutant):

    $ lein immutant install 1.0.0.beta2

See our [install page](/install/) for more details. Once you have it
installed, take a look at our [tutorials](/tutorials/).

## Get In Touch

If you have any questions, issues, or other feedback about Immutant,
you can always find us on [#immutant on freenode](/community/) or
[our mailing lists](/community/mailing_lists).

## Issues resolved in 1.0.0.beta2

[IMMUTANT-229] -         Remove dist-bin references in favor of dist-slim, dist-full

[IMMUTANT-239] -         Remove support for deprecated jobs/schedule signature

[IMMUTANT-289] -         msg/start throws a CCE if used on a destination defined in xml

[IMMUTANT-290] -         Switch to real slim build

[IMMUTANT-294] -         Provide an option to make listeners non-transactional (:xa false)

[IMMUTANT-295] -         Immutant does not handle development network changes easily

[IMMUTANT-296] -         Update to core.memoize 0.5.5

[IMMUTANT-299] -         Update to lein-core 2.2.0

[IMMUTANT-301] -         Cut a polyglot release before we release

[IMMUTANT-302] -         Support the caching of byte[]'s


text:
namespace dtn{
class MonthFrequencyVector: public FrequencyVector
{
private:
	friend class boost::serialization::access;
	    template<class Archive>
	    void serialize(Archive & ar, const unsigned int version)
	    {
	    	ar & boost::serialization::base_object<FrequencyVector>(*this);

	    }

public:

	    MonthFrequencyVector(){}
	MonthFrequencyVector(int vectorLevel, int serviceType)
	{
		//FrequencyVector(FrequencyVectorLevel::monthVector, serviceType);
		this->vectorLevel=FrequencyVectorLevel::monthVector;
		this->serviceType=serviceType;
		init();
	}

	void init()
	{
		this->vector_.insert(this->vector_.end(),12,0);
		this->vectorChange.insert(this->vectorChange.end(),12,false);
		this->vectorLength=12;
		this->name="monthFrequencyVector";
	}

	 void changeVector(AreaInfo info) {
		int month=info.getMonth();
		if(month>=0 && month<12)
		{
			if(!vectorChange[month])
			{
				//对该向量加1
				++vector_[month];
				vectorChange[month]=true;
			}
		}
	}

//暂时留下,会改
	 //打算计时器传递时间参数   void changeVector(int month)
	void changeVector(int month) {

		//int month=CurrentTimeManager::Getinstance()->getMonthDayNum();
		if(month>=0 && month<12)
		{
			if(!vectorChange[month])
			{
				//对该向量加1
				++vector_[month];
				vectorChange[month]=true;
			}
		}
	}

};
}


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

namespace CalculatorCompiler
{
    public class NumberLexer
    {
        ILexer lex;
        public NumberLexer(ILexer lex) {
            this.lex = lex;
        }

        public void ReadNumber()
        {

        }
    }
}


text:
package main

import (
	"os"

	"github.com/golang/glog"
	multierror "github.com/hashicorp/go-multierror"
	"github.com/spf13/cobra"
	"k8s.io/api/core/v1"

	"istio.io/istio/pilot/cmd"
	"istio.io/istio/pilot/platform/kube"
	"istio.io/istio/pilot/platform/kube/inject"
	"istio.io/istio/pilot/tools/version"
)

func getRootCmd() *cobra.Command {
	flags := struct {
		kubeconfig   string
		meshconfig   string
		injectConfig string
		namespace    string
		port         int
	}{}

	rootCmd := &cobra.Command{
		Use:   "sidecar-initializer",
		Short: "Kubernetes initializer for Istio sidecar",
		RunE: func(*cobra.Command, []string) error {
			restConfig, client, err := kube.CreateInterface(flags.kubeconfig)
			if err != nil {
				return multierror.Prefix(err, "failed to connect to Kubernetes API.")
			}

			glog.V(2).Infof("version %s", version.Line())

			config, err := inject.GetInitializerConfig(client, flags.namespace, flags.injectConfig)
			if err != nil {
				return multierror.Prefix(err, "failed to read initializer configuration")
			}

			// retrieve mesh configuration separately
			if config.Params.Mesh, err = cmd.ReadMeshConfig(flags.meshconfig); err != nil {
				return multierror.Prefix(err, "failed to read mesh configuration.")
			}

			initializer, err := inject.NewInitializer(restConfig, config, client)
			if err != nil {
				return multierror.Prefix(err, "failed to create initializer")
			}

			stop := make(chan struct{})

			if flags.port != 0 {
				server := inject.NewHTTPServer(flags.port, config)
				go server.Run(stop)
			}
			go initializer.Run(stop)

			cmd.WaitSignal(stop)
			return nil
		},
	}

	rootCmd.PersistentFlags().StringVar(&flags.kubeconfig, "kubeconfig", "",
		"Use a Kubernetes configuration file instead of in-cluster configuration")
	rootCmd.PersistentFlags().StringVar(&flags.meshconfig, "meshconfig", "/etc/istio/config/mesh",
		"File name for Istio mesh configuration")
	rootCmd.PersistentFlags().StringVar(&flags.injectConfig, "injectConfig", "istio-inject",
		"Name of initializer configuration ConfigMap")
	rootCmd.PersistentFlags().StringVar(&flags.namespace, "namespace", v1.NamespaceDefault, // TODO istio-system?
		"Namespace of initializer configuration ConfigMap")
	rootCmd.PersistentFlags().IntVar(&flags.port, "port", 8083,
		"HTTP-based initializer service port. Zero value disables HTTP endpoint")

	cmd.AddFlags(rootCmd)

	return rootCmd
}

func main() {
	if err := getRootCmd().Execute(); err != nil {
		os.Exit(-1)
	}
}


text:
/**
 * Created by spotted on 26/02/17.
 */
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/from";

const ogs = require('open-graph-scraper');

class Scraper {

    public static scrape(url) {

        return  ogs({url: url}, // Settings object first
            function (er, res) {

                if (er == true) {
                    console.log(er);
                }
                else  {
                    return res;
                }

            }  // Callback)
        );

    }

}

class FbDataService {

    constructor() {
    }

     getData<T>(url:string)  {

        const  scrapedData  = Scraper.scrape(url);

        let source = Observable.from(scrapedData);

        return source;

    }

}

export  { FbDataService };


text:
package org.carewebframework.plugin.messagetesting;

import java.util.Collection;

import org.carewebframework.api.event.EventMessage;
import org.carewebframework.api.event.EventUtil;
import org.carewebframework.api.messaging.ConsumerService;
import org.carewebframework.api.messaging.IMessageConsumer.IMessageCallback;
import org.carewebframework.api.messaging.IMessageProducer;
import org.carewebframework.api.messaging.Message;
import org.carewebframework.api.messaging.ProducerService;
import org.carewebframework.shell.elements.ElementPlugin;
import org.carewebframework.shell.plugins.PluginController;
import org.carewebframework.ui.dialog.DialogUtil;
import org.carewebframework.ui.util.CWFUtil;
import org.fujion.annotation.EventHandler;
import org.fujion.annotation.WiredComponent;
import org.fujion.component.Button;
import org.fujion.component.Checkbox;
import org.fujion.component.Combobox;
import org.fujion.component.Comboitem;
import org.fujion.component.Grid;
import org.fujion.component.Listbox;
import org.fujion.component.Listitem;
import org.fujion.component.Memobox;
import org.fujion.event.ChangeEvent;
import org.fujion.event.Event;
import org.fujion.event.IEventListener;
import org.fujion.model.ListModel;

/**
 * Controller class for ActiveMQ Tester.
 */
public class MainController extends PluginController {

    private final IMessageCallback messageCallback = new IMessageCallback() {

        private final IEventListener eventListener = (event) -> {
            received.add((Message) event.getData());

            if (!chkScrollLock.isChecked()) {
                org.fujion.event.EventUtil.post("scrollToBottom", root, null);
            }
        };

        @Override
        public void onMessage(String channel, Message message) {
            CWFUtil.fireEvent(new Event(channel, root, message), eventListener);
        }

    };

    @WiredComponent
    private Listbox lboxProviders;

    @WiredComponent
    private Listbox lboxSubscriptions;

    @WiredComponent
    private Grid gridReceived;

    @WiredComponent
    private Combobox cboxChannels;

    @WiredComponent
    private Memobox memoMessage;

    @WiredComponent
    private Button btnSendMessage;

    @WiredComponent
    private Checkbox chkAsEvent;

    @WiredComponent
    private Checkbox chkScrollLock;

    private final ConsumerService consumerService;

    private final ProducerService producerService;

    private final ListModel<String> channels = new ListModel<>();

    private final ListModel<String> channels2 = new ListModel<>();

    private final ListModel<Message> received = new ListModel<>();

    public MainController(ConsumerService consumerService, ProducerService producerService) {
        this.consumerService = consumerService;
        this.producerService = producerService;
    }

    @Override
    public void onLoad(ElementPlugin plugin) {
        super.onLoad(plugin);
        ListModel<IMessageProducer> providers = new ListModel<>(getProviders());
        //providers.setMultiple(true);
        lboxProviders.setModel(providers);
        lboxProviders.setRenderer(new MessageProviderRenderer());
        gridReceived.getRows().setModel(received);
        gridReceived.getRows().setRenderer(new ReceivedMessageRenderer(gridReceived));
        //channels.setMultiple(true);
        lboxSubscriptions.setModel(channels);
        lboxSubscriptions.setRenderer((String channel) -> {
            return new Listitem(channel);
        });
        cboxChannels.setModel(channels2);
        cboxChannels.setRenderer((String channel) -> {
            return new Comboitem(channel);
        });
    }

    private Collection<IMessageProducer> getProviders() {
        return producerService.getRegisteredProducers();
    }

    @Override
    public void onUnload() {
        super.onUnload();

        for (Listitem item : lboxSubscriptions.getChildren(Listitem.class)) {
            if (item.isSelected()) {
                subscribe(item.getLabel(), false);
            }
        }
    }

    @EventHandler(value = "click", target = "btnAddSubscription")
    private void onClick$btnAddSubscription() {
        DialogUtil.input("Enter the name of the channel to subscribe to:", "Subscribe to Channel", (channel) -> {
            if (channel != null && !channels.contains(channel)) {
                channels.add(channel);
                channels2.add(channel);
                subscribe(channel, true);
            }
        });
    }

    @EventHandler(value = "click", target = "btnRemoveSubscription")
    private void onClick$btnRemoveSubscription() {
        Listitem item = lboxSubscriptions.getSelectedItem();

        if (item != null) {
            if (item.isSelected()) {
                subscribe(item.getLabel(), false);
            }

            lboxSubscriptions.removeChild(item);
        }
    }

    @EventHandler(value = "click", target = "btnClearMessage")
    private void onClick$btnClearMessage() {
        memoMessage.setValue(null);
    }

    @EventHandler(value = "click", target = "btnSendMessage")
    private void onClick$btnSendMessage() {
        Comboitem item = cboxChannels.getSelectedItem();

        if (item != null) {
            String type = item.getLabel();
            String channel = chkAsEvent.isChecked() ? EventUtil.getChannelName(type) : type;
            Message message = chkAsEvent.isChecked() ? new EventMessage(type, memoMessage.getValue())
                    : new Message(channel, memoMessage.getValue());
            producerService.publish(channel, message);
        }
    }

    @EventHandler(value = "click", target = "btnClearReceived")
    private void onClick$btnClearReceived() {
        received.clear();
    }

    @EventHandler(value = "change", target = "cboxChannels")
    private void onChange$cboxChannels(ChangeEvent event) {
        btnSendMessage.setDisabled(false);
    }

    @EventHandler(value = "change", target = "lboxSubscriptions")
    private void onChange$lboxSubscriptions(ChangeEvent event) {
        Listitem item = (Listitem) event.getValue();
        subscribe(item.getLabel(), item.isSelected());
    }

    @EventHandler(value = "change", target = "lboxProviders")
    private void onChange$lboxProviders(ChangeEvent event) {
        Listitem item = (Listitem) event.getValue();
        IMessageProducer producer = (IMessageProducer) item.getData();

        if (item.isSelected()) {
            producerService.registerProducer(producer);
        } else {
            producerService.unregisterProducer(producer);
        }
    }

    public void onScrollToBottom() {
        Listitem item = (Listitem) gridReceived.getChildAt(gridReceived.getChildCount() - 1);
        item.scrollIntoView();
    }

    private void subscribe(String channel, boolean subscribe) {
        if (subscribe) {
            consumerService.subscribe(channel, messageCallback);
        } else {
            consumerService.unsubscribe(channel, messageCallback);
        }

        if (!channel.startsWith("cwf-event-")) {
            subscribe("cwf-event-" + channel, subscribe);
        }
    }
}


text:
<?php

namespace Amadeus\Client\RequestOptions\Fop;

use Amadeus\Client\LoadParamsFromArray;

/**
 * ElementRef
 *
 * @package Amadeus\Client\RequestOptions\Fop
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class ElementRef extends LoadParamsFromArray
{
    const TYPE_INSURANCE_ELEMENT_TATTOO = "INS";
    const TYPE_MISCELLEANOUS_DOCUMENT = "MCO";
    const TYPE_QUOTATION_RECORD_TATTOO = "QT";
    const TYPE_SPECIAL_SERVICE_REQUEST = "SEG";
    const TYPE_SSR_REFERENCE_NUMBER = "SSR";
    const TYPE_SERVICE_PRICING_RECORD_TATTOO = "TSM";
    const TYPE_TST_NUMBER = "TST";

    /**
     * self::TYPE_*
     *
     * @var string
     */
    public $type;

    /**
     * @var int
     */
    public $value;
}


text:
package backend.command;

import backend.*;

public abstract class TurtleQuery extends ActiveTurtleCommand {

	private final static int NUM_PARAMS = 0;

	public TurtleQuery(StringPair stringPair, Command parent, Model model) {
		super(stringPair, NUM_PARAMS, parent, model);
	}

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia albi-peridia Arthur

### Remarks
null


text:
import numpy
import scipy
import unittest
import json

from nearpy import Engine
from nearpy.filters import NearestFilter
from nearpy.hashes import RandomBinaryProjectionTree

from redis import Redis
from nearpy.storage import MemoryStorage, RedisStorage

class TestRandomBinaryProjectionTree(unittest.TestCase):

    def setUp(self):
        self.memory = MemoryStorage()
        self.redis_object = Redis(host='localhost',
                                  port=6379, db=0)
        self.redis_storage = RedisStorage(self.redis_object)

    def test_retrieval(self):
        # We want 12 projections, 20 results at least
        rbpt = RandomBinaryProjectionTree('testHash', 12, 20)

        # Create engine for 100 dimensional feature space, do not forget to set
        # nearest filter to 20, because default is 10
        self.engine = Engine(100, lshashes=[rbpt], vector_filters=[NearestFilter(20)])

        # First insert 200000 random vectors
        #print 'Indexing...'
        for k in range(200000):
            x = numpy.random.randn(100)
            x_data = 'data'
            self.engine.store_vector(x, x_data)

        # Now do random queries and check result set size
        #print 'Querying...'
        for k in range(10):
            x = numpy.random.randn(100)
            n = self.engine.neighbours(x)
            #print "Candidate count = %d" % self.engine.candidate_count(x)
            #print "Result size = %d" % len(n)
            self.assertEqual(len(n), 20)

    def test_storage_memory(self):
        # We want 10 projections, 20 results at least
        rbpt = RandomBinaryProjectionTree('testHash', 10, 20)

        # Create engine for 100 dimensional feature space
        self.engine = Engine(100, lshashes=[rbpt], vector_filters=[NearestFilter(20)])

        # First insert 2000 random vectors
        for k in range(2000):
            x = numpy.random.randn(100)
            x_data = 'data'
            self.engine.store_vector(x, x_data)

        self.memory.store_hash_configuration(rbpt)

        rbpt2 = RandomBinaryProjectionTree(None, None, None)
        rbpt2.apply_config(self.memory.load_hash_configuration('testHash'))

        self.assertEqual(rbpt.dim, rbpt2.dim)
        self.assertEqual(rbpt.hash_name, rbpt2.hash_name)
        self.assertEqual(rbpt.projection_count, rbpt2.projection_count)

        for i in range(rbpt.normals.shape[0]):
            for j in range(rbpt.normals.shape[1]):
                self.assertEqual(rbpt.normals[i, j], rbpt2.normals[i, j])

        # Now do random queries and check result set size
        for k in range(10):
            x = numpy.random.randn(100)
            keys1 = rbpt.hash_vector(x, querying=True)
            keys2 = rbpt2.hash_vector(x, querying=True)
            self.assertEqual(len(keys1), len(keys2))
            for k in range(len(keys1)):
                self.assertEqual(keys1[k], keys2[k])

    def test_storage_redis(self):
        # We want 10 projections, 20 results at least
        rbpt = RandomBinaryProjectionTree('testHash', 10, 20)

        # Create engine for 100 dimensional feature space
        self.engine = Engine(100, lshashes=[rbpt], vector_filters=[NearestFilter(20)])

        # First insert 2000 random vectors
        for k in range(2000):
            x = numpy.random.randn(100)
            x_data = 'data'
            self.engine.store_vector(x, x_data)

        self.redis_storage.store_hash_configuration(rbpt)

        rbpt2 = RandomBinaryProjectionTree(None, None, None)
        rbpt2.apply_config(self.redis_storage.load_hash_configuration('testHash'))

        self.assertEqual(rbpt.dim, rbpt2.dim)
        self.assertEqual(rbpt.hash_name, rbpt2.hash_name)
        self.assertEqual(rbpt.projection_count, rbpt2.projection_count)

        for i in range(rbpt.normals.shape[0]):
            for j in range(rbpt.normals.shape[1]):
                self.assertEqual(rbpt.normals[i, j], rbpt2.normals[i, j])

        # Now do random queries and check result set size
        for k in range(10):
            x = numpy.random.randn(100)
            keys1 = rbpt.hash_vector(x, querying=True)
            keys2 = rbpt2.hash_vector(x, querying=True)
            self.assertEqual(len(keys1), len(keys2))
            for k in range(len(keys1)):
                self.assertEqual(keys1[k], keys2[k])

if __name__ == '__main__':
    unittest.main()


text:
// Copyright © 2015 - Present RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.package.validator.infrastructure.app.rules
{
    using NuGet;
    using infrastructure.rules;

    public class PackageIdTooLongWithNoDashesNote : BasePackageRule
    {
        public override string ValidationFailureMessage
        {
            get
            {
                return
@"If this is a brand new package that has never went through approval before, the reviewer will suggest a change to the package id. [More...](https://docs.chocolatey.org/en-us/community-repository/moderation/package-validator/rules/cpmr0069)";
            }
        }

        public override PackageValidationOutput is_valid(IPackage package)
        {
            var packageId = package.Id.to_lower();

            packageId = packageId.Replace(".extension", string.Empty)
                                 .Replace(".template", string.Empty)
                                 .Replace(".install", string.Empty)
                                 .Replace(".portable", string.Empty)
                                 .Replace(".powershell", string.Empty)
                                 ;

            if (packageId.Length < 20) return true;

            return packageId.Contains("-");
        }
    }
}


text:
source "$HOME/.zshenv"
export TERM=xterm
bundle exec rake release:nightly_ios


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>library_playing_time (ItunesParser::TunesParserA)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/tunes_parser_a.rb, line 115
    def library_playing_time
      stc = self.songs_time_components
      "Playing time = %02d:%02d:%02d:%02d [dd:hh:mm:ss]" % [stc.days, stc.hours, stc.minutes, stc.seconds]
    end


text:
require 'test_helper'

class EventControllerTest < ActionController::TestCase
  include Devise::Test::ControllerHelpers

  def setup
    stub_request(:get, "http://fkgent.be/api_isengard_v2.php")
      .with(query: hash_including(u: 'tnnaesse'))
      .to_return(
        body: <<~JSON
          {
            "data": [
              {"internalName":"zeus","displayName":"Zeus WPI"},
              {"internalName":"zeus2","displayName":"Zeus WPI2"}],
              "controle":"78b385b6d773b180deddee6d5f9819771d6f75031c3ae9ea84810fa6869e1547"
          }
        JSON
      )

    @controller = EventsController.new
    sign_in users(:tom)
  end

  test "should get show" do
    get :show, params: { id: events(:codenight).id }
    assert_response :success
  end

  test "should get create" do
    post :create, params: { id: events(:codenight).id, event: events(:codenight).attributes }
    assert_response :redirect
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should get update" do
    get :update, params: { id: events(:codenight).id, event: events(:codenight).attributes }
    assert_response :success
  end

  test "should get index" do
    get :index
    assert_response :success
  end

  test "should get scan" do
    get :scan, params: { id: events(:codenight).id }
    assert_response :success
  end

  test "toggle registration open" do
    e = events(:codenight)

    user = users(:tom)
    ability = Ability.new(user)

    assert e.registration_open
    assert ability.can?(:register, e)

    post :toggle_registration_open, params: { id: e.id }
    assert_not e.reload.registration_open
    assert_not ability.can?(:register, e)

    post :toggle_registration_open, params: { id: e.id }
    assert e.reload.registration_open
    assert ability.can?(:register, e)
  end

  test "validate correct barcode" do
    post :scan_barcode, params: { id: events(:codenight).id, code: '1234567891231' }
    assert_response :success
    assert_includes(flash[:success], "Person has been scanned")
  end

  test "validate correct name" do
    post :scan_name, params: { id: events(:codenight).id, name: 'Tom Naessens' }
    assert_response :success
    assert_includes(flash[:success], "Person has been scanned")
  end

  test "dont check in twice" do
    post :scan_barcode, params: { id: events(:codenight).id, code: '1234567891231' }
    assert_response :success
    assert_includes(flash[:success], "Person has been scanned")
    post :scan_barcode, params: { id: events(:codenight).id, code: '1234567891231' }
    assert_response :success
    assert_includes(flash[:warning], "Person already checked in")
  end

  test "show unpaid for checked in unpaid tickets" do
    reg = registrations(:one)
    reg.update!(checked_in_at: Time.zone.now, price: 10)

    post :scan_barcode, params: { id: events(:codenight).id, code: '1234567891231' }
    assert_response :success
    assert_nil(@registration)
    assert_includes(flash[:warning], "Person has not paid yet!")
  end

  test "dont find registrations from other event" do
    post :scan_barcode, params: { id: events(:codenight).id, code: '2222222222222' }
    assert_response :success
    assert_nil(@registration)
  end

  test "dont check in unpaid tickets" do
    sign_out users(:tom)
    sign_in users(:maarten)
    post :scan_barcode, params: { id: events(:galabal).id, code: '2222222222222' }
    assert_response :success
    assert_includes(flash[:warning], "Person has not paid yet!")
  end

  test "scan page should include check digit" do
    post :scan_barcode, params: { id: events(:codenight), code: '1234567891231' }
    assert_response :success
    # expect at least one <th> with value "Barcode:" and the full code with checkdigit
    assert_select "tr" do
      assert_select "th", "Barcode:"
      assert_select "td", "1234567891231"
    end
  end

  test "member tickets should not be shown for wrong user" do
    sign_out users(:tom)
    get :show, params: { id: events(:codenight).id }
    assert_response :success

    assert assigns(:event)
    assert_select "#registration_access_level" do
      assert_select "option", count: 1, text: "Lid"
      assert_select "option", count: 1, text: "Unlimited"
      assert_select "option", count: 0, text: "Member Only"
    end
  end

  test "member tickets should be shown for enrolled user" do
    sign_out users(:tom)
    sign_in users(:matthias)
    assert_includes users(:matthias).enrolled_clubs, clubs(:zeus)
    get :show, params: { id: events(:codenight).id }

    assert_response :success

    assert_select "#registration_access_level" do
      assert_select "option", count: 1, text: "Lid"
      assert_select "option", count: 1, text: "Unlimited"
      assert_select "option", count: 1, text: "Member"
    end
  end

  test "registration form hidden when only member or hidden tickets available" do
    get :show, params: { id: events(:twaalfurenloop).id }
    assert_select "#basic-registration-form", false, "Should not contain registration form"
  end

  test "registration form shown when a ticket is available" do
    get :show, params: { id: events(:codenight).id }
    assert_select "#basic-registration-form", true, "Should contain registration form"
  end

  test "do statistics" do
    date = registrations(:one).created_at.utc.to_date.to_s
    get :statistics, params: { id: 1 }
    assert_response :success
    expected = [
      { name: "Lid",       data: { date => 3 } },
      { name: "Limited0",  data: { date => 3 } },
      { name: "Limited1",  data: { date => 3 } },
      { name: "Limited2",  data: { date => 3 } },
      { name: "Member",    data: { date => 0 } },
      { name: "Unlimited", data: { date => 0 } }
    ]
    expected.zip(assigns(:data)).each do |e, a|
      assert_equal e[:name], a[:name], "Mismatching names. Expected #{e[:name]} got #{a[:name]}"
      e[:data].each_key do |k|
        assert (a[:data].key? k), "Missing date for #{e[:name]}: #{k}"
        assert_equal e[:data][k], a[:data][k], "Mismatching counts for #{e[:name]} on #{k}: Expected #{e[:data][k]} got #{a[:data][k]}"
      end
    end
  end

  test "registration form for student-only event shown when logged in" do
    sign_in users(:matthias)
    get :show, params: { id: events(:sko).id }
    assert_select "#basic-registration-form", true, "Should contain registration form"
  end

  test "registration form for student-only event hidden when logged out" do
    sign_out users(:matthias)
    get :show, params: { id: events(:twaalfurenloop).id }
    assert_select "#basic-registration-form", false, "Should not contain registration form"
  end
end


text:
/**
 * Created by nhatnk on 5/31/15.
 */

(function(){
  angular
    .module('BlendEdxApp')
    .service('userService', userService);

  userService.$inject = ['Restangular'];

  function userService(Restangular){
    return Restangular.service('users');
  }
}());


text:
package org.apache.helix.task;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.helix.controller.stages.ClusterDataCache;
import org.apache.helix.controller.stages.CurrentStateOutput;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.Message;
import org.apache.helix.model.Partition;
import org.apache.helix.model.ResourceAssignment;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.log4j.Logger;

/**
 * A TaskAssignmentCalculator for when a task group must be assigned according to partitions/states on a target
 * resource. Here, tasks are co-located according to where a resource's partitions are, as well as
 * (if desired) only where those partitions are in a given state.
 */
public class FixedTargetTaskAssignmentCalculator extends TaskAssignmentCalculator {
  private static final Logger LOG = Logger.getLogger(FixedTargetTaskAssignmentCalculator.class);

  @Override public Set<Integer> getAllTaskPartitions(JobConfig jobCfg, JobContext jobCtx,
      WorkflowConfig workflowCfg, WorkflowContext workflowCtx,
      Map<String, IdealState> idealStateMap) {
    return getAllTaskPartitions(getTgtIdealState(jobCfg, idealStateMap), jobCfg, jobCtx);
  }

  @Override
  public Map<String, SortedSet<Integer>> getTaskAssignment(CurrentStateOutput currStateOutput,
      ResourceAssignment prevAssignment, Collection<String> instances, JobConfig jobCfg,
      JobContext jobContext, WorkflowConfig workflowCfg, WorkflowContext workflowCtx,
      Set<Integer> partitionSet, Map<String, IdealState> idealStateMap) {
    IdealState tgtIs = getTgtIdealState(jobCfg, idealStateMap);
    if (tgtIs == null) {
      LOG.warn("Missing target resource for the scheduled job!");
      return Collections.emptyMap();
    }
    Set<String> tgtStates = jobCfg.getTargetPartitionStates();
    return getTgtPartitionAssignment(currStateOutput, instances, tgtIs, tgtStates, partitionSet,
        jobContext);
  }

  /**
   * Gets the ideal state of the target resource of this job
   * @param jobCfg job config containing target resource id
   * @param idealStateMap the map of resource name map to ideal state
   * @return target resource ideal state, or null
   */
  private static IdealState getTgtIdealState(JobConfig jobCfg,
      Map<String, IdealState> idealStateMap) {
    String tgtResourceId = jobCfg.getTargetResource();
    return idealStateMap.get(tgtResourceId);
  }

  /**
   * Returns the set of all partition ids for a job.
   * If a set of partition ids was explicitly specified in the config, that is used. Otherwise, we
   * use the list of all partition ids from the target resource.
   * return empty set if target resource does not exist.
   */
  private static Set<Integer> getAllTaskPartitions(IdealState tgtResourceIs, JobConfig jobCfg,
      JobContext taskCtx) {
    Map<String, List<Integer>> currentTargets = taskCtx.getPartitionsByTarget();
    SortedSet<String> targetPartitions = Sets.newTreeSet();
    if (jobCfg.getTargetPartitions() != null) {
      targetPartitions.addAll(jobCfg.getTargetPartitions());
    } else {
      if (tgtResourceIs != null) {
        targetPartitions.addAll(tgtResourceIs.getPartitionSet());
      } else {
        LOG.warn("Missing target resource for the scheduled job!");
      }
    }

    Set<Integer> taskPartitions = Sets.newTreeSet();
    for (String pName : targetPartitions) {
      taskPartitions.addAll(getPartitionsForTargetPartition(pName, currentTargets, taskCtx));
    }
    return taskPartitions;
  }

  private static List<Integer> getPartitionsForTargetPartition(String targetPartition,
      Map<String, List<Integer>> currentTargets, JobContext jobCtx) {
    if (!currentTargets.containsKey(targetPartition)) {
      int nextId = jobCtx.getPartitionSet().size();
      jobCtx.setPartitionTarget(nextId, targetPartition);
      return Lists.newArrayList(nextId);
    } else {
      return currentTargets.get(targetPartition);
    }
  }

  /**
   * Get partition assignments for the target resource, but only for the partitions of interest.
   * @param currStateOutput The current state of the instances in the cluster.
   * @param instances The instances.
   * @param tgtIs The ideal state of the target resource.
   * @param tgtStates Only partitions in this set of states will be considered. If null, partitions
   *          do not need to
   *          be in any specific state to be considered.
   * @param includeSet The set of partitions to consider.
   * @return A map of instance vs set of partition ids assigned to that instance.
   */
  private static Map<String, SortedSet<Integer>> getTgtPartitionAssignment(
      CurrentStateOutput currStateOutput, Iterable<String> instances, IdealState tgtIs,
      Set<String> tgtStates, Set<Integer> includeSet, JobContext jobCtx) {
    Map<String, SortedSet<Integer>> result = new HashMap<String, SortedSet<Integer>>();
    for (String instance : instances) {
      result.put(instance, new TreeSet<Integer>());
    }

    Map<String, List<Integer>> partitionsByTarget = jobCtx.getPartitionsByTarget();
    for (String pName : tgtIs.getPartitionSet()) {
      List<Integer> partitions = partitionsByTarget.get(pName);
      if (partitions == null || partitions.size() < 1) {
        continue;
      }
      int pId = partitions.get(0);
      if (includeSet.contains(pId)) {
        for (String instance : instances) {
          Message pendingMessage =
              currStateOutput.getPendingState(tgtIs.getResourceName(), new Partition(pName),
                  instance);
          if (pendingMessage != null) {
            continue;
          }

          String s =
              currStateOutput.getCurrentState(tgtIs.getResourceName(), new Partition(pName),
                  instance);
          if (s != null && (tgtStates == null || tgtStates.contains(s))) {
            result.get(instance).add(pId);
          }
        }
      }
    }

    return result;
  }
}


text:
'use strict';

const common = require('../common');
const { Worker } = require('worker_threads');

new Worker("require('trace_events')", { eval: true })
  .on('error', common.expectsError({
    code: 'ERR_TRACE_EVENTS_UNAVAILABLE',
    name: 'Error'
  }));


text:
<?php namespace Proper;

class Exception
extends \Exception
{
	protected $property;
	protected $action;

	public function __construct(Property $property, Action $action = null, $message, $previous = null)
	{
		parent::__construct($message, null, $previous);
		$this->property = $property;
		$this->action = $action;
	}
}


text:
Flask Auth
===========

This module provides a framework for doing authentication within Flask.


text:
package com.resultnotifier.main.ui.main;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.resultnotifier.main.AppState;
import com.resultnotifier.main.db.DatabaseManager;
import com.resultnotifier.main.notification.FCMTokenReceiverService;
import com.resultnotifier.main.notification.FCMTokenUpdaterService;
import com.resultnotifier.main.ui.drawer.NavDrawerItem;
import com.resultnotifier.main.ui.drawer.NavDrawerListAdapter;
import com.resultnotifier.main.R;
import com.resultnotifier.main.service.RENServiceClient;
import com.resultnotifier.main.ui.filter.FilterActivity;
import com.resultnotifier.main.ui.filter.FilterItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "REN_MainActivity";
    private static int[] mColors;
    private static Snackbar mSnackbar;
    private MainFragment mCurrentFragment;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private String[] mNavMenuTitles;
    private NavDrawerListAdapter mAdapter;
    private Toolbar mToolbar;
    private DatabaseManager mDatabaseManager;
    private RENServiceClient mRenServiceClient;

    public static Snackbar getmSnackbar() {
        return MainActivity.mSnackbar;
    }

    public static void setmSnackbar(Snackbar mSnackbar) {
        MainActivity.mSnackbar = mSnackbar;
    }

    public static int getRandomColor() {
        return mColors[(int) (Math.random() * mColors.length)];
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "Creating MainActivity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mmain);

        mRenServiceClient = AppState.getRenServiceClient(getApplicationContext());

        fetchDataTypes();

        mToolbar = (Toolbar) findViewById(R.id.mtoolbar);
        setSupportActionBar(mToolbar);

        final Resources resources = getResources();

        mColors = resources.getIntArray(R.array.dataType_icon_bg_colors);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        mNavMenuTitles = resources.getStringArray(R.array.nav_drawer_items);
        final TypedArray navMenuIcons = resources.obtainTypedArray(R.array.nav_drawer_icons);
        final ArrayList<NavDrawerItem> navDrawerItems = new ArrayList<>(mNavMenuTitles.length);
        for (int i = 0; i < mNavMenuTitles.length; i++) {
            navDrawerItems.add(new NavDrawerItem(mNavMenuTitles[i],
                    navMenuIcons.getResourceId(i, -1)));
        }
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
        mAdapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
        mDrawerList.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                mToolbar,
                R.string.app_name,
                R.string.app_name
        );

        mDrawerLayout.addDrawerListener(mDrawerToggle);
        if (savedInstanceState == null) {
            displayView(0);
        }

        mDatabaseManager = AppState.getDatabaseManager(getApplicationContext());
        updateFcmToken();

        getSupportActionBar().setHomeButtonEnabled(true);
        Log.i(TAG, "MainActivity created");
    }

    private void updateFcmToken() {
        Log.i(TAG, "Requesting to update FCM token");
        final Intent fcmTokeUpdaterServiceIntent =
                new Intent(this, FCMTokenUpdaterService.class);
        startService(fcmTokeUpdaterServiceIntent);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */
    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_filter:
                Intent intent = new Intent(this, FilterActivity.class);
                startActivityForResult(intent, 0);
                this.overridePendingTransition(R.anim.enter_from_right,
                        R.anim.leave_to_left);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (mCurrentFragment != null) {
                Log.e(TAG, "back to main activity");
                mCurrentFragment.refresh();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
    }

    private void fetchDataTypes() {
        Log.i(TAG, "Requesting data types");
        mRenServiceClient.fetchDataTypes(new RENServiceClient.FetchDataTypesCallback() {
            @Override
            public void onSuccess(final List<String> dataTypes) {
                saveDataTypes(dataTypes);
            }

            @Override
            public void onError(final int error) {
                Log.i(TAG, "Unable to fetch data types. error=" + error);
            }
        });
    }

    public RENServiceClient getRENServiceClient() {
        return mRenServiceClient;
    }

    private void saveDataTypes(final List<String> dataTypes) {
        for (final String dataType : dataTypes) {
            final FilterItem filterItem = new FilterItem(dataType, true);
            if (!mDatabaseManager.isDataTypeAvailable(dataType)) {
                mDatabaseManager.addDataType(filterItem);
            }
        }
    }

    /**
     * Displaying fragment view for selected nav drawer list item
     */
    private void displayView(int position) {
        mCurrentFragment = null;
        switch (position) {
            case 0:
                mCurrentFragment = new PublishedFragment();
                break;
            case 1:
                mCurrentFragment = new TopmostFragment();
                break;
            case 2:
                mCurrentFragment = new RecentFragment();
                break;
            case 3:
                mCurrentFragment = new SavedFragment();
                break;
            default:
                break;
        }

        Log.i(TAG, "Displaying Fragment. position=" + position);
        if (mCurrentFragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, mCurrentFragment).commit();
            mDrawerList.setItemChecked(position, true);
            getSupportActionBar().setTitle(mNavMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            Log.e(TAG, "Error in creating fragment. position=" + position);
        }
    }

    /**
     * Slide menu item click listener
     */
    private class SlideMenuClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            displayView(position);
        }
    }
}