text:
#ifndef QTREEVIEW_P_H
#define QTREEVIEW_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "private/qabstractitemview_p.h"
#include <QtCore/qvariantanimation.h>
#include <QtCore/qabstractitemmodel.h>

#ifndef QT_NO_TREEVIEW

QT_BEGIN_NAMESPACE

struct QTreeViewItem
{
    QTreeViewItem() : parentItem(-1), expanded(false), spanning(false), hasChildren(false),
                      hasMoreSiblings(false), total(0), level(0), height(0) {}
    QModelIndex index; // we remove items whenever the indexes are invalidated
    int parentItem; // parent item index in viewItems
    uint expanded : 1;
    uint spanning : 1;
    uint hasChildren : 1; // if the item has visible children (even if collapsed)
    uint hasMoreSiblings : 1;
    uint total : 28; // total number of children visible
    uint level : 16; // indentation
    int height : 16; // row height
};

Q_DECLARE_TYPEINFO(QTreeViewItem, Q_MOVABLE_TYPE);

class Q_GUI_EXPORT QTreeViewPrivate : public QAbstractItemViewPrivate
{
    Q_DECLARE_PUBLIC(QTreeView)
public:

    QTreeViewPrivate()
        : QAbstractItemViewPrivate(),
          header(0), indent(20), lastViewedItem(0), defaultItemHeight(-1),
          uniformRowHeights(false), rootDecoration(true),
          itemsExpandable(true), sortingEnabled(false),
          expandsOnDoubleClick(true),
          allColumnsShowFocus(false), current(0), spanning(false),
          animationsEnabled(false), columnResizeTimerID(0),
          autoExpandDelay(-1), hoverBranch(-1), geometryRecursionBlock(false), hasRemovedItems(false) {}

    ~QTreeViewPrivate() {}
    void initialize();

    QItemViewPaintPairs draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const;
    void adjustViewOptionsForIndex(QStyleOptionViewItemV4 *option, const QModelIndex &current) const;

#ifndef QT_NO_ANIMATION
    struct AnimatedOperation : public QVariantAnimation
    {
        int item;
        QPixmap before;
        QPixmap after;
        QWidget *viewport;
        AnimatedOperation() : item(0) { setEasingCurve(QEasingCurve::InOutQuad); }
        int top() const { return startValue().toInt(); }
        QRect rect() const { QRect rect = viewport->rect(); rect.moveTop(top()); return rect; }
        void updateCurrentValue(const QVariant &) { viewport->update(rect()); }
        void updateState(State state, State) { if (state == Stopped) before = after = QPixmap(); }
    } animatedOperation;
    void prepareAnimatedOperation(int item, QVariantAnimation::Direction d);
    void beginAnimatedOperation();
    void drawAnimatedOperation(QPainter *painter) const;
    QPixmap renderTreeToPixmapForAnimation(const QRect &rect) const;
    void _q_endAnimatedOperation();
#endif //QT_NO_ANIMATION

    void expand(int item, bool emitSignal);
    void collapse(int item, bool emitSignal);

    void _q_columnsAboutToBeRemoved(const QModelIndex &, int, int);
    void _q_columnsRemoved(const QModelIndex &, int, int);
    void _q_modelAboutToBeReset();
    void _q_sortIndicatorChanged(int column, Qt::SortOrder order);
    void _q_modelDestroyed();

    void layout(int item, bool recusiveExpanding = false, bool afterIsUninitialized = false);

    int pageUp(int item) const;
    int pageDown(int item) const;

    int itemHeight(int item) const;
    int indentationForItem(int item) const;
    int coordinateForItem(int item) const;
    int itemAtCoordinate(int coordinate) const;

    int viewIndex(const QModelIndex &index) const;
    QModelIndex modelIndex(int i, int column = 0) const;

    void insertViewItems(int pos, int count, const QTreeViewItem &viewItem);
    void removeViewItems(int pos, int count);
#if 0
    bool checkViewItems() const;
#endif

    int firstVisibleItem(int *offset = 0) const;
    int columnAt(int x) const;
    bool hasVisibleChildren( const QModelIndex& parent) const;

    bool expandOrCollapseItemAtPos(const QPoint &pos);

    void updateScrollBars();

    int itemDecorationAt(const QPoint &pos) const;
    QRect itemDecorationRect(const QModelIndex &index) const;

    QList<QPair<int, int> > columnRanges(const QModelIndex &topIndex, const QModelIndex &bottomIndex) const;
    void select(const QModelIndex &start, const QModelIndex &stop, QItemSelectionModel::SelectionFlags command);

    QPair<int,int> startAndEndColumns(const QRect &rect) const;

    void updateChildCount(const int parentItem, const int delta);

    void paintAlternatingRowColors(QPainter *painter, QStyleOptionViewItemV4 *option, int y, int bottom) const;

    // logicalIndices: vector of currently visibly logical indices
    // itemPositions: vector of view item positions (beginning/middle/end/onlyone)
    void calcLogicalIndices(QVector<int> *logicalIndices, QVector<QStyleOptionViewItemV4::ViewItemPosition> *itemPositions) const;

    QHeaderView *header;
    int indent;

    mutable QVector<QTreeViewItem> viewItems;
    mutable int lastViewedItem;
    int defaultItemHeight; // this is just a number; contentsHeight() / numItems
    bool uniformRowHeights; // used when all rows have the same height
    bool rootDecoration;
    bool itemsExpandable;
    bool sortingEnabled;
    bool expandsOnDoubleClick;
    bool allColumnsShowFocus;

    // used for drawing
    mutable QPair<int,int> leftAndRight;
    mutable int current;
    mutable bool spanning;

    // used when expanding and collapsing items
    QSet<QPersistentModelIndex> expandedIndexes;
    bool animationsEnabled;

    inline bool storeExpanded(const QPersistentModelIndex &idx) {
        if (expandedIndexes.contains(idx))
            return false;
        expandedIndexes.insert(idx);
        return true;
    }

    inline bool isIndexExpanded(const QModelIndex &idx) const {
        //We first check if the idx is a QPersistentModelIndex, because creating QPersistentModelIndex is slow
        return isPersistent(idx) && expandedIndexes.contains(idx);
    }

    // used when hiding and showing items
    QSet<QPersistentModelIndex> hiddenIndexes;

    inline bool isRowHidden(const QModelIndex &idx) const {
        //We first check if the idx is a QPersistentModelIndex, because creating QPersistentModelIndex is slow
        return isPersistent(idx) && hiddenIndexes.contains(idx);
    }

    inline bool isItemHiddenOrDisabled(int i) const {
        if (i < 0 || i >= viewItems.count())
            return false;
        const QModelIndex index = viewItems.at(i).index;
        return isRowHidden(index) || !isIndexEnabled(index);
    }

    inline int above(int item) const
        { int i = item; while (isItemHiddenOrDisabled(--item)){} return item < 0 ? i : item; }
    inline int below(int item) const
        { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.count() ? i : item; }
    inline void invalidateHeightCache(int item) const
        { viewItems[item].height = 0; }

    inline int accessibleTable2Index(const QModelIndex &index) const {
        return (viewIndex(index) + (header ? 1 : 0)) * model->columnCount()+index.column() + 1;
    }

    // used for spanning rows
    QVector<QPersistentModelIndex> spanningIndexes;

    // used for updating resized columns
    int columnResizeTimerID;
    QList<int> columnsToUpdate;

    // used for the automatic opening of nodes during DND
    int autoExpandDelay;
    QBasicTimer openTimer;

    // used for drawing hilighted expand/collapse indicators
    int hoverBranch;

    // used for blocking recursion when calling setViewportMargins from updateGeometries
    bool geometryRecursionBlock;

    // If we should clean the set
    bool hasRemovedItems;
};

QT_END_NAMESPACE

#endif // QT_NO_TREEVIEW

#endif // QTREEVIEW_P_H


text:
// Code generated by protoc-gen-go.
// source: route_guide.proto
// DO NOT EDIT!

/*
Package routeguide is a generated protocol buffer package.

It is generated from these files:
	route_guide.proto

It has these top-level messages:
	Point
	Rectangle
	Feature
	RouteNote
	RouteSummary
*/
package routeguide

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import (
	context "context"
	grpc "grpc.go4.org"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
type Point struct {
	Latitude  int32 `protobuf:"varint,1,opt,name=latitude" json:"latitude,omitempty"`
	Longitude int32 `protobuf:"varint,2,opt,name=longitude" json:"longitude,omitempty"`
}

func (m *Point) Reset()                    { *m = Point{} }
func (m *Point) String() string            { return proto.CompactTextString(m) }
func (*Point) ProtoMessage()               {}
func (*Point) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
type Rectangle struct {
	// One corner of the rectangle.
	Lo *Point `protobuf:"bytes,1,opt,name=lo" json:"lo,omitempty"`
	// The other corner of the rectangle.
	Hi *Point `protobuf:"bytes,2,opt,name=hi" json:"hi,omitempty"`
}

func (m *Rectangle) Reset()                    { *m = Rectangle{} }
func (m *Rectangle) String() string            { return proto.CompactTextString(m) }
func (*Rectangle) ProtoMessage()               {}
func (*Rectangle) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }

func (m *Rectangle) GetLo() *Point {
	if m != nil {
		return m.Lo
	}
	return nil
}

func (m *Rectangle) GetHi() *Point {
	if m != nil {
		return m.Hi
	}
	return nil
}

// A feature names something at a given point.
//
// If a feature could not be named, the name is empty.
type Feature struct {
	// The name of the feature.
	Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
	// The point where the feature is detected.
	Location *Point `protobuf:"bytes,2,opt,name=location" json:"location,omitempty"`
}

func (m *Feature) Reset()                    { *m = Feature{} }
func (m *Feature) String() string            { return proto.CompactTextString(m) }
func (*Feature) ProtoMessage()               {}
func (*Feature) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }

func (m *Feature) GetLocation() *Point {
	if m != nil {
		return m.Location
	}
	return nil
}

// A RouteNote is a message sent while at a given point.
type RouteNote struct {
	// The location from which the message is sent.
	Location *Point `protobuf:"bytes,1,opt,name=location" json:"location,omitempty"`
	// The message to be sent.
	Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
}

func (m *RouteNote) Reset()                    { *m = RouteNote{} }
func (m *RouteNote) String() string            { return proto.CompactTextString(m) }
func (*RouteNote) ProtoMessage()               {}
func (*RouteNote) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }

func (m *RouteNote) GetLocation() *Point {
	if m != nil {
		return m.Location
	}
	return nil
}

// A RouteSummary is received in response to a RecordRoute rpc.
//
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
type RouteSummary struct {
	// The number of points received.
	PointCount int32 `protobuf:"varint,1,opt,name=point_count,json=pointCount" json:"point_count,omitempty"`
	// The number of known features passed while traversing the route.
	FeatureCount int32 `protobuf:"varint,2,opt,name=feature_count,json=featureCount" json:"feature_count,omitempty"`
	// The distance covered in metres.
	Distance int32 `protobuf:"varint,3,opt,name=distance" json:"distance,omitempty"`
	// The duration of the traversal in seconds.
	ElapsedTime int32 `protobuf:"varint,4,opt,name=elapsed_time,json=elapsedTime" json:"elapsed_time,omitempty"`
}

func (m *RouteSummary) Reset()                    { *m = RouteSummary{} }
func (m *RouteSummary) String() string            { return proto.CompactTextString(m) }
func (*RouteSummary) ProtoMessage()               {}
func (*RouteSummary) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }

func init() {
	proto.RegisterType((*Point)(nil), "routeguide.Point")
	proto.RegisterType((*Rectangle)(nil), "routeguide.Rectangle")
	proto.RegisterType((*Feature)(nil), "routeguide.Feature")
	proto.RegisterType((*RouteNote)(nil), "routeguide.RouteNote")
	proto.RegisterType((*RouteSummary)(nil), "routeguide.RouteSummary")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// Client API for RouteGuide service

type RouteGuideClient interface {
	// A simple RPC.
	//
	// Obtains the feature at a given position.
	//
	// A feature with an empty name is returned if there's no feature at the given
	// position.
	GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error)
	// A server-to-client streaming RPC.
	//
	// Obtains the Features available within the given Rectangle.  Results are
	// streamed rather than returned at once (e.g. in a response message with a
	// repeated field), as the rectangle may cover a large area and contain a
	// huge number of features.
	ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error)
	// A client-to-server streaming RPC.
	//
	// Accepts a stream of Points on a route being traversed, returning a
	// RouteSummary when traversal is completed.
	RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error)
	// A Bidirectional streaming RPC.
	//
	// Accepts a stream of RouteNotes sent while a route is being traversed,
	// while receiving other RouteNotes (e.g. from other users).
	RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error)
}

type routeGuideClient struct {
	cc *grpc.ClientConn
}

func NewRouteGuideClient(cc *grpc.ClientConn) RouteGuideClient {
	return &routeGuideClient{cc}
}

func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) {
	out := new(Feature)
	err := grpc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[0], c.cc, "/routeguide.RouteGuide/ListFeatures", opts...)
	if err != nil {
		return nil, err
	}
	x := &routeGuideListFeaturesClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type RouteGuide_ListFeaturesClient interface {
	Recv() (*Feature, error)
	grpc.ClientStream
}

type routeGuideListFeaturesClient struct {
	grpc.ClientStream
}

func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) {
	m := new(Feature)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[1], c.cc, "/routeguide.RouteGuide/RecordRoute", opts...)
	if err != nil {
		return nil, err
	}
	x := &routeGuideRecordRouteClient{stream}
	return x, nil
}

type RouteGuide_RecordRouteClient interface {
	Send(*Point) error
	CloseAndRecv() (*RouteSummary, error)
	grpc.ClientStream
}

type routeGuideRecordRouteClient struct {
	grpc.ClientStream
}

func (x *routeGuideRecordRouteClient) Send(m *Point) error {
	return x.ClientStream.SendMsg(m)
}

func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) {
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	m := new(RouteSummary)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[2], c.cc, "/routeguide.RouteGuide/RouteChat", opts...)
	if err != nil {
		return nil, err
	}
	x := &routeGuideRouteChatClient{stream}
	return x, nil
}

type RouteGuide_RouteChatClient interface {
	Send(*RouteNote) error
	Recv() (*RouteNote, error)
	grpc.ClientStream
}

type routeGuideRouteChatClient struct {
	grpc.ClientStream
}

func (x *routeGuideRouteChatClient) Send(m *RouteNote) error {
	return x.ClientStream.SendMsg(m)
}

func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) {
	m := new(RouteNote)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Server API for RouteGuide service

type RouteGuideServer interface {
	// A simple RPC.
	//
	// Obtains the feature at a given position.
	//
	// A feature with an empty name is returned if there's no feature at the given
	// position.
	GetFeature(context.Context, *Point) (*Feature, error)
	// A server-to-client streaming RPC.
	//
	// Obtains the Features available within the given Rectangle.  Results are
	// streamed rather than returned at once (e.g. in a response message with a
	// repeated field), as the rectangle may cover a large area and contain a
	// huge number of features.
	ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error
	// A client-to-server streaming RPC.
	//
	// Accepts a stream of Points on a route being traversed, returning a
	// RouteSummary when traversal is completed.
	RecordRoute(RouteGuide_RecordRouteServer) error
	// A Bidirectional streaming RPC.
	//
	// Accepts a stream of RouteNotes sent while a route is being traversed,
	// while receiving other RouteNotes (e.g. from other users).
	RouteChat(RouteGuide_RouteChatServer) error
}

func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) {
	s.RegisterService(&_RouteGuide_serviceDesc, srv)
}

func _RouteGuide_GetFeature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(Point)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(RouteGuideServer).GetFeature(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/routeguide.RouteGuide/GetFeature",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(RouteGuideServer).GetFeature(ctx, req.(*Point))
	}
	return interceptor(ctx, in, info, handler)
}

func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(Rectangle)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream})
}

type RouteGuide_ListFeaturesServer interface {
	Send(*Feature) error
	grpc.ServerStream
}

type routeGuideListFeaturesServer struct {
	grpc.ServerStream
}

func (x *routeGuideListFeaturesServer) Send(m *Feature) error {
	return x.ServerStream.SendMsg(m)
}

func _RouteGuide_RecordRoute_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(RouteGuideServer).RecordRoute(&routeGuideRecordRouteServer{stream})
}

type RouteGuide_RecordRouteServer interface {
	SendAndClose(*RouteSummary) error
	Recv() (*Point, error)
	grpc.ServerStream
}

type routeGuideRecordRouteServer struct {
	grpc.ServerStream
}

func (x *routeGuideRecordRouteServer) SendAndClose(m *RouteSummary) error {
	return x.ServerStream.SendMsg(m)
}

func (x *routeGuideRecordRouteServer) Recv() (*Point, error) {
	m := new(Point)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream})
}

type RouteGuide_RouteChatServer interface {
	Send(*RouteNote) error
	Recv() (*RouteNote, error)
	grpc.ServerStream
}

type routeGuideRouteChatServer struct {
	grpc.ServerStream
}

func (x *routeGuideRouteChatServer) Send(m *RouteNote) error {
	return x.ServerStream.SendMsg(m)
}

func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) {
	m := new(RouteNote)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _RouteGuide_serviceDesc = grpc.ServiceDesc{
	ServiceName: "routeguide.RouteGuide",
	HandlerType: (*RouteGuideServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "GetFeature",
			Handler:    _RouteGuide_GetFeature_Handler,
		},
	},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "ListFeatures",
			Handler:       _RouteGuide_ListFeatures_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "RecordRoute",
			Handler:       _RouteGuide_RecordRoute_Handler,
			ClientStreams: true,
		},
		{
			StreamName:    "RouteChat",
			Handler:       _RouteGuide_RouteChat_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
	Metadata: "route_guide.proto",
}

func init() { proto.RegisterFile("route_guide.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
	// 404 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x53, 0xc1, 0x4a, 0xeb, 0x40,
	0x14, 0xed, 0xf4, 0xb5, 0xaf, 0x2f, 0x37, 0x79, 0x3c, 0x3a, 0x0f, 0x21, 0x54, 0x41, 0x8d, 0x9b,
	0x6e, 0x0c, 0xa5, 0x82, 0x4b, 0xc5, 0x16, 0xec, 0xa6, 0x48, 0x8d, 0xdd, 0x97, 0x31, 0x19, 0xd3,
	0x81, 0x24, 0x13, 0x92, 0x09, 0xe8, 0x07, 0xf8, 0x05, 0xfe, 0xb0, 0x93, 0xc9, 0xa4, 0x4d, 0xb5,
	0xc5, 0x5d, 0xe6, 0xdc, 0x73, 0xee, 0x3d, 0xf7, 0x5c, 0x02, 0xfd, 0x8c, 0x17, 0x82, 0xae, 0xc2,
	0x82, 0x05, 0xd4, 0x4d, 0x33, 0x2e, 0x38, 0x06, 0x05, 0x29, 0xc4, 0xb9, 0x83, 0xee, 0x82, 0xb3,
	0x44, 0xe0, 0x01, 0xfc, 0x89, 0x88, 0x60, 0xa2, 0x08, 0xa8, 0x8d, 0xce, 0xd0, 0xb0, 0xeb, 0x6d,
	0xde, 0xf8, 0x04, 0x8c, 0x88, 0x27, 0x61, 0x55, 0x6c, 0xab, 0xe2, 0x16, 0x70, 0x1e, 0xc1, 0xf0,
	0xa8, 0x2f, 0x48, 0x12, 0x46, 0x14, 0x9f, 0x43, 0x3b, 0xe2, 0xaa, 0x81, 0x39, 0xee, 0xbb, 0xdb,
	0x41, 0xae, 0x9a, 0xe2, 0xc9, 0x62, 0x49, 0x59, 0x33, 0xd5, 0x66, 0x3f, 0x65, 0xcd, 0x9c, 0x39,
	0xf4, 0xee, 0x29, 0x11, 0x45, 0x46, 0x31, 0x86, 0x4e, 0x42, 0xe2, 0xca, 0x93, 0xe1, 0xa9, 0x6f,
	0x7c, 0x29, 0xbd, 0x72, 0x5f, 0xba, 0xe3, 0xc9, 0xe1, 0x3e, 0x1b, 0x8a, 0xb3, 0x94, 0x06, 0xcb,
	0xea, 0x03, 0x17, 0xbb, 0x5a, 0xf4, 0xa3, 0x16, 0xdb, 0xd0, 0x8b, 0x69, 0x9e, 0x93, 0xb0, 0x5a,
	0xdc, 0xf0, 0xea, 0xa7, 0xf3, 0x81, 0xc0, 0x52, 0x6d, 0x9f, 0x8a, 0x38, 0x26, 0xd9, 0x1b, 0x3e,
	0x05, 0x33, 0x2d, 0xd5, 0x2b, 0x9f, 0x17, 0x89, 0xd0, 0x21, 0x82, 0x82, 0xa6, 0x25, 0x82, 0x2f,
	0xe0, 0xef, 0x4b, 0xb5, 0x95, 0xa6, 0x54, 0x51, 0x5a, 0x1a, 0xac, 0x48, 0xf2, 0x0e, 0x01, 0xcb,
	0x65, 0x9a, 0x3e, 0xb5, 0x7f, 0x55, 0x77, 0xa8, 0xdf, 0x32, 0x39, 0x8b, 0x46, 0x24, 0xcd, 0x69,
	0xb0, 0x12, 0x4c, 0x66, 0xd2, 0x51, 0x75, 0x53, 0x63, 0x4b, 0x09, 0x8d, 0xdf, 0xdb, 0x00, 0xca,
	0xd5, 0xac, 0x5c, 0x07, 0x5f, 0x03, 0xcc, 0xa8, 0xa8, 0xb3, 0xfc, 0xbe, 0xe9, 0xe0, 0x7f, 0x13,
	0xd2, 0x3c, 0xa7, 0x85, 0x6f, 0xc0, 0x9a, 0xcb, 0xa9, 0x1a, 0xc8, 0xf1, 0x51, 0x93, 0xb6, 0xb9,
	0xf6, 0x01, 0xf5, 0x08, 0x49, 0xbd, 0x29, 0x59, 0x3c, 0x0b, 0x94, 0x97, 0x7d, 0x83, 0xed, 0x9d,
	0x8e, 0x8d, 0x1c, 0x9d, 0xd6, 0x10, 0xe1, 0x5b, 0x7d, 0xb2, 0xe9, 0x9a, 0x88, 0x2f, 0xc3, 0xeb,
	0x4b, 0x0e, 0xf6, 0xc3, 0xa5, 0x7c, 0x84, 0x26, 0x23, 0x38, 0x66, 0xdc, 0x0d, 0xb3, 0xd4, 0x77,
	0xe9, 0x2b, 0x89, 0xd3, 0x88, 0xe6, 0x0d, 0xfa, 0xe4, 0xdf, 0x36, 0xa3, 0x45, 0xf9, 0x4f, 0x2c,
	0xd0, 0xf3, 0x6f, 0xf5, 0x73, 0x5c, 0x7d, 0x06, 0x00, 0x00, 0xff, 0xff, 0xc8, 0xe4, 0xef, 0xe6,
	0x31, 0x03, 0x00, 0x00,
}

redpajama_set_name: RedPajamaGithub


text:
js-css-min-django
=================

This is a python script for automated merge and minify of JS and CSS files.

Optionally it can parse django template tags embeded into css and js files.

And, if you have [lesscpy](https://github.com/lesscpy/lesscpy) installed, you can compiled .LESS to .CSS before merging.

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

```bash
$pip install jscssmin --target $PYTHONPATH --install-option="--install-scripts=~/bin"
```

Be sure to point scripts to a place here you have write access **and** is in your path.

Example with a django project
-----------------------------

During development I simply use django tags like *{% url ... %}* and *{% static ... %}* on my .js and .css files to define dynamic url to views and images of my project. At this point the .js and .css are placed into the templates directory of my app so I can *{% include ... %}* it to my .html templates and have the tags rendered to final urls. Of course the js and css will appear inline with the HTML content. For development I think this is fine.

On deploy you usually want all your javascript and styling to be in a single external file.

Here is how this script can help you with that:

On my base.html template I usually have something like this:

```html
<head>
...
<!-- css -->
{% if debug %}
  <link href="{% static 'tasks/css/fixtypeahead.css' %}" rel="stylesheet">
  <link rel="stylesheet/less" type="text/css" href="{% static 'message/css/message.less' %}" />
  <link rel="stylesheet/less" type="text/css" href="{% static 'tasks/css/tasks.less' %}" />
  <link rel="stylesheet/less" type="text/css" href="{% static 'tasks/css/compactform.less' %}" />
{% else %}
  <link href="{% static 'tasks/css/compactform.css' %}" rel="stylesheet">
  <link href="{% static 'css/mydeploycss.min.css' %}" rel="stylesheet">
{% endif %}
{% block extracss %}{% endblock %}

<!-- js -->
{% if debug %}
  <!-- you need this only while debugging with less files -->
  <script type="text/javascript" src="{% static 'js/less-1.6.2.min.js' %}"></script>
  <script src="{% static 'js/code1.js' %}"></script>
  <script src="{% static 'js/code2.js' %}"></script>
  <script>
    // js bellow contains django tags inside
    {% include 'tasks/code3template.js' %}
    {% include 'tasks/codentemplate.js' %}
    {% include 'message/moretemplatecode.js' %}
  </script>
{% else %}
  <script src="{% static 'js/deploycode.min.js' %}"></script>
{% endif %}
{% block extrajs %}{% endblock %}
...
</head>
```

Check out [less.js](https://github.com/less/less.js) for a less compiler at client side.

Create a file named *jscssmin.yaml* next to your manage.py (if using django, otherwise put this file in your root). Here's a example:

```yaml
---
config: myapp.settings
path:
    - /home/username/apps_wsgi/myapp
    #more paths as you need
blocks:
    my js:
        static:
            - static/js/code1.js
            - static/js/code2.js
        template:
            - tasks/templates/tasks/code3template.js
            - tasks/templates/tasks/codentemplate.js
            - message/templates/message/moretemplatecode.js
        #all static and rendered template JS will be merged, minified and saved to:
        jsmin: static/js/deploycode.min.js
    my css:
        static:
            - tasks/static/tasks/css/fixtypeahead.css
        less:
            - message/static/message/css/message.less
            - tasks/static/tasks/css/tasks.less
        #the static css and the css compiled from less files are merged, minified and saved to:
        cssmin: static/css/mydeploycss.min.css
    compact:
        less:
            - tasks/static/tasks/css/compactform.less
        #the single less is compiled to css and saved as is to:
        full: tasks/static/tasks/css/compactform.css
...
```

Here we define a path to the django project and the settings.py file to use while rendering the template tags. *You only need to define those if you have tags inside .js or .css, if you don't then simply ignore both*.

In this case we have three blocks, *my js*, *my css* and *compact*.

For the first block all five javascript files are going to be merged, minified and saved to a single *deploycode.min.js* file. (Yes, the 3 files under *template* will be rendered before merge)

For the second block we have one .css and two .less files merged and minified.

In our least block the compactform.less file is compiled to CSS and saved as is to a CSS file.

Is up to you not to mix JS and CSS/LESS inside a single block.

Once you update/checkout the work copy of your django project on your server all you have to do is:

```bash
$jscssmin
Processing block: compact
Compiling LESS: tasks/static/tasks/css/compactform.less
Saving: tasks/static/tasks/css/compactform.css (0.17kB)

Processing block: my css
Merging: tasks/static/tasks/css/fixtypeahead.css
Compiling LESS: message/static/message/css/message.less
Compiling LESS: tasks/static/tasks/css/tasks.less
Full merged size: 2.66kB
Minifying CSS...  Final: 72.7%
Saving: static/css/mydeploycss.min.css (1.93kB)

Processing block: my js
Merging: static/js/code1.js
Merging: static/js/code2.js
Merging template: tasks/templates/tasks/code3template.js
Merging template: tasks/templates/tasks/codentemplate.js
Merging template: message/templates/message/moretemplatecode.js
Full merged size: 34.66kB
Minifying JS...  Final: 50.1%
Saving: static/js/deploycode.min.js (17.35kB)

$python manage.py collectstatic
$touch /path/to/yourwsgi.wsgi
```

Ok, this least step can change on your server, but that's the overall idea...

Also, you can use the option *--images* to optimise **all** *.PNG* and *.JPG* present on the directory tree starting where you executed this script (usualy your django project root). Like:

```bash
$python jscssmin.py --images
```

This will save a copy of all original images with *".original"* appended to its name and a smaller (hopefully), version will be saved with the original name. This script will ignore every file that already have a *.original* version present. To force this script to process every single file again use the option *--images-full*.

Non django project
------------------

No secret: simply create a *jscssmin.yaml* file here there is no definition of *config*, and define all static files you want to merge/minify. Without a defined *config* all files under *templates* are going to be ignorated.

Using as a minifier module
--------------------------

In another python script:
```python
import  jscssmin

#minify JS from text to file
fulljstext = '<script>full code....</script>'
jscssmin.jsMin(fulljstext, 'path/to/min/code.js')

#minify CSS from text to file
fullcsstext = '<style>full styles...</style>'
jscssmin.cssMin(fullcsstext, 'path/to/min/style.css')

#minify a JPG image
jscssmin.jpgMin('path/to/image.jpg')

#minify a PNG image
jscssmin.pngMin('path/to/image.png')
```

All four functions used above are only helpers to call some online minifer api. See below. **This script does not minify JS or CSS by itself, so you need to be online to execute it with success**.

Minifier
--------

This script uses some great online api provided by [@andychilton] for all minify action:
+ http://javascript-minifier.com
+ http://cssminifier.com
+ http://pngcrush.com
+ http://jpgoptimiser.com

[@andychilton]: http://twitter.com/andychilton


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="fr"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="fr"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="fr"> <![endif]-->
<!--[if gt IE 7]> <html class="no-js ie oldie" lang="fr"> <![endif]-->

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!--<html class="no-js" lang="fr"> <![endif]-->

<head>

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

<meta name="viewport" content="width=device-width, maximum-scale=1"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/carousel.js"></script>
<script type="text/javascript" src="js/navigation.js"></script>
<script type="text/javascript" src="js/smoothScroll.js"></script>
<script type="text/javascript" src="js/blocsAlign.js"></script>
<script type="text/javascript" src="js/mobileNavigation.js"></script>

<link href="css/style.css" type="text/css" rel="stylesheet"/>
<link href="css/styleSmartPhone.css" type="text/css" rel="stylesheet"/>

 <link rel="shortcut icon" href="pics/favicon.ico"/>

</head>


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SprkIconComponent } from '../../../sprk-icon/sprk-icon.component';
import { SprkLinkDirective } from '../../../../directives/sprk-link/sprk-link.directive';
import { SprkMastheadAccordionComponent } from './sprk-masthead-accordion.component';

describe('SprkMastheadAccordionComponent', () => {
  let component: SprkMastheadAccordionComponent;
  let fixture: ComponentFixture<SprkMastheadAccordionComponent>;
  let accordionElement: HTMLElement;
  let accordionNavElement: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SprkMastheadAccordionComponent,
        SprkIconComponent,
        SprkLinkDirective,
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SprkMastheadAccordionComponent);
    component = fixture.componentInstance;
    accordionElement = fixture.nativeElement.querySelector('ul');
    accordionNavElement = fixture.nativeElement.querySelector('nav');
  });

  it('should create itself', () => {
    expect(component).toBeTruthy();
  });

  it('should do nothing when additionalClasses has no value', () => {
    fixture.detectChanges();
    expect(accordionElement.classList.toString()).toEqual(
      'sprk-c-MastheadAccordion sprk-b-List sprk-b-List--bare',
    );
  });

  it('should add classes when additionalClasses has a value', () => {
    component.additionalClasses = 'sprk-u-man';
    fixture.detectChanges();
    expect(accordionElement.classList.toString()).toEqual(
      'sprk-c-MastheadAccordion sprk-b-List sprk-b-List--bare sprk-u-man',
    );
  });

  it('should add aria label when ariaLabel has a value', () => {
    component.ariaLabel = 'test';
    fixture.detectChanges();
    expect(accordionNavElement.getAttribute('aria-label')).toEqual('test');
  });

  it('should not add aria label when ariaLabel has no value', () => {
    fixture.detectChanges();
    expect(accordionNavElement.getAttribute('aria-label')).toBe(null);
  });

  it('should add data-id when idString has a value', () => {
    component.idString = 'test';
    fixture.detectChanges();
    expect(accordionNavElement.getAttribute('data-id')).toEqual('test');
  });

  it('should not add data-id when idString has no value', () => {
    fixture.detectChanges();
    expect(accordionNavElement.getAttribute('data-id')).toBe(null);
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Monoscape.Common.Model;
using System.Runtime.Serialization;

namespace Monoscape.LoadBalancerController.Api.Services.Dashboard.Model
{
    [DataContract]
    public class LbGetRequestQueueResponse : AbstractResponse
    {
        [DataMember]
        public List<ApplicationHttpRequest> RequestQueue { get; set; }
    }
}


text:
/* MicroJava Symbol Table Scopes */
package MicroJava;

class Scope {

    Scope outer; // parent scope
    Obj locals;  // local variables of this scope
    int nVars;   // number of variables in this scope
    int level;

    Scope(Scope outer, int level) {
        this.outer = outer;
        this.level = level;
    }
}


text:
const assert = require('assert');
const http = require('http');

const port = 3954;
const hostName = 'localhost';
const localUrl = `http://${hostName}:${port}`;
const localOptions = {
  hostname: 'localhost',
  port: port,
  method: 'GET'
};

const REQ = (moduleName) => require(`./../../${moduleName}`);

describe('POST', () => {
  let instance;
  before((done) => {
    instance = http.createServer((req, res) => res.end('ok')).listen(port);
    instance.on('listening', () => done())
  })

  after((done) => {
    instance.close();
    done();
  });

  const POST = REQ('src/POST');
  describe('#require', () => {
    it('returns a function', () => assert.equal(typeof POST, 'function'));
  });
});


text:
package com.hp.hpl.jena.graph.test;

import com.hp.hpl.jena.graph.*;

import junit.framework.TestSuite;

/**
     Tests for recursive sub-graph extraction.
     @author hedgehog
*/
public class TestGraphExtract extends GraphTestBase
	{
	public TestGraphExtract(String name)
		{ super( name ); }

	public static TestSuite suite()
		{ return new TestSuite( TestGraphExtract.class ); }

    public void testExtractNothing()
        {
        testExtract( "", "x", "" );
        testExtract( "", "x", "a R b" );
        testExtract( "", "x", "a R x" );
        testExtract( "","x", "a x y" );
        }

    public void testExtractOneLevel()
        {
        testExtract( "a R b", "a", "a R b" );
        testExtract("a R b; a R c", "a", "a R b; a R c" );
        testExtract( "a R b; a S d", "a", "a R b; a S d" );
        }

    public void testNoJunk()
        {
        testExtract( "a R b", "a", "a R b; x R y" );
        }

    public void testExtractTwoLevels()
        {
        testExtract( "a R b; b S c", "a", "a R b; b S c" );
        testExtract( "a R b; b S c", "a", "a R b; b S c; x P y" );
        testExtract( "a R b; b S c; b T d", "a", "a R b; b S c; b T d" );
        testExtract( "a R b; b S c; a T d", "a", "a R b; a T d; b S c" );
        }

    public void testExtractSeveralLevels()
        {
        testExtract( "a R b; b S c; c T d; d U e", "a", "a R b; b S c; c T d; d U e" );
        }

    public void testExtractNoLoop()
        {
        testExtract( "a R a", "a", "a R a" );
        testExtract( "a R b; b R a", "a", "a R b; b R a; z P a" );
        testExtract( "a R b; b S c; c T a", "a", "a R b; b S c; c T a; junk P junk" );
        }

    public void testTripleFilter()
        {
        assertTrue( TripleBoundary.stopAtAnonObject.stopAt( triple( "a R _b" ) ) );
        assertFalse( TripleBoundary.stopAtAnonObject.stopAt( triple( "a R b" ) ) );
        assertFalse( TripleBoundary.stopAtAnonObject.stopAt( triple( "a _R b" ) ) );
        assertFalse( TripleBoundary.stopAtAnonObject.stopAt( triple( "_a R b" ) ) );
        }

    public void testExtractBoundary()
        {
        testExtract( "a R b; b S _c", "a", "a R b; b S _c; _c T d", TripleBoundary.stopAtAnonObject );
        }

    /**
         This test exposed that the update-existing-graph functionality was broken
         if the target graph already contained any statements with a subject S
         appearing as subject in the source graph - no further Spo statements were
         added.
    */
    public void testPartialUpdate()
        {
        Graph source = graphWith( "a R b; b S e" );
        Graph dest = graphWith( "b R d" );
        GraphExtract e = new GraphExtract( TripleBoundary.stopNowhere );
        e.extractInto( dest, node( "a" ), source );
        assertIsomorphic( graphWith( "a R b; b S e; b R d" ), dest );
        }

    public void testExtract( String wanted, String node, String source )
        {
        testExtract( wanted, node, source, TripleBoundary.stopNowhere );
        }

    /**
    */
    private void testExtract( String wanted, String node, String source, TripleBoundary b )
        {
        assertIsomorphic( graphWith( wanted ), extract( node( node ), b, graphWith( source ) ) );
        }

    public Graph extract( Node node, TripleBoundary b, Graph graph )
        { return new GraphExtract( b ).extract( node, graph ); }

    }


text:
class ChefServerWebui::Main < ChefServerWebui::Application
end


text:
.. _deploy-environment-ug:

Deploy a New OpenStack Environment
==================================

After Fuel completes the installation,
point your browser to default Fuel UI
URL: `http://10.20.0.2:8000 <http://10.20.0.2:8000>`__.

Alternatively, point your browser
to the IP address and port number that you specified.

In the Fuel UI, create a new OpenStack environment.

#. Configure the network settings using the address plan.

#. Verify the network configuration by clicking **Verify Networks**.

#. In the **Settings** tab, modify additional options:

   * Access

   * OpenStack Components

   * Hypervisor type

   * Scheduler driver

   * Syslog

   * Storage

#. Assign a role for each node server.

#. Optionally, associate NICs with the OpenStack networks:

   #. Select the nodes.
   #. Click **Configure Interfaces**.
   #. Drag and drop the appropriate networks onto the physical interfaces.
   #. Click **Apply**.

#. Click **Deploy Changes**.
    Depending on your environment deployment of Mirantis OpenStack may take
    some time.

After you deployed Mirantis OpenStack, verify the configuration by
running the tests from the **Health Check** tab.

You must complete the following steps
to deploy your OpenStack environment.
After completing this stage, configure the parameters for deployment,
including networking, storage, and optional parameters.

+----+----------------------------+-------------------------------------------+
|    | Step Description           | Additional Information                    |
+====+============================+===========================================+
| 1  | Point your browser to the  | For example: http://10.20.0.2:8000/       |
|    | Fuel server (on port 8000) |                                           |
+----+----------------------------+-------------------------------------------+
| 2  | Click on the **New**       | The **Create a new OpenStack              |
|    | *OpenStack environment*    | Environment** wizard launches             |
|    | icon to create a new       | automatically.                            |
|    | environment.               |                                           |
+----+----------------------------+-------------------------------------------+
| 3  | Choose a name for your     | If you install Mirantis OpenStack, you can|
|    | environment and choose the | select Ubuntu Enterprise Linux or CentOS  |
|    | Operating System and       | OpenStack.                                |
|    | OpenStack distribution.    |                                           |
+----+----------------------------+-------------------------------------------+
| 4  | Choose your Deployment     | High Availability mode requires at        |
|    | Mode (Multi-node HA or non | least 3 nodes to be assigned as           |
|    | HA).                       | controllers.                              |
+----+----------------------------+-------------------------------------------+
| 5  | Choose your                | Current choices from the UI are           |
|    | :ref:`hypervisor-term`     | :ref:`kvm-term`, :ref:`qemu-term`, or     |
|    |                            | vcenter.                                  |
+----+----------------------------+-------------------------------------------+
| 6  | Select your network        | If you choose Nova-network, you can       |
|    | service (Nova-network,     | choose FlatDHCP or VLAN Manager later in  |
|    | Neutron with GRE           | the **Network** settings tab.             |
|    | segmentation or Neutron    |                                           |
|    | with VLAN segmentation.    |                                           |
+----+----------------------------+-------------------------------------------+
| 7  | Select your storage        | If you select **default**, then the Local |
|    | backend for Cinder.        | Volumes over iSCSI are used as backend for|
|    |                            | Cinder. If you select **Ceph**, you must  |
|    |                            | assign at least 2 nodes as Ceph-OSD nodes.|
+----+----------------------------+-------------------------------------------+
| 8  | Select your storage        | If you select **default**, then the local |
|    | backend for Glance.        | storage in non-HA mode and Swift in HA    |
|    |                            | mode is used as backend for Cinder. Swift |
|    |                            | will be automatically installed on the    |
|    |                            | controllers. If you select **Ceph**, you  |
|    |                            | must assign at least 2 nodes as Ceph-OSD  |
|    |                            | nodes.                                    |
+----+----------------------------+-------------------------------------------+
| 9  | Choose additional Platform | Sahara enables on-demand provisioning of  |
|    | Services.                  | Hadoop clusters on OpenStack.             |
|    |                            | Murano enables Windows-based datacenter   |
|    |                            | services to be deployed on OpenStack.     |
+----+----------------------------+-------------------------------------------+
| 10 | Select Create and click on | Additional configuration tabs appear.     |
|    | the icon with your named   |                                           |
|    | environment.               |                                           |
+----+----------------------------+-------------------------------------------+
| 11 | In **Nodes** tab, assign a | A node may act as a controller, compute,  |
|    | role or roles to each node | or storage node. You can combine          |
|    | server.                    | a storage role with a controller or       |
|    |                            | compute role.                             |
+----+----------------------------+-------------------------------------------+
| 12 | In **Network** tab,        | If you chose Neutron as your network      |
|    | configure the network      | service, additional sections are          |
|    | settings from the address  | available for setting your L2 and L3      |
|    | plan prepared earlier.     | configuration.                            |
+----+----------------------------+-------------------------------------------+
| 13 | Click **Verify Networks**  | This sends test frames and 802.1Q         |
|    | to check and confirm the   | tagged frames to each node server to      |
|    | network configuration.     | confirm connectivity.                     |
+----+----------------------------+-------------------------------------------+
| 14 | (Optional) In the          | You may also modify your choices for      |
|    | **Settings** tab, you can  | hypervisor, storage, and Platform         |
|    | configure or modify the    | Services configured before the            |
|    | options for Horizon        | deployment.                               |
|    | access, scheduler type,    |                                           |
|    | logging, and other         |                                           |
|    | OpenStack options.         |                                           |
+----+----------------------------+-------------------------------------------+
| 15 | Click the **Deploy**       | Mirantis OpenStack deployment may take    |
|    | **Changes** button.        | 15-60 minutes, depending on your the      |
|    |                            | selected options. You can monitor status  |
|    |                            | by opening the **Nodes** tab or by        |
|    |                            | checking individual node logs in the Logs |
|    |                            | tab.                                      |
+----+----------------------------+-------------------------------------------+
| 16 | Once deployed, run the     | You can run the test groups in parallel or|
|    | tests in the **Health**    | one at a time.                            |
|    | **Check** tab to confirm   |                                           |
|    | success.                   |                                           |
+----+----------------------------+-------------------------------------------+

After you complete these tasks, Mirantis OpenStack is ready to use.

In the following sections, you can view specific examples of deploying
Mirantis OpenStack, including complete switch configuration and cabling.

.. see also:: :ref:`Nova-network <novanetwork>`, :ref:`Neutron <neutron>`

Create a new environment
========================

.. image:: /_images/fuel-wizard.png
   :align: center
   :width: 70%

Network settings page
=====================

.. image:: /_images/fuel-network-settings.png
   :align: center
   :width: 70%

Settings page
=============

.. image:: /_images/fuel-settings1.png
   :align: center
   :width: 70%

.. image:: /_images/fuel-settings2.png
   :align: center
   :width: 70%

.. image:: /_images/fuel-settings3.png
   :align: center
   :width: 70%

.. image:: /_images/fuel-settings4.png
   :align: center
   :width: 70%

Add nodes to environment
========================

.. image:: /_images/fuel-nodes.png
   :align: center
   :width: 70%

Select discovered nodes
=======================

.. image:: /_images/fuel-nodes-selected.png
   :align: center
   :width: 70%

Node's network settings
=======================

.. image:: /_images/fuel-node-network.png
   :align: center
   :width: 70%


text:
A Promise is an object that's representing a potential future value, we just don't know what it will be _yet_.
When you have a Promise in hands, it promises you to get you a value back or an error.

## Promises vs callbacks
Two things are important to note why Promises are a more suitable solutions for asynchronous programming than callbacks.

The first thing is the inversion of inversion of control. Or simply put: restoring control to the calling code.
When you use callbacks, you invert the control of your asynchronous behaviour to some other external logic (could be your code but it could also be a third party library).
The issue with inversion of control is that since you're not in control anymore, you let someone else decide _when_ the asynchronous task will be over.
You also trust that third party code to call your callback in the right time and in the exact amount of time you're expecting.
Promises give you the control back because _you_ decide when and how the "callback" is called.

```javascript
// callback based code
function request(callback) {
  fetch(..., (error, result) => (
    callback(...) // What if this callback was called too soon? Or never called, or called twice...
  ));
}

request((error, result) => {
  // ...
});

// Promise based code.
function request() {
  return new Promise(...);
}

const someRequest = request().then(...);
```

The second thing you probably have heard of is "callback hell", when you need to subsequently call more than one asynchronous task. Often, you need to wait until one is done to start another one, which leads to deep nesting. It also makes it hard to run concurrent async code and wait until everything is done to keep going on something else.

```javascript
asyncTaskOne((error, result) => {
  asyncTaskTwo((error, result) => {
    asyncTaskThree((error, result) => {
      // ....
    });
  });
});
```

This gets hard to read and to reason about extremely quickly. Nesting often means unnecessary complexity in the code.
Instead, a promise based code would look like

```javascript
asyncTaskOne()
  .then(asyncTaskTwo)
  .then(asyncTaskThree);

// Or even better, if you the tasks are independent
Promise.all([
  asyncTaskOne,
  asyncTaskTwo,
  asyncTaskThree
]).then([resultOne, resultTwo, resultThree] => ...);
```

## How do Promises work?
Promises are immutable objects that can have three states:
- `Pending`
- `Fulfilled`
- `Rejected`

It always starts with the `pending` state (that's what you get right away after creating the promise) and will move to `fulfilled` or `rejected`. Once the state changed, it cannot change anymore due to their immutable behaviour.

- `Fulfilled` means the Promise has resolved with a value that is not an error.
- `Rejected` means the Promise has resolved with an error (whatever you were doing didn't work).

Based on their next state, a Promise will call one of its methods.
A Promise is what is called a "thenable", which means it has a `then` method on it. That method is being called
whenever the Promise gets resolved (error or not).

`then` takes two arguments (two functions called `onFulfill` and `onReject`), the second one being optional.
The first function will be called if the Promise gets fulfilled (resolved but didn't error out).
The second argument will be called (if provided) if the Promise gets rejected (resolved with an error).

Let's take a look at a _potential_ `then` signature:
```javascript
function then(onFulfill, onReject) { }
```

```javascript
Promise.resolve('hello world')
  .then(console.log); // 'hello world'
```

```javascript
Promise.reject('bad')
  .then(
    (result) => {
        // Never gets here...
    },
    (error) => {
        console.error(error); // 'bad'
    }
  )
```

Because it's optional, the second argument can be omitted. Although, if you don't provide an error handler,
javascript will swallow the error and never tell you what happened. In the future, rejected Promise will exit the node process with a non 0 code. Which is bad.

Last but not least, there is another way to deal with errors in Promises.
Promises have a `catch` method, which can act as an error-handler as well.

```javascript
Promise.reject('bad')
  .catch(error => console.error('Catching the error...'));
```

There are some differences between using a second error handler in the `then` or using `catch`.
Consider the following code:

```javascript
Promise.resolve(true)
  .then(
    result => Promise.reject(false),
    error => console.error('Couldn\'t catch the rejected promise') // This is never be called because the Promise already fulfilled.
  )
  .catch(error => console.error('Caught the rejected Promise')) // This is called because `then` returned a rejected promised
  .then(() => Promise.reject(false))
  .then(
    result => console.log('This is never called'),
    error => console.error('Caught the rejected Promise')
  )
  .catch(error => console.error('This is never called')) // Never called because we already handled the error before.
```

## All about `then` and how to use it efficiently
As we said earlier, Promises are "thenables", so they have a `then` method on them.
This is a very powerful function because anything you return from a `then` function is converted to a Promise (If not already one) that will resolve in whatever you're returning.

If you return something that is not a Promise, `then` will transform it to a Promise that will **resolve** with whatever your returned earlier.

```javascript
Promise.resolve()
  .then(() => 'hello')
  .then(console.log) // 'hello'

```

I've highlighted the word _resolve_ above. It is very important to understand that the Promise created by `then` will resolve (can be fulfilled or rejected) the value.
If you're trying to resolve a rejected Promise (so if you return a rejected promise), the returned Promise from `then` will also be rejected.

```javascript
Promise.resolve()
  .then(() => Promise.reject())
  .then(() => ...) // Never called!
  .catch(error => console.error(error)); // Called because we've returned a rejected Promise.
```

Another interesting fact about `then` is that if you return a Promise, the main Promise will wait and only resolve once the returned Promise (from the `then`) is resolved.

```javascript
Promise.resolve()
  .then(() => {
    return new Promise(resolve => {
        setTimeout(resolve, 2000);
    });
  })
  .then(() => {
    return new Promise(resolve => {
        setTimeout(resolve, 2000);
    });
  })
  .then(() => {
    // Will be called only after 4 seconds
  });

// Another example
function getPromise() {
  return new Promise(resolve => setTimeout(resolve, 2000))
    .then(() => new Promise(resolve => setTimeout(resolve, 2000)));
}

getPromise()
  .then(() => {
    // Will only be called after 4 seconds.
});
```
## Resources

- [MDN Promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)


text:
package org.dkpro.statistics.agreement;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Default implementation of the {@link IAnnotationStudy} interface. Abstract base class for coding
 * and unitizing annotation studies.
 *
 * @author Christian M. Meyer
 */
public abstract class AnnotationStudy
    implements IAnnotationStudy
{
    private static final long serialVersionUID = -3596722258510421730L;

    protected List<String> raters;
    protected Set<Object> categories;

    protected AnnotationStudy()
    {
        raters = new ArrayList<String>();
        categories = new LinkedHashSet<Object>();
    }

    /**
     * Add a rater with the given name. Returns the index of the newly added rater which is required
     * to identify the rater in {@link IAnnotationUnit}. The first rater receives index 0. Note that
     * adding names for the raters is optional.
     */
    public int addRater(final String name)
    {
        raters.add(name);
        return (raters.size() - 1);
    }

    /** Find the index of the rater with the given name. */
    public int findRater(final String name)
    {
        return raters.indexOf(name);
    }

    @Override
    public int getRaterCount()
    {
        return raters.size();
    }

    /**
     * Adds the given category to the set of possible annotation labels. This method is only
     * required of a category has not been used by any rater of within the annotation study.
     *
     * @throws NullPointerException
     *             if the specified category is null.
     */
    public void addCategory(final Object category)
    {
        categories.add(category);
    }

    @Override
    public Iterable<Object> getCategories()
    {
        return categories;
    }

    /*
     * public Object[] getCategoryArray() { Object[] result = null; int idx = 0; for (Object
     * category : getCategories()) { if (result == null) result = new Object[categories.size()];
     * result[idx++] = category; } return result; }
     */

    @Override
    public int getCategoryCount()
    {
        return categories.size();
    }

    @Override
    public boolean isDichotomous()
    {
        return (categories.size() == 2);
    }
}


text:
package org.apache.camel.issues;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.reifier.RouteReifier;
import org.junit.Test;

public class AdviceWithWeaveByToUriCBRTest extends ContextTestSupport {

    @Test
    public void testAdviceCBR() throws Exception {
        RouteDefinition route = context.getRouteDefinitions().get(0);
        RouteReifier.adviceWith(route, context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                weaveByToUri("direct:branch*").replace().to("mock:foo");
                mockEndpointsAndSkip("direct:branch*");
            }
        });

        getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .choice()
                        .when(header("foo")).to("direct:branch-1")
                    .otherwise()
                         .to("direct:branch-2");
            }
        };
    }

}


text:
#include <boost/predef/hardware/simd/x86.h>
#include <boost/predef/hardware/simd/x86_amd.h>
#include <boost/predef/hardware/simd/arm.h>
#include <boost/predef/hardware/simd/ppc.h>

#ifndef BOOST_PREDEF_HARDWARE_SIMD_H
#define BOOST_PREDEF_HARDWARE_SIMD_H

#include <boost/predef/version_number.h>

/*`
 [section Using the `BOOST_HW_SIMD_*` predefs]
 [include ../doc/hardware_simd.qbk]
 [endsect]

 [/ --------------------------- ]

 [section `BOOST_HW_SIMD_*`]

 [heading `BOOST_HW_SIMD`]

 The SIMD extension detected for a specific architectures.
 Version number depends on the detected extension.

 [table
     [[__predef_symbol__] [__predef_version__]]

     [[`BOOST_HW_SIMD_X86_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_X86_AMD_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_ARM_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_PPC_AVAILABLE`] [__predef_detection__]]
     ]

 [include ../include/boost/predef/hardware/simd/x86.h]
 [include ../include/boost/predef/hardware/simd/x86_amd.h]
 [include ../include/boost/predef/hardware/simd/arm.h]
 [include ../include/boost/predef/hardware/simd/ppc.h]

 [endsect]

 [/ --------------------------- ]

 [section `BOOST_HW_SIMD_X86_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/x86/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_X86_AMD_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/x86_amd/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_ARM_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/arm/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_PPC_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/ppc/versions.h]
 [endsect]

 */

// We check if SIMD extension of multiples architectures have been detected,
// if yes, then this is an error!
//
// NOTE: _X86_AMD implies _X86, so there is no need to check for it here!
//
#if defined(BOOST_HW_SIMD_ARM_AVAILABLE) && defined(BOOST_HW_SIMD_PPC_AVAILABLE) ||\
    defined(BOOST_HW_SIMD_ARM_AVAILABLE) && defined(BOOST_HW_SIMD_X86_AVAILABLE) ||\
    defined(BOOST_HW_SIMD_PPC_AVAILABLE) && defined(BOOST_HW_SIMD_X86_AVAILABLE)
#   error "Multiple SIMD architectures detected, this cannot happen!"
#endif

#if defined(BOOST_HW_SIMD_X86_AVAILABLE) && defined(BOOST_HW_SIMD_X86_AMD_AVAILABLE)
    // If both standard _X86 and _X86_AMD are available,
    // then take the biggest version of the two!
#   if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_AMD
#      define BOOST_HW_SIMD BOOST_HW_SIMD_X86
#   else
#      define BOOST_HW_SIMD BOOST_HW_SIMD_X86_AMD
#   endif
#endif

#if !defined(BOOST_HW_SIMD)
    // At this point, only one of these two is defined
#   if defined(BOOST_HW_SIMD_X86_AVAILABLE)
#      define BOOST_HW_SIMD BOOST_HW_SIMD_X86
#   endif
#   if defined(BOOST_HW_SIMD_X86_AMD_AVAILABLE)
#      define BOOST_HW_SIMD BOOST_HW_SIMD_X86_AMD
#   endif
#endif

#if defined(BOOST_HW_SIMD_ARM_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_ARM
#endif

#if defined(BOOST_HW_SIMD_PPC_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_PPC
#endif

#if defined(BOOST_HW_SIMD)
#   define BOOST_HW_SIMD_AVAILABLE
#else
#   define BOOST_HW_SIMD BOOST_VERSION_NUMBER_NOT_AVAILABLE
#endif

#define BOOST_HW_SIMD_NAME "Hardware SIMD"

#endif

#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_HW_SIMD, BOOST_HW_SIMD_NAME)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>J.E.S.S. installer</title>

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="compiled/style.css">

Installation...

                We are installing J.E.S.S., please wait.


text:
#import <Foundation/Foundation.h>

@interface NSScanner (NSScanner_Extensions)

- (NSString *)remainingString;

- (unichar)currentCharacter;
- (unichar)scanCharacter;
- (BOOL)scanCharacter:(unichar)inCharacter;
- (void)backtrack:(unsigned)inCount;

- (BOOL)scanCStyleComment:(NSString **)outComment;
- (BOOL)scanCPlusPlusStyleComment:(NSString **)outComment;

@end


text:
package betterwithmods.util;

import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.ArrayUtils;

import javax.annotation.Nonnull;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class InvUtils {

    public static boolean containsIngredient(List<Ingredient> collection, List<Ingredient> ingredient) {
        return matchesPredicate(collection, ingredient, (a,b) -> {
            if(a.getMatchingStacks().length > 0)
                return Arrays.stream(a.getMatchingStacks()).allMatch(b::apply);
            return false;
        });
    }

    public static boolean isIngredientValid(Ingredient ingredient) {
        return ArrayUtils.isEmpty(ingredient.getMatchingStacks());
    }

    public static boolean containsIngredient(ItemStackHandler handler, Ingredient ingredient) {
        return InventoryIterator.stream(handler).anyMatch(ingredient::apply);
    }

    public static boolean isFluidContainer(ItemStack stack) {
        return !stack.isEmpty() && (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null) || stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null));
    }

    public static <T> NonNullList<T> asNonnullList(T... array) {
        NonNullList<T> nonNullList = NonNullList.create();
        if (array != null)
            nonNullList.addAll(Arrays.stream(array).filter(Objects::nonNull).collect(Collectors.toList()));
        return nonNullList;
    }

    public static <T> NonNullList<T> asNonnullList(List<T> list) {
        NonNullList<T> nonNullList = NonNullList.create();
        if (list != null)
            nonNullList.addAll(list.stream().filter(Objects::nonNull).collect(Collectors.toList()));
        return nonNullList;
    }

    public static void givePlayer(EntityPlayer player, EnumFacing inv, NonNullList<ItemStack> stacks) {
        IItemHandlerModifiable inventory = (IItemHandlerModifiable) player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, inv);
        if (inventory != null)
            insert(inventory, stacks, false);
    }

    public static boolean usePlayerItemStrict(EntityPlayer player, EnumFacing inv, Ingredient ingredient, int amount) {
        IItemHandlerModifiable inventory = (IItemHandlerModifiable) player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, inv);
        return inventory != null && consumeItemsInInventoryStrict(inventory, ingredient, amount, false);
    }

    public static boolean usePlayerItem(EntityPlayer player, EnumFacing inv, ItemStack stack, int amount) {
        IItemHandlerModifiable inventory = (IItemHandlerModifiable) player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, inv);
        return inventory != null && consumeItemsInInventory(inventory, stack, amount, false);
    }

    public static boolean usePlayerItem(EntityPlayer player, EnumFacing inv, Ingredient ingredient) {
        IItemHandlerModifiable inventory = (IItemHandlerModifiable) player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, inv);
        boolean result = false;

        if (inventory != null) {
            NonNullList<ItemStack> containers = NonNullList.create();
            result = consumeItemsInInventory(inventory, ingredient, false, containers);
            givePlayer(player, inv, containers);
        }
        return result;
    }

    public static Optional<IItemHandler> getItemHandler(World world, BlockPos pos, EnumFacing facing) {
        if (!world.isRemote) {
            TileEntity tile = world.getTileEntity(pos);
            if (tile != null) {
                return Optional.ofNullable(tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing));
            } else {
                List<Entity> entities = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1), entity -> entity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing));
                Optional<Entity> entity = entities.stream().findFirst();
                if (entity.isPresent()) {
                    return Optional.ofNullable(entity.get().getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing));
                }
            }
        }
        return Optional.ofNullable(null);
    }

    public static void ejectInventoryContents(World world, BlockPos pos, IItemHandler inv) {
        for (int i = 0; i < inv.getSlots(); ++i) {
            ejectStackWithOffset(world, pos, inv.getStackInSlot(i));
        }
    }

    public static void clearInventory(IItemHandlerModifiable inv) {
        for (int i = 0; i < inv.getSlots(); ++i) {
            ItemStack stack = inv.getStackInSlot(i);
            if (!stack.isEmpty()) {
                inv.setStackInSlot(i, ItemStack.EMPTY);
            }
        }
    }

    public static void copyTags(ItemStack destStack, ItemStack sourceStack) {
        if (sourceStack.hasTagCompound()) {
            destStack.setTagCompound(sourceStack.getTagCompound().copy());
        }

    }

    public static ItemStack decrStackSize(IItemHandlerModifiable inv, int slot, int amount) {
        if (!inv.getStackInSlot(slot).isEmpty()) {
            ItemStack splitStack;
            if (inv.getStackInSlot(slot).getCount() <= amount) {
                splitStack = inv.getStackInSlot(slot);
                inv.setStackInSlot(slot, ItemStack.EMPTY);
                return splitStack;
            } else {
                splitStack = inv.getStackInSlot(slot).splitStack(amount);
                if (inv.getStackInSlot(slot).getCount() < 1) {
                    inv.setStackInSlot(slot, ItemStack.EMPTY);
                }
                return splitStack;
            }
        } else {
            return null;
        }
    }

    public static ItemStack insertSingle(IItemHandler inv, ItemStack stack, boolean simulate) {
        return insert(inv, stack, 1, simulate);
    }

    public static ItemStack insert(IItemHandler inv, ItemStack stack, int count, boolean simulate) {
        ItemStack copy = stack.copy();
        if (copy.getCount() > count) {
            copy.setCount(count);
        }
        return insert(inv, copy, simulate);
    }

    public static boolean canInsert(IItemHandler inv, ItemStack stack, int count) {
        ItemStack copy = stack.copy();
        if (copy.getCount() > count) {
            copy.setCount(count);
        }
        ItemStack inserted = insert(inv, copy, true);
        if (inserted.equals(copy)) {
            return false;
        }
        return true;
    }

    public static void insert(IItemHandler inv, NonNullList<ItemStack> stacks, boolean simulate) {
        stacks.forEach(stack -> insert(inv, stack, 0, inv.getSlots(), simulate));
    }

    public static ItemStack insert(IItemHandler inv, ItemStack stack, boolean simulate) {
        return insert(inv, stack, 0, inv.getSlots(), simulate);
    }

    public static ItemStack insert(IItemHandler inv, ItemStack stack, int minSlot, int maxSlot, boolean simulate) {
        return attemptInsert(inv, stack, minSlot, maxSlot, simulate);
    }

    public static ItemStack attemptInsert(IItemHandler inv, ItemStack stack, int minSlot, int maxSlot, boolean simulate) {
        if (isFull(inv))
            return stack;
        for (int slot = minSlot; slot < maxSlot; slot++) {
            stack = inv.insertItem(slot, stack, simulate);
            if (stack.isEmpty())
                break;
        }
        return stack;
    }

    public static boolean insertFromWorld(IItemHandler inv, EntityItem entity, int minSlot, int maxSlot, boolean simulate) {
        ItemStack stack = entity.getItem().copy();
        ItemStack leftover = attemptInsert(inv, stack, minSlot, maxSlot, simulate);
        if (leftover.isEmpty()) {
            entity.setDead();
            return true;
        } else {
            entity.setItem(leftover);
            return false;
        }
    }

    public static boolean isFull(IItemHandler inv) {
        boolean full = true;
        for (int slot = 0; slot < inv.getSlots(); slot++) {
            ItemStack stack = inv.getStackInSlot(slot);
            if (stack.getCount() != inv.getSlotLimit(slot)) {
                full = false;
                break;
            }
        }
        return full;
    }

    public static int getFirstOccupiedStackInRange(IItemHandler inv, int minSlot, int maxSlot) {
        for (int slot = minSlot; slot <= maxSlot; ++slot) {
            if (!inv.getStackInSlot(slot).isEmpty()) {
                return slot;
            }
        }
        return -1;
    }

    public static int getFirstEmptyStackInRange(IItemHandler inv, int minSlot, int maxSlot) {
        for (int slot = minSlot; slot <= maxSlot; ++slot) {
            if (inv.getStackInSlot(slot).isEmpty()) {
                return slot;
            }
        }

        return -1;
    }

    public static int getOccupiedStacks(IItemHandler inv) {
        return getOccupiedStacks(inv, 0, inv.getSlots() - 1);
    }

    public static int getOccupiedStacks(IItemHandler inv, int min, int max) {
        int count = 0;

        for (int i = min; i <= max; ++i) {
            if (inv.getStackInSlot(i).isEmpty()) {
                ++count;
            }
        }

        return count;
    }

    public static int countItemStacksInInventory(IItemHandler inv, ItemStack toCheck) {
        int itemCount = 0;
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack stack = inv.getStackInSlot(i);
            if (!stack.isEmpty()) {
                if (ItemStack.areItemsEqual(toCheck, stack) ||
                        (toCheck.getItem() == stack.getItem() && toCheck.getItemDamage() == OreDictionary.WILDCARD_VALUE)) {
                    if (toCheck.hasTagCompound()) {
                        if (ItemStack.areItemStackTagsEqual(toCheck, stack))
                            itemCount += stack.getCount();
                    } else
                        itemCount += stack.getCount();
                }
            }
        }
        return itemCount;
    }

    public static int countItemsInInventory(IItemHandler inv, Item item) {
        return countItemsInInventory(inv, item, OreDictionary.WILDCARD_VALUE);
    }

    public static int countItemsInInventory(IItemHandler inv, Item item, int meta) {
        int itemCount = 0;
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack stack = inv.getStackInSlot(i);
            if (!stack.isEmpty()) {
                if (stack.getItem() == item) {
                    if ((meta == OreDictionary.WILDCARD_VALUE) || (stack.getItemDamage() == meta)) {
                        itemCount += inv.getStackInSlot(i).getCount();
                    }
                }
            }
        }
        return itemCount;
    }

    public static int countOresInInventory(IItemHandler inv, List<ItemStack> list) {
        int ret = 0;
        if (list != null && !list.isEmpty()) {
            for (ItemStack oreStack : list) {
                ret += countItemStacksInInventory(inv, oreStack);
            }
        }
        return ret;
    }

    public static boolean consumeItemsInInventoryStrict(IItemHandlerModifiable inv, Ingredient ingredient, int sizeOfStack, boolean simulate) {
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack stack = inv.getStackInSlot(i);
            if (!stack.isEmpty()) {
                if (ingredient.apply(stack)) {
                    if (stack.getCount() >= sizeOfStack) {
                        decrStackSize(inv, i, sizeOfStack);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean consumeItemsInInventory(IItemHandler inv, ItemStack toCheck, int sizeOfStack, boolean simulate) {
        boolean extracted = false;
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack inSlot = inv.getStackInSlot(i);
            if (InvUtils.matches(toCheck, inSlot)) {
                ItemStack container = ForgeHooks.getContainerItem(inSlot);
                if (inv.extractItem(i, sizeOfStack, simulate).getCount() >= sizeOfStack) {
                    extracted = true;
                    InvUtils.insert(inv, container, false);
                    break;
                }
            }
        }
        return extracted;
    }

    public static boolean consumeItemsInInventory(IItemHandler inv, Ingredient ingredient, boolean simulate, NonNullList<ItemStack> containers) {
        int count;
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack inSlot = inv.getStackInSlot(i);
            if (ingredient.apply(inSlot)) {
                ItemStack container = ForgeHooks.getContainerItem(inSlot);
                if (!container.isEmpty())
                    containers.add(container);
                if (ingredient instanceof StackIngredient)
                    count = ((StackIngredient) ingredient).getCount(inSlot);
                else
                    count = 1;
                return inv.extractItem(i, count, simulate).getCount() >= count;
            }
        }
        return false;
    }

    public static boolean consumeItemsInInventory(IItemHandler inv, StackIngredient ingredient, boolean simulate, NonNullList<ItemStack> containers) {
        for (int i = 0; i < inv.getSlots(); i++) {
            ItemStack inSlot = inv.getStackInSlot(i);
            if (ingredient.apply(inSlot)) {
                int sizeOfStack = ingredient.getCount(inSlot);
                ItemStack container = ForgeHooks.getContainerItem(inSlot);
                if (!container.isEmpty())
                    containers.add(container);
                return inv.extractItem(i, sizeOfStack, simulate).getCount() >= sizeOfStack;
            }
        }
        return false;
    }

    public static boolean consumeItemsInInventory(IItemHandlerModifiable inv, Item item, int meta, int stackSize) {
        for (int i = 0; i < inv.getSlots(); ++i) {
            ItemStack stack = inv.getStackInSlot(i);
            if (!stack.isEmpty() && stack.getItem() == item && (meta == OreDictionary.WILDCARD_VALUE || stack.getItemDamage() == meta)) {
                if (stack.getCount() >= stackSize) {
                    decrStackSize(inv, i, stackSize);
                    return false;
                }

                stackSize -= stack.getCount();
                inv.setStackInSlot(i, ItemStack.EMPTY);
            }
        }
        return false;
    }

    public static boolean consumeOresInInventory(IItemHandlerModifiable inv, List<?> list, int stackSize) {
        if (list.size() > 0) {
            for (Object aList : list) {
                ItemStack tempStack = (ItemStack) aList;
                Item item = tempStack.getItem();
                int meta = tempStack.getItemDamage();

                for (int j = 0; j < inv.getSlots(); ++j) {
                    ItemStack stack = inv.getStackInSlot(j);
                    if (!stack.isEmpty() && stack.getItem() == item && (stack.getItemDamage() == meta || meta == OreDictionary.WILDCARD_VALUE)) {
                        if (tempStack.hasTagCompound()) {
                            if (ItemStack.areItemStackTagsEqual(tempStack, stack)) {
                                if (stack.getCount() >= stackSize) {
                                    decrStackSize(inv, j, stackSize);
                                    return false;
                                }

                                stackSize -= stack.getCount();
                                inv.setStackInSlot(j, ItemStack.EMPTY);
                            }
                        } else {
                            if (stack.getCount() >= stackSize) {
                                decrStackSize(inv, j, stackSize);
                                return false;
                            }

                            stackSize -= stack.getCount();
                            inv.setStackInSlot(j, ItemStack.EMPTY);
                        }
                    }
                }
            }
        }

        return false;
    }

    public static int getFirstOccupiedStackNotOfItem(IItemHandler inv, Item item) {
        return getFirstOccupiedStackNotOfItem(inv, item, OreDictionary.WILDCARD_VALUE);
    }

    public static int getFirstOccupiedStackNotOfItem(IItemHandler inv, Item item, int meta) {
        for (int i = 0; i < inv.getSlots(); ++i) {
            if (!inv.getStackInSlot(i).isEmpty()) {
                int tempMeta = inv.getStackInSlot(i).getItemDamage();
                if (inv.getStackInSlot(i).getItem() != item && (meta == OreDictionary.WILDCARD_VALUE || tempMeta != meta)) {
                    return i;
                }
            }
        }

        return -1;
    }

    public static int getFirstOccupiedStackOfItem(IItemHandler inv, Item item) {
        return getFirstOccupiedStackOfItem(inv, item);
    }

    public static int getFirstOccupiedStackOfItem(IItemHandler inv, ItemStack stack) {
        return getFirstOccupiedStackOfItem(inv, StackIngredient.fromStacks(stack));
    }

    public static int getFirstOccupiedStackOfItem(IItemHandler inv, Ingredient ingred) {
        for (int i = 0; i < inv.getSlots(); ++i) {
            if (!inv.getStackInSlot(i).isEmpty()) {
                if (ingred.apply(inv.getStackInSlot(i))) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static boolean spawnStack(World world, BlockPos pos, List<ItemStack> stacks) {
        boolean spawned = true;
        for (ItemStack stack : stacks) {
            if (!stack.isEmpty())
                if (!spawnStack(world, pos, stack, 10))
                    spawned = false;
        }
        return spawned;
    }

    public static boolean spawnStack(World world, BlockPos pos, ItemStack stack, int pickupDelay) {
        return spawnStack(world, pos.getX() + 0.5f, pos.getY() + 0.5f, pos.getZ() + 0.5f, stack, pickupDelay);
    }

    public static boolean spawnStack(World world, double x, double y, double z, ItemStack stack, int pickupDelay) {
        EntityItem item = new EntityItem(world, x, y, z, stack);
        item.motionX = 0;
        item.motionY = 0;
        item.motionZ = 0;
        item.setPickupDelay(pickupDelay);
        return world.spawnEntity(item);
    }

    public static void spawnStack(World world, double x, double y, double z, int count, ItemStack stack) {
        ItemStack copy = stack.copy();
        if (copy.getCount() > count)
            copy.setCount(count);
        spawnStack(world, x, y, z, copy, 10);
    }

    public static void ejectStackWithOffset(World world, BlockPos pos, List<ItemStack> stacks) {
        for (ItemStack stack : stacks) {
            if (!stack.isEmpty())
                ejectStackWithOffset(world, pos, stack.copy());
        }
    }

    public static void ejectStackWithOffset(World world, BlockPos pos, ItemStack... stacks) {
        for (ItemStack stack : stacks) {
            if (!stack.isEmpty())
                ejectStackWithOffset(world, pos, stack.copy());
        }
    }

    public static void ejectStackWithOffset(World world, BlockPos pos, ItemStack stack) {
        if (stack.isEmpty())
            return;
        VectorBuilder builder = new VectorBuilder();
        new StackEjector(world, stack,builder.set(pos).rand(0.5f).offset(0.25f).build(), builder.setGaussian(0.05f).build()).ejectStack();
    }

    public static void ejectStack(World world, double x, double y, double z, ItemStack stack, int pickupDelay) {
        if (world.isRemote)
            return;

        VectorBuilder builder = new VectorBuilder();
        StackEjector ejector = new StackEjector(world, stack,builder.set(x,y,z).build());
        ejector.setPickupDelay(pickupDelay);
        ejector.ejectStack();
    }

    public static void ejectStack(World world, double x, double y, double z, ItemStack stack) {
        ejectStack(world, x, y, z, stack, 10);
    }

    public static void ejectBrokenItems(World world, BlockPos pos, ResourceLocation lootLocation) {
        if (!world.isRemote) {
            LootContext.Builder build = new LootContext.Builder((WorldServer) world);
            List<ItemStack> stacks = world.getLootTableManager().getLootTableFromLocation(lootLocation).generateLootForPools(world.rand, build.build());
            if (!stacks.isEmpty()) {
                ejectStackWithOffset(world, pos, stacks);
            }
        }
    }

    public static void writeToStack(IItemHandler inv, ItemStack stack) {
        NonNullList<ItemStack> list = NonNullList.withSize(inv.getSlots(), ItemStack.EMPTY);
        for (int i = 0; i < inv.getSlots(); i++) {
            if (!inv.getStackInSlot(i).isEmpty()) {
                list.set(i, inv.getStackInSlot(i).copy());
            }
        }
        NBTTagCompound tag = ItemStackHelper.saveAllItems(new NBTTagCompound(), list);

        if (!tag.hasNoTags())
            stack.setTagCompound(tag);
    }

    public static void readFromStack(IItemHandler inv, ItemStack stack) {
        if (!stack.isEmpty() && stack.hasTagCompound()) {
            NonNullList<ItemStack> list = NonNullList.withSize(inv.getSlots(), ItemStack.EMPTY);
            NBTTagCompound tag = stack.getTagCompound();
            if (tag != null) {
                ItemStackHelper.loadAllItems(tag, list);
                for (int i = 0; i < inv.getSlots(); i++) {
                    inv.insertItem(i, list.get(i), false);
                }
            }
        }
    }

    public static int calculateComparatorLevel(@Nonnull IItemHandler inventory) {
        int i = 0;
        float f = 0.0F;
        for (int j = 0; j < inventory.getSlots(); ++j) {
            ItemStack itemstack = inventory.getStackInSlot(j);
            if (!itemstack.isEmpty()) {
                f += (float) itemstack.getCount() / (float) itemstack.getMaxStackSize();
                ++i;
            }
        }
        f = f / (float) inventory.getSlots();
        return MathHelper.floor(f * 14.0F) + (i > 0 ? 1 : 0);
    }

    public static ItemStack setCount(ItemStack input, int count) {
        if(input.isEmpty())
            return input;
        ItemStack stack = input.copy();
        stack.setCount(count);
        return stack;
    }

    public static boolean matches(ItemStack one, ItemStack two) {
        if (one.isItemEqual(two))
            return true;
        if (one.getItem() == two.getItem() && (one.getMetadata() == OreDictionary.WILDCARD_VALUE || two.getMetadata() == OreDictionary.WILDCARD_VALUE))
            return true;
        return false;
    }

    public static boolean matchesSize(ItemStack one, ItemStack two) {
        return one.getCount() == two.getCount() && matches(one, two);
    }

    public static <T> boolean matchesPredicate(List<T> oneList, List<T> twoList, BiPredicate<T,T> matches) {
        if (oneList.size() != twoList.size())
            return false; //trivial case
        HashSet<T> alreadyMatched = new HashSet<>();
        for (T one : oneList) {
            Optional<T> found = twoList.stream().filter(two -> !alreadyMatched.contains(two) && matches.test(one,two)).findFirst();
            if (found.isPresent())
                alreadyMatched.add(found.get()); //Don't match twice
            else
                return false; //This T doesn't match, thus the two lists don't match
        }
        return true;
    }

    public static boolean matchesExact(List<ItemStack> oneList, List<ItemStack> twoList) {
        return matchesPredicate(oneList, twoList, InvUtils::matchesSize);
    }

    public static boolean matches(List<ItemStack> oneList, List<ItemStack> twoList) {
        return matchesPredicate(oneList,twoList, InvUtils::matches);
    }

    public static <T> List<List<T>> splitIntoBoxes(List<T> stacks, int boxes) {
        ArrayList<List<T>> splitStacks = new ArrayList<>();
        for (int i = 0; i < boxes; i++) {
            final int finalI = i;
            splitStacks.add(IntStream.range(0, stacks.size()).filter(index -> index % boxes == finalI).mapToObj(stacks::get).collect(Collectors.toList()));
        }
        return splitStacks;
    }

}