text:
package opencontrail

import (
	json "encoding/json"
	easyjson "github.com/mailru/easyjson"
	jlexer "github.com/mailru/easyjson/jlexer"
	jwriter "github.com/mailru/easyjson/jwriter"
)

// suppress unused package warning
var (
	_ *json.RawMessage
	_ *jlexer.Lexer
	_ *jwriter.Writer
	_ easyjson.Marshaler
)

func easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(in *jlexer.Lexer, out *RoutingTable) {
	isTopLevel := in.IsStart()
	if in.IsNull() {
		if isTopLevel {
			in.Consumed()
		}
		in.Skip()
		return
	}
	in.Delim('{')
	for !in.IsDelim('}') {
		key := in.UnsafeString()
		in.WantColon()
		if in.IsNull() {
			in.Skip()
			in.WantComma()
			continue
		}
		switch key {
		case "InterfacesUUID":
			if in.IsNull() {
				in.Skip()
				out.InterfacesUUID = nil
			} else {
				in.Delim('[')
				if out.InterfacesUUID == nil {
					if !in.IsDelim(']') {
						out.InterfacesUUID = make([]string, 0, 4)
					} else {
						out.InterfacesUUID = []string{}
					}
				} else {
					out.InterfacesUUID = (out.InterfacesUUID)[:0]
				}
				for !in.IsDelim(']') {
					var v1 string
					v1 = string(in.String())
					out.InterfacesUUID = append(out.InterfacesUUID, v1)
					in.WantComma()
				}
				in.Delim(']')
			}
		case "Routes":
			if in.IsNull() {
				in.Skip()
				out.Routes = nil
			} else {
				in.Delim('[')
				if out.Routes == nil {
					if !in.IsDelim(']') {
						out.Routes = make([]*Route, 0, 8)
					} else {
						out.Routes = []*Route{}
					}
				} else {
					out.Routes = (out.Routes)[:0]
				}
				for !in.IsDelim(']') {
					var v2 *Route
					if in.IsNull() {
						in.Skip()
						v2 = nil
					} else {
						if v2 == nil {
							v2 = new(Route)
						}
						(*v2).UnmarshalEasyJSON(in)
					}
					out.Routes = append(out.Routes, v2)
					in.WantComma()
				}
				in.Delim(']')
			}
		default:
			in.SkipRecursive()
		}
		in.WantComma()
	}
	in.Delim('}')
	if isTopLevel {
		in.Consumed()
	}
}
func easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(out *jwriter.Writer, in RoutingTable) {
	out.RawByte('{')
	first := true
	_ = first
	{
		const prefix string = ",\"InterfacesUUID\":"
		out.RawString(prefix[1:])
		if in.InterfacesUUID == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
			out.RawString("null")
		} else {
			out.RawByte('[')
			for v3, v4 := range in.InterfacesUUID {
				if v3 > 0 {
					out.RawByte(',')
				}
				out.String(string(v4))
			}
			out.RawByte(']')
		}
	}
	{
		const prefix string = ",\"Routes\":"
		out.RawString(prefix)
		if in.Routes == nil && (out.Flags&jwriter.NilSliceAsEmpty) == 0 {
			out.RawString("null")
		} else {
			out.RawByte('[')
			for v5, v6 := range in.Routes {
				if v5 > 0 {
					out.RawByte(',')
				}
				if v6 == nil {
					out.RawString("null")
				} else {
					(*v6).MarshalEasyJSON(out)
				}
			}
			out.RawByte(']')
		}
	}
	out.RawByte('}')
}

// MarshalJSON supports json.Marshaler interface
func (v RoutingTable) MarshalJSON() ([]byte, error) {
	w := jwriter.Writer{}
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(&w, v)
	return w.Buffer.BuildBytes(), w.Error
}

// MarshalEasyJSON supports easyjson.Marshaler interface
func (v RoutingTable) MarshalEasyJSON(w *jwriter.Writer) {
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(w, v)
}

// UnmarshalJSON supports json.Unmarshaler interface
func (v *RoutingTable) UnmarshalJSON(data []byte) error {
	r := jlexer.Lexer{Data: data}
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(&r, v)
	return r.Error()
}

// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *RoutingTable) UnmarshalEasyJSON(l *jlexer.Lexer) {
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail(l, v)
}
func easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(in *jlexer.Lexer, out *Route) {
	isTopLevel := in.IsStart()
	if in.IsNull() {
		if isTopLevel {
			in.Consumed()
		}
		in.Skip()
		return
	}
	in.Delim('{')
	for !in.IsDelim('}') {
		key := in.UnsafeString()
		in.WantColon()
		if in.IsNull() {
			in.Skip()
			in.WantComma()
			continue
		}
		switch key {
		case "Family":
			out.Family = string(in.String())
		case "Prefix":
			out.Prefix = string(in.String())
		case "NhID":
			out.NhID = int64(in.Int64())
		case "Protocol":
			out.Protocol = int64(in.Int64())
		default:
			in.SkipRecursive()
		}
		in.WantComma()
	}
	in.Delim('}')
	if isTopLevel {
		in.Consumed()
	}
}
func easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(out *jwriter.Writer, in Route) {
	out.RawByte('{')
	first := true
	_ = first
	if in.Family != "" {
		const prefix string = ",\"Family\":"
		first = false
		out.RawString(prefix[1:])
		out.String(string(in.Family))
	}
	if in.Prefix != "" {
		const prefix string = ",\"Prefix\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.String(string(in.Prefix))
	}
	if in.NhID != 0 {
		const prefix string = ",\"NhID\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.Int64(int64(in.NhID))
	}
	if in.Protocol != 0 {
		const prefix string = ",\"Protocol\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.Int64(int64(in.Protocol))
	}
	out.RawByte('}')
}

// MarshalJSON supports json.Marshaler interface
func (v Route) MarshalJSON() ([]byte, error) {
	w := jwriter.Writer{}
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(&w, v)
	return w.Buffer.BuildBytes(), w.Error
}

// MarshalEasyJSON supports easyjson.Marshaler interface
func (v Route) MarshalEasyJSON(w *jwriter.Writer) {
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(w, v)
}

// UnmarshalJSON supports json.Unmarshaler interface
func (v *Route) UnmarshalJSON(data []byte) error {
	r := jlexer.Lexer{Data: data}
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(&r, v)
	return r.Error()
}

// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *Route) UnmarshalEasyJSON(l *jlexer.Lexer) {
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail1(l, v)
}
func easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(in *jlexer.Lexer, out *Metadata) {
	isTopLevel := in.IsStart()
	if in.IsNull() {
		if isTopLevel {
			in.Consumed()
		}
		in.Skip()
		return
	}
	in.Delim('{')
	for !in.IsDelim('}') {
		key := in.UnsafeString()
		in.WantColon()
		if in.IsNull() {
			in.Skip()
			in.WantComma()
			continue
		}
		switch key {
		case "UUID":
			out.UUID = string(in.String())
		case "MAC":
			out.MAC = string(in.String())
		case "VRF":
			out.VRF = string(in.String())
		case "VRFID":
			out.VRFID = int64(in.Int64())
		case "LocalIP":
			out.LocalIP = string(in.String())
		case "RoutingTable":
			if in.IsNull() {
				in.Skip()
				out.RoutingTable = nil
			} else {
				in.Delim('[')
				if out.RoutingTable == nil {
					if !in.IsDelim(']') {
						out.RoutingTable = make([]*Route, 0, 8)
					} else {
						out.RoutingTable = []*Route{}
					}
				} else {
					out.RoutingTable = (out.RoutingTable)[:0]
				}
				for !in.IsDelim(']') {
					var v7 *Route
					if in.IsNull() {
						in.Skip()
						v7 = nil
					} else {
						if v7 == nil {
							v7 = new(Route)
						}
						(*v7).UnmarshalEasyJSON(in)
					}
					out.RoutingTable = append(out.RoutingTable, v7)
					in.WantComma()
				}
				in.Delim(']')
			}
		default:
			in.SkipRecursive()
		}
		in.WantComma()
	}
	in.Delim('}')
	if isTopLevel {
		in.Consumed()
	}
}
func easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(out *jwriter.Writer, in Metadata) {
	out.RawByte('{')
	first := true
	_ = first
	if in.UUID != "" {
		const prefix string = ",\"UUID\":"
		first = false
		out.RawString(prefix[1:])
		out.String(string(in.UUID))
	}
	if in.MAC != "" {
		const prefix string = ",\"MAC\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.String(string(in.MAC))
	}
	if in.VRF != "" {
		const prefix string = ",\"VRF\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.String(string(in.VRF))
	}
	if in.VRFID != 0 {
		const prefix string = ",\"VRFID\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.Int64(int64(in.VRFID))
	}
	if in.LocalIP != "" {
		const prefix string = ",\"LocalIP\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		out.String(string(in.LocalIP))
	}
	if len(in.RoutingTable) != 0 {
		const prefix string = ",\"RoutingTable\":"
		if first {
			first = false
			out.RawString(prefix[1:])
		} else {
			out.RawString(prefix)
		}
		{
			out.RawByte('[')
			for v8, v9 := range in.RoutingTable {
				if v8 > 0 {
					out.RawByte(',')
				}
				if v9 == nil {
					out.RawString("null")
				} else {
					(*v9).MarshalEasyJSON(out)
				}
			}
			out.RawByte(']')
		}
	}
	out.RawByte('}')
}

// MarshalJSON supports json.Marshaler interface
func (v Metadata) MarshalJSON() ([]byte, error) {
	w := jwriter.Writer{}
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(&w, v)
	return w.Buffer.BuildBytes(), w.Error
}

// MarshalEasyJSON supports easyjson.Marshaler interface
func (v Metadata) MarshalEasyJSON(w *jwriter.Writer) {
	easyjsonBa0ee0e3EncodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(w, v)
}

// UnmarshalJSON supports json.Unmarshaler interface
func (v *Metadata) UnmarshalJSON(data []byte) error {
	r := jlexer.Lexer{Data: data}
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(&r, v)
	return r.Error()
}

// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *Metadata) UnmarshalEasyJSON(l *jlexer.Lexer) {
	easyjsonBa0ee0e3DecodeGithubComSkydiveProjectSkydiveTopologyProbesOpencontrail2(l, v)
}


text:
.class Landroid/view/SurfaceView$MyWindow;
.super Lcom/android/internal/view/BaseIWindow;
.source "SurfaceView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/SurfaceView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "MyWindow"
.end annotation

# instance fields
.field mCurHeight:I

.field mCurWidth:I

.field private final mSurfaceView:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Landroid/view/SurfaceView;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>(Landroid/view/SurfaceView;)V
    .locals 1
    .param p1, "surfaceView"    # Landroid/view/SurfaceView;

    .prologue
    const/4 v0, -0x1

    .line 651
    invoke-direct {p0}, Lcom/android/internal/view/BaseIWindow;-><init>()V

    .line 704
    iput v0, p0, Landroid/view/SurfaceView$MyWindow;->mCurWidth:I

    .line 705
    iput v0, p0, Landroid/view/SurfaceView$MyWindow;->mCurHeight:I

    .line 652
    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Landroid/view/SurfaceView$MyWindow;->mSurfaceView:Ljava/lang/ref/WeakReference;

    .line 653
    return-void
.end method

# virtual methods
.method public dispatchAppVisibility(Z)V
    .locals 0
    .param p1, "visible"    # Z

    .prologue
    .line 684
    return-void
.end method

.method public dispatchGetNewSurface()V
    .locals 4

    .prologue
    .line 688
    iget-object v2, p0, Landroid/view/SurfaceView$MyWindow;->mSurfaceView:Ljava/lang/ref/WeakReference;

    invoke-virtual {v2}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/view/SurfaceView;

    .line 689
    .local v1, "surfaceView":Landroid/view/SurfaceView;
    if-eqz v1, :cond_0

    .line 690
    iget-object v2, v1, Landroid/view/SurfaceView;->mHandler:Landroid/os/Handler;

    const/4 v3, 0x2

    invoke-virtual {v2, v3}, Landroid/os/Handler;->obtainMessage(I)Landroid/os/Message;

    move-result-object v0

    .line 691
    .local v0, "msg":Landroid/os/Message;
    iget-object v2, v1, Landroid/view/SurfaceView;->mHandler:Landroid/os/Handler;

    invoke-virtual {v2, v0}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    .line 693
    .end local v0    # "msg":Landroid/os/Message;
    :cond_0
    return-void
.end method

.method public executeCommand(Ljava/lang/String;Ljava/lang/String;Landroid/os/ParcelFileDescriptor;)V
    .locals 0
    .param p1, "command"    # Ljava/lang/String;
    .param p2, "parameters"    # Ljava/lang/String;
    .param p3, "out"    # Landroid/os/ParcelFileDescriptor;

    .prologue
    .line 702
    return-void
.end method

.method public resized(Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;ZLandroid/content/res/Configuration;)V
    .locals 3
    .param p1, "frame"    # Landroid/graphics/Rect;
    .param p2, "overscanInsets"    # Landroid/graphics/Rect;
    .param p3, "contentInsets"    # Landroid/graphics/Rect;
    .param p4, "visibleInsets"    # Landroid/graphics/Rect;
    .param p5, "stableInsets"    # Landroid/graphics/Rect;
    .param p6, "reportDraw"    # Z
    .param p7, "newConfig"    # Landroid/content/res/Configuration;

    .prologue
    .line 659
    iget-object v1, p0, Landroid/view/SurfaceView$MyWindow;->mSurfaceView:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/SurfaceView;

    .line 660
    .local v0, "surfaceView":Landroid/view/SurfaceView;
    if-eqz v0, :cond_1

    .line 664
    iget-object v1, v0, Landroid/view/SurfaceView;->mSurfaceLock:Ljava/util/concurrent/locks/ReentrantLock;

    invoke-virtual {v1}, Ljava/util/concurrent/locks/ReentrantLock;->lock()V

    .line 666
    if-eqz p6, :cond_2

    .line 667
    const/4 v1, 0x1

    :try_start_0
    iput-boolean v1, v0, Landroid/view/SurfaceView;->mUpdateWindowNeeded:Z

    .line 668
    const/4 v1, 0x1

    iput-boolean v1, v0, Landroid/view/SurfaceView;->mReportDrawNeeded:Z

    .line 669
    iget-object v1, v0, Landroid/view/SurfaceView;->mHandler:Landroid/os/Handler;

    const/4 v2, 0x3

    invoke-virtual {v1, v2}, Landroid/os/Handler;->sendEmptyMessage(I)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 676
    :cond_0
    :goto_0
    iget-object v1, v0, Landroid/view/SurfaceView;->mSurfaceLock:Ljava/util/concurrent/locks/ReentrantLock;

    invoke-virtual {v1}, Ljava/util/concurrent/locks/ReentrantLock;->unlock()V

    .line 679
    :cond_1
    return-void

    .line 670
    :cond_2
    :try_start_1
    iget-object v1, v0, Landroid/view/SurfaceView;->mWinFrame:Landroid/graphics/Rect;

    invoke-virtual {v1}, Landroid/graphics/Rect;->width()I

    move-result v1

    invoke-virtual {p1}, Landroid/graphics/Rect;->width()I

    move-result v2

    if-ne v1, v2, :cond_3

    iget-object v1, v0, Landroid/view/SurfaceView;->mWinFrame:Landroid/graphics/Rect;

    invoke-virtual {v1}, Landroid/graphics/Rect;->height()I

    move-result v1

    invoke-virtual {p1}, Landroid/graphics/Rect;->height()I

    move-result v2

    if-eq v1, v2, :cond_0

    .line 672
    :cond_3
    const/4 v1, 0x1

    iput-boolean v1, v0, Landroid/view/SurfaceView;->mUpdateWindowNeeded:Z

    .line 673
    iget-object v1, v0, Landroid/view/SurfaceView;->mHandler:Landroid/os/Handler;

    const/4 v2, 0x3

    invoke-virtual {v1, v2}, Landroid/os/Handler;->sendEmptyMessage(I)Z
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    goto :goto_0

    .line 676
    :catchall_0
    move-exception v1

    iget-object v2, v0, Landroid/view/SurfaceView;->mSurfaceLock:Ljava/util/concurrent/locks/ReentrantLock;

    invoke-virtual {v2}, Ljava/util/concurrent/locks/ReentrantLock;->unlock()V

    throw v1
.end method

.method public windowFocusChanged(ZZ)V
    .locals 3
    .param p1, "hasFocus"    # Z
    .param p2, "touchEnabled"    # Z

    .prologue
    .line 697
    const-string v0, "SurfaceView"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "Unexpected focus in surface: focus="

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, ", touchEnabled="

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 698
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
'use strict';

let React;
let ReactNoopPersistent;

describe('ReactPersistentUpdatesMinimalism', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoopPersistent = require('react-noop-renderer/persistent');
  });

  it('should render a simple component', () => {
    function Child() {
      return
Hello World
;
    }

    function Parent() {
      return <Child />;
    }

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      hostDiffCounter: 0,
      hostCloneCounter: 0,
    });

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      hostDiffCounter: 1,
      hostCloneCounter: 1,
    });
  });

  it('should not diff referentially equal host elements', () => {
    function Leaf(props) {
      return (

          hello

          {props.name}

      );
    }

    const constEl = (

        <Leaf name="world" />

    );

    function Child() {
      return constEl;
    }

    function Parent() {
      return <Child />;
    }

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      hostDiffCounter: 0,
      hostCloneCounter: 0,
    });

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      hostDiffCounter: 0,
      hostCloneCounter: 0,
    });
  });

  it('should not diff parents of setState targets', () => {
    let childInst;

    function Leaf(props) {
      return (

          hello

          {props.name}

      );
    }

    class Child extends React.Component {
      state = {name: 'Batman'};
      render() {
        childInst = this;
        return (

            <Leaf name={this.state.name} />

        );
      }
    }

    function Parent() {
      return (

            <Leaf name="world" />
            <Child />

            <Leaf name="world" />

      );
    }

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      hostDiffCounter: 0,
      hostCloneCounter: 0,
    });

    childInst.setState({name: 'Robin'});
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      // section > div > Child > div
      // section > div > Child > Leaf > span
      // section > div > Child > Leaf > span > b
      hostDiffCounter: 3,
      // section
      // section > div
      // section > div > Child > div
      // section > div > Child > Leaf > span
      // section > div > Child > Leaf > span > b
      hostCloneCounter: 5,
    });

    ReactNoopPersistent.render(<Parent />);
    expect(ReactNoopPersistent.flushWithHostCounters()).toEqual({
      // Parent > section
      // Parent > section > div
      // Parent > section > div > Leaf > span
      // Parent > section > div > Leaf > span > b
      // Parent > section > div > Child > div
      // Parent > section > div > Child > div > Leaf > span
      // Parent > section > div > Child > div > Leaf > span > b
      // Parent > section > div > hr
      // Parent > section > div > Leaf > span
      // Parent > section > div > Leaf > span > b
      hostDiffCounter: 10,
      hostCloneCounter: 10,
    });
  });
});


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "KtouthBrand::ST2::ErrorMessage" do
  before :all do
    @text = 'sample error message!'
    @lineno = 152
    @column = 11
  end

  subject { KtouthBrand::ST2::ErrorMessage }
  it { should be_instance_of(Class) }

  describe ".new" do
    context 'argument exceptions' do
      it { expect { subject.new }.to raise_error(ArgumentError) }
      it { expect { subject.new(nil) }.to raise_error(ArgumentError) }
      it { expect { subject.new('') }.to raise_error(ArgumentError) }
      it { expect { subject.new('     ') }.to raise_error(ArgumentError) }
      it { expect { subject.new(15623) }.to raise_error(ArgumentError) }
      it { expect { subject.new('simple', /invalid/) }.to raise_error(ArgumentError) }

      it { expect { subject.new(@text, :line => /invalid/) }.to raise_error(ArgumentError) }
      it { expect { subject.new(@text, :line => 'this option is integer only') }.to raise_error(ArgumentError) }

      it { expect { subject.new(@text, :column => /invalid/) }.to raise_error(ArgumentError) }
      it { expect { subject.new(@text, :column => 'this option is integer only') }.to raise_error(ArgumentError) }
    end
    it { subject.new('valid error-message.', :line => 10, :column => 19).should be_a(subject) }
  end

  describe "#message" do
    subject { KtouthBrand::ST2::ErrorMessage.new(@text) }
    it { should be_respond_to(:message) }
    it { subject.message.should == @text }
  end

  describe "#line" do
    subject { KtouthBrand::ST2::ErrorMessage.new(@text) }
    it { should be_respond_to(:line) }
    it { subject.line.should be_nil }

    context 'set :lineno option' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text, :line => @lineno) }
      it { subject.line.should == @lineno }
    end
  end

  describe "#column" do
    subject { KtouthBrand::ST2::ErrorMessage.new(@text) }
    it { should be_respond_to(:column) }
    it { subject.column.should be_nil }

    context 'set :columnno option' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text, :column => @column) }
      it { subject.column.should == @column }
    end
  end

  describe "#to_s" do
    context 'no options message' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text) }
      it { subject.to_s.should == ['-', '-', @text].join(':') }
    end
    context 'no :column option message' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text, :line => @lineno) }
      it { subject.to_s.should == [@lineno, '-', @text].join(':') }
    end
    context 'no ;line option message' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text, :column => @column) }
      it { subject.to_s.should == ['-', @column, @text].join(':') }
    end
    context 'full options message' do
      subject { KtouthBrand::ST2::ErrorMessage.new(@text, :line => @lineno, :column => @column) }
      it { subject.to_s.should == [@lineno, @column, @text].join(':') }
    end
  end
end


text:
<tool id="ip_detection_viz" name="Detection Visualization" version="0.3">
    <description>Detection Visualization</description>
    <requirements>
        <requirement type="package" version="0.14.2">scikit-image</requirement>
        <requirement type="package" version="3.0.2">matplotlib</requirement>
        <requirement type="package" version="0.15.1">tifffile</requirement>
    </requirements>
    <command detect_errors="aggressive">
        <![CDATA[
        python '$__tool_directory__/detection_viz.py' '$input' '$output'
        --stroke_size $thickness --circle_radius $circle_radius
        #if $tp_option['display'] == 'true'
        --tp '$tp'
        #end if
        #if $fn_option['display'] == 'true'
        --fn '$fn'
        #end if
        #if $fp_option['display'] == 'true'
        --fp '$fp'
        #end if
        ]]>
    </command>
    <inputs>
        <param name="input" type="data" format="tiff,png,jpg,bmp" label="Binary Image File"/>
        <conditional name="tp_option">
            <param label="Display true positives" name="display" type="select">
                <option selected="True" value="false">No</option>
                <option value="true">Yes</option>
            </param>
            <when value="false"></when>
            <when value="true">
                <param name="tp" type="data" format="tabular" label="True positives file" />
            </when>
        </conditional>
        <conditional name="fn_option">
            <param label="Display false negatives" name="display" type="select">
                <option selected="True" value="false">No</option>
                <option value="true">Yes</option>
            </param>
            <when value="false"></when>
            <when value="true">
                <param name="fn" type="data" format="tabular" label="False negatives file" />
            </when>
        </conditional>
        <conditional name="fp_option">
            <param label="Display false positives" name="display" type="select">
                <option selected="True" value="false">No</option>
                <option value="true">Yes</option>
            </param>
            <when value="false"></when>
            <when value="true">
                <param name="fp" type="data" format="tabular" label="False positives file" />
            </when>
        </conditional>
        <param name="thickness" type="float" value="3.0" label="Stroke thickness"/>
        <param name="circle_radius" type="float" value="50.0" label="Circle radius"/>
    </inputs>
    <outputs>
        <data format="png" name="output"/>
    </outputs>
    <tests>
        <test>
            <param name="input" value="sample.png"/>
            <param name="tp_option.display" value="false"/>
            <param name="fn_option.display" value="false"/>
            <param name="fp_option.display" value="false"/>
            <output name="output" value="out.png" ftype="png"/>
        </test>
    </tests>
    <help>
    **What it does**

    Draws circles of different colors around detected true positives, false negatives and false positives.
    </help>
    <citations>
        <citation type="doi">10.1016/j.jbiotec.2017.07.019</citation>
    </citations>
</tool>


text:
package org.wso2.siddhi.core.query.processor.stream.window;

import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.MetaComplexEvent;
import org.wso2.siddhi.core.event.stream.StreamEvent;
import org.wso2.siddhi.core.event.stream.StreamEventCloner;
import org.wso2.siddhi.core.executor.ConstantExpressionExecutor;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.executor.VariableExpressionExecutor;
import org.wso2.siddhi.core.query.processor.Processor;
import org.wso2.siddhi.core.table.EventTable;
import org.wso2.siddhi.core.util.collection.operator.Finder;
import org.wso2.siddhi.core.util.parser.CollectionOperatorParser;
import org.wso2.siddhi.query.api.expression.Expression;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LossyFrequentWindowProcessor extends WindowProcessor implements FindableProcessor{

    private ConcurrentHashMap<String, LossyCount> countMap = new ConcurrentHashMap<String, LossyCount>();
    private ConcurrentHashMap<String, StreamEvent> map = new ConcurrentHashMap<String, StreamEvent>();
    private VariableExpressionExecutor[] variableExpressionExecutors;

    private int totalCount = 0;
    private double currentBucketId=1;
    private double support;           // these will be initialize during init
    private double error;             // these will be initialize during init
    private double windowWidth;

    @Override
    protected void init(ExpressionExecutor[] attributeExpressionExecutors, ExecutionPlanContext executionPlanContext) {
        support = Double.parseDouble(String.valueOf(((ConstantExpressionExecutor) attributeExpressionExecutors[0]).getValue()));
        if (attributeExpressionExecutors.length > 1) {
            error =  Double.parseDouble(String.valueOf(((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()));
        } else {
            error = support / 10; // recommended error is 10% of 20$ of support value;
        }
        if ((support > 1 || support < 0) || (error > 1 || error < 0)) {
            log.error("Wrong argument has provided, Error executing the window");
        }
        variableExpressionExecutors = new VariableExpressionExecutor[attributeExpressionExecutors.length - 2];
        if (attributeExpressionExecutors.length > 2) {  // by-default all the attributes will be compared
            for (int i = 2; i < attributeExpressionExecutors.length; i++) {
                variableExpressionExecutors[i - 2] = (VariableExpressionExecutor) attributeExpressionExecutors[i];
            }
        }
        windowWidth = Math.ceil(1 / error);
        currentBucketId = 1;
    }

    @Override
    protected synchronized void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) {
        ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>();

        StreamEvent streamEvent = streamEventChunk.getFirst();

        while (streamEvent != null) {
            StreamEvent next = streamEvent.getNext();
            streamEvent.setNext(null);

            StreamEvent clonedEvent = streamEventCloner.copyStreamEvent(streamEvent);
            clonedEvent.setType(StreamEvent.Type.EXPIRED);

            totalCount++;
            if (totalCount != 1) {
                currentBucketId = Math.ceil(totalCount / windowWidth);
            }

            StreamEvent oldEvent = map.put(generateKey(streamEvent), clonedEvent);
            if (oldEvent != null) {    // this event is already in the store
                countMap.put(generateKey(streamEvent), countMap.get(generateKey(streamEvent)).incrementCount());
            } else {
                //  This is a new event
                LossyCount lCount;
                lCount = new LossyCount(1, (int)currentBucketId - 1 );
                countMap.put(generateKey(streamEvent), lCount);
            }
            // calculating all the events in the system which match the
            // requirement provided by the user
            List<String> keys = new ArrayList<String>();
            keys.addAll(countMap.keySet());
            for (String key : keys) {
                LossyCount lossyCount = countMap.get(key);
                if (lossyCount.getCount() >= ((support - error) * totalCount)) {
                    // among the selected events, if the newly arrive event is there we mark it as an inEvent
                    if(key.equals(generateKey(streamEvent))) {
                       complexEventChunk.add(streamEvent);
                    }
                }
            }
            if (totalCount % windowWidth == 0) {
                // its time to run the data-structure prune code
                keys = new ArrayList<String>();
                keys.addAll(countMap.keySet());
                for (String key : keys) {
                    LossyCount lossyCount = countMap.get(key);
                    if (lossyCount.getCount() + lossyCount.getBucketId() <= currentBucketId) {
                        log.info("Removing the Event: " + key + " from the window");
                        countMap.remove(key);
                        complexEventChunk.add(map.remove(key));
                    }
                }
            }

            streamEvent = next;
        }
        nextProcessor.process(complexEventChunk);
    }

    @Override
    public void start() {
        //Do nothing
    }

    @Override
    public void stop() {
        //Do nothing
    }

    @Override
    public Object[] currentState() {
        return new Object[]{countMap};
    }

    @Override
    public void restoreState(Object[] state) {
        countMap = (ConcurrentHashMap<String, LossyCount>) state[0];
    }

    private String generateKey(StreamEvent event) {      // for performance reason if its all attribute we don't do the attribute list check
        StringBuilder stringBuilder = new StringBuilder();
        if (variableExpressionExecutors.length == 0) {
            for (Object data : event.getOutputData()) {
                stringBuilder.append(data);
            }
        } else {
            for (VariableExpressionExecutor executor : variableExpressionExecutors) {
                stringBuilder.append(event.getAttribute(executor.getPosition()));
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public synchronized StreamEvent find(ComplexEvent matchingEvent, Finder finder) {
        return finder.find(matchingEvent, map.values(),streamEventCloner);
    }

    @Override
    public Finder constructFinder(Expression expression, MetaComplexEvent metaComplexEvent, ExecutionPlanContext executionPlanContext, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, EventTable> eventTableMap, int matchingStreamIndex, long withinTime) {
        return CollectionOperatorParser.parse(expression, metaComplexEvent, executionPlanContext, variableExpressionExecutors, eventTableMap, matchingStreamIndex, inputDefinition, withinTime);
    }

    public class LossyCount {
        int count;
        int bucketId;

        public LossyCount(int count, int bucketId) {
            this.count = count;
            this.bucketId = bucketId;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public int getBucketId() {
            return bucketId;
        }

        public void setBucketId(int bucketId) {
            this.bucketId = bucketId;
        }

        public LossyCount incrementCount(){
            this.count++;
            return this;
        }
    }
}


text:
<?php

namespace Psr\Error;

use ErrorException;
use PHPUnit_Framework_TestCase;

class ErrorHandlerTest extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->errorReporting = error_reporting(E_DEPRECATED);
    }

    protected function tearDown()
    {
        error_reporting($this->errorReporting);
    }

    public function handlerData()
    {
        //                               severity             isHandled
        return array(
            // standard severities - handled
            'Error'             => array(E_ERROR,             true),
            'User error'        => array(E_USER_ERROR,        true),
            'Recoverable error' => array(E_RECOVERABLE_ERROR, true),
            'Warning'           => array(E_WARNING,           true),
            'User warning'      => array(E_USER_WARNING,      true),
            'Notice'            => array(E_NOTICE,            true),
            'User notice'       => array(E_USER_NOTICE,       true),

            // standard severities - not handled
            'Deprecated'        => array(E_DEPRECATED,        false),
            'User deprecated'   => array(E_USER_DEPRECATED,   false),

            // uncommon severities
            'Parse error'       => array(E_PARSE,             true),
            'Core error'        => array(E_CORE_ERROR,        true),
            'Core warning'      => array(E_CORE_WARNING,      true),
            'Compile error'     => array(E_COMPILE_ERROR,     true),
            'Compile warning'   => array(E_COMPILE_WARNING,   true),
            'Strict'            => array(E_STRICT,            true),
            'All'               => array(E_ALL,               true),
        );
    }

    /**
     * @dataProvider handlerData
     */
    public function testHandler($severity, $isHandled)
    {
        $handler = new ErrorHandler;
        $error = null;
        $wasHandled = null;
        try {
            $wasHandled = $handler($severity, 'Error message.', '/path/to/file', 111);
        } catch (ErrorException $error) {}

        if ($isHandled) {
            $this->assertEquals(new ErrorException('Error message.', 0, $severity, '/path/to/file', 111), $error);
        } else {
            $this->assertFalse($wasHandled);
        }
    }

    /**
     * @dataProvider handlerData
     */
    public function testHandlerAtSuppression($severity, $isHandled)
    {
        $handler = new ErrorHandler;
        error_reporting(0);

        $this->assertSame(
            E_DEPRECATED !== $severity && E_USER_DEPRECATED !== $severity,
            $handler($severity, 'Error message.', '/path/to/file', 111)
        );
    }

    public function testHandlerOptionalArguments()
    {
        $handler = new ErrorHandler;
        $error = null;
        try {
            $handler(E_USER_NOTICE, 'Error message.');
        } catch (ErrorException $error) {}

        $this->assertEquals(new ErrorException('Error message.', 0, E_USER_NOTICE), $error);
        $this->assertSame('', $error->getFile());
        $this->assertSame(0, $error->getLine());
    }
}


text:
<?php

namespace Symfony\Component\Workflow\Event;

final class TransitionEvent extends Event
{
    public function setContext(array $context): void
    {
        $this->context = $context;
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Simplicity - Massive Admin Pack</title>

  <link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="assets/weather-icons/weather-icons.min.css">

  <link rel="stylesheet" type="text/css" href="assets/effects/menu-effects.css">

  <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Lato:400,100italic,100,300italic,300,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

  <link rel='stylesheet' type='text/css' href='assets/jquery-ui/ui-lightness/jquery-ui-1.10.3.custom.css' />
  <link rel='stylesheet' type='text/css' href='assets/morrischarts/morris.css' />
  <link rel='stylesheet' type='text/css' href='assets/fullcalendar/fullcalendar.css' />
  <link rel='stylesheet' type='text/css' href='assets/datatables/jquery.dataTables.css' />

  <link rel="stylesheet" type="text/css" href="css/styles-less.css">
  <link rel="stylesheet" type="text/css" href="css/responsive.css">
  <link rel="stylesheet" type="text/css" href="css/animate.css">
  <link rel="stylesheet" type="text/css" href="_demo/demo.css">

  <link rel="stylesheet" type="text/css" href="css/purchase-bar.css">

  <link rel="stylesheet" type="text/css" href="assets/icheck/flat/_all.css"/>
  <link rel="stylesheet" type="text/css" href="assets/bootstrap-wizards/prettify.css"/>
  <link rel="stylesheet" type="text/css" href="assets/fuelux/style.css"/>
  <link rel="shortcut icon" href="favicon.ico" type="image/png">
  <link rel="shortcut icon" type="image/png" href="favicon.ico" />

Simplicity

admin template

      Samantha Lenna Wilson

        Dashboard
        4

        Layouts

          Fixed Sidebar

          Collapsed Sidebar

          Fixed Header Bar

          Horizontal Menu Bar

        Animated Elements
        62

        Pages

          Coming Soon Page

          Login Page

          Register Page

          Mail Page

          Mail Compose Page

          404 Error Page

          500 Error Page

          Blank Page

          Profile Page

        Support Center

          Ticket Archive

          Ticket Response

        UI Elements

          Modals & Alerts

          ToolTips

          General

          Buttons

          Grids

          Calendar

          Tocify

          Tables

        Icons
        7

        Maps
        21

          Google Maps

          Vector Maps

        Progress Bars

        Forms

          General Form Elements

          Smart Form Elements

          Form Wizards

        Settings
        2

        Pricing Tables
        2

        Tabs & Accordions

        Projects

        Tasks

        Invoice

<input type="text" class="search" placeholder="Input your search..." />

Settings

My Profile

Sign Out

13

Inbox

Send

Draft

Compose

2

              Uploaded successfully
              1 minute ago

              Jenna commented on your link
              1 hour ago

              Jason invited you on a event
              3 hours ago

Forms

General Form Elements

Form Wizards

Thank you! Your submission has been received!

1Personal Information

2Billing Information

3Payment

              <form method="post" action="#" id="wizard-form-data" class="basic-form horizontal-form">

                      First name*
                      <input type="text" name="first-name" id="first-name" placeholder="Enter your first name" class="required" />
                      E-mail
                      <input type="text" name="email" id="email" placeholder="Enter your e-mail" />

                      Last Name*
                      <input type="last-name" name="last-name" id="last-name" placeholder="Enter your last name" class="required" />
                      Website (optional)
                      <input type="text" name="website" id="website" placeholder="Enter your website URL" />

                      Address*
                      <input type="text" name="address" id="address" placeholder="Enter your address" class="required" />
                      State*
                      <input type="text" name="state" id="state" placeholder="Enter your state" class="required" />

                          Zip/Postal Code*
                          <input type="text" name="zip" id="zip" placeholder="Enter your zip or postal code" class="required" />

                          Phone number*
                          <input type="text" name="phone" id="phone" placeholder="Enter your phone number" class="required" />

                      City*
                      <input type="text" name="city" id="city" placeholder="Enter your city" class="required" />
                      Country*
                      <input type="text" name="country" id="country" placeholder="Enter your country" class="required" />
                      Billing e-mail*
                      <input type="text" name="billing-email" id="billing-email" placeholder="Enter your billing e-mail" class="required" />

                      Account Holder Name*
                      <input type="text" name="account-holder-name" id="account-holder-name" placeholder="e.g. John Doe" class="required" />
                      Card Type*
                      <select name="card-type" id="card-type">
                        <option value="-">Card type</option>
                        <option value="visa">Visa</option>
                        <option value="master">Master</option>
                        <option value="amex">Amex</option>
                      </select>

                          Security Code*
                          <input type="text" name="security-code" id="security-code" placeholder="Credit card security code" class="required" />

                          Expiration date*
                          <select name="expiration-date" id="expiration-date">
                            <option value="-">Month</option>
                            <option value="1">January</option>
                            <option value="2">February</option>
                            <option value="3">March</option>
                            <option value="4">April</option>
                            <option value="5">May</option>
                            <option value="6">June</option>
                            <option value="7">July</option>
                            <option value="8">August</option>
                            <option value="9">September</option>
                            <option value="10">October</option>
                            <option value="11">November</option>
                            <option value="12">December</option>
                          </select>

                          Expiration year*
                          <select name="expiration-year" id="expiration-year">
                            <option value="-">Year</option>
                            <option value="2014">2014</option>
                            <option value="2015">2015</option>
                            <option value="2016">2016</option>
                            <option value="2017">2017</option>
                            <option value="2018">2018</option>
                            <option value="2019">2019</option>
                          </select>

                      Card Number*
                      <input type="text" name="card-number" id="card-number" placeholder="Enter your state" class="required" />
                      Country*
                      <input type="text" name="country" id="country" placeholder="Enter your country" class="required" />

              </form>

                <button type="button" class="btn btn-default  btn-prev"> Previous</button>
                <button type="button" class="btn btn-success btn-next" data-last="Finish">Next</button>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Overview</title>
<meta name="date" content="2017-02-02">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Packages

Package
Description

se.angergard.app

se.angergard.app.data

se.angergard.app.fx.editor

se.angergard.app.fx.group

se.angergard.app.fx.item

se.angergard.app.fx.project

se.angergard.app.fx.utils

se.angergard.app.io

se.angergard.junit

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.basex.query.expr.index;

import org.basex.data.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.util.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * This class defines a static database source for index operations.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class IndexStaticDb extends IndexDb {
  /**
   * Constructor.
   * @param data data reference
   * @param info input info
   */
  public IndexStaticDb(final Data data, final InputInfo info) {
    super(info);
    exprType.data(data);
  }

  @Override
  public void checkUp() {
  }

  @Override
  public Expr compile(final CompileContext cc) {
    return this;
  }

  @Override
  public boolean has(final Flag... flags) {
    return false;
  }

  @Override
  public boolean inlineable(final InlineContext ic) {
    return true;
  }

  @Override
  public VarUsage count(final Var var) {
    return VarUsage.NEVER;
  }

  @Override
  public IndexDb inline(final InlineContext ic) {
    return null;
  }

  @Override
  public boolean accept(final ASTVisitor visitor) {
    return true;
  }

  @Override
  public int exprSize() {
    return 1;
  }

  @Override
  public IndexDb copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return copyType(new IndexStaticDb(data(), info));
  }

  @Override
  Data data(final QueryContext qc) {
    return data();
  }

  @Override
  public boolean equals(final Object obj) {
    return obj instanceof IndexStaticDb && data() == ((IndexStaticDb) obj).data() &&
        super.equals(obj);
  }

  @Override
  public void toXml(final QueryPlan plan) {
    plan.add(plan.create(this));
  }

  @Override
  public void toString(final QueryString qs) {
    qs.quoted(Token.token(data().meta.name));
  }
}


text:
package com.heatonresearch.aifh.examples.randomize;

import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * A histogram panel.
 */
public class HistoPanel extends JPanel {

    public final int BAR_WIDTH = 10;

    private long evalCount;
    private long evalTime;
    private int evalRate;
    private long lastUpdate;
    private long generated;
    private long started;
    private int runtime;
    private double low;
    private double high;
    private final int[] boxes;
    private boolean uniformMode;
    private final DecimalFormat formatter = new DecimalFormat("#.##");
    private final NumberFormat intFormatter = NumberFormat.getNumberInstance();

    public HistoPanel() {
        this.boxes = new int[2000];
        reset();
    }

    public void reset() {
        this.evalCount = 0;
        this.evalTime = 0;
        this.evalRate = 0;
        this.lastUpdate = -1;
        this.generated = 0;
        this.started = -1;
        this.low = Double.POSITIVE_INFINITY;
        this.high = Double.NEGATIVE_INFINITY;
        this.runtime = 0;
        for (int i = 0; i < boxes.length; i++) {
            this.boxes[i] = 0;
        }
    }

    public void reportNumber(final double d) {
        if (lastUpdate == -1) {
            lastUpdate = System.currentTimeMillis();
            started = lastUpdate;
        }

        final long currentTime = System.currentTimeMillis();
        generated++;
        this.low = Math.min(this.low, d);
        this.high = Math.max(this.high, d);

        final int boxNumber = (int) ((d * 300.0) + 1000.0);
        if (boxNumber >= 0 && boxNumber < this.boxes.length) {
            this.boxes[boxNumber]++;
        }

        this.evalTime = (currentTime - started) - 5000;

        if (evalTime > 0) {
            evalCount++;
        }

        if ((currentTime - lastUpdate) > 1000) {
            this.runtime = (int) ((currentTime - started) / 1000);
            lastUpdate = currentTime;
            if (evalCount > 0) {
                evalRate = (int) (evalCount / evalTime);
            } else {
                evalRate = 0;
            }
            repaint();
        }
    }

    public boolean isUniformMode() {
        return uniformMode;
    }

    public void setUniformMode(final boolean uniformMode) {
        this.uniformMode = uniformMode;
    }

    public void paint(final Graphics g) {
        final int height = this.getHeight();
        final int width = this.getWidth();

        g.clearRect(0, 0, width, height);
        long gen = generated;
        gen /= 1024;

        final int h = g.getFontMetrics().getHeight();

        final int barCount = width / BAR_WIDTH;
        int mode = 0;
        for (final int boxe : this.boxes) {
            mode = Math.max(mode, boxe);
        }

        final int bar2box;
        int boxesIndex = 0;

        if (this.uniformMode) {
            bar2box = 1;
            boxesIndex = (this.boxes.length / 2) + bar2box;
        } else {
            bar2box = this.boxes.length / barCount;
        }

        for (int i = 0; i < barCount; i++) {
            int barAmount = 0;
            for (int j = 0; j < bar2box; j++) {
                barAmount += this.boxes[boxesIndex++];
            }
            barAmount /= bar2box;

            final double barRatio = (double) barAmount / mode;
            final int barHeight = (int) (barRatio * height);

            g.setColor(Color.CYAN);
            g.fillRect(i * BAR_WIDTH, height - barHeight, BAR_WIDTH, barHeight);
            g.setColor(Color.LIGHT_GRAY);
            g.drawRect(i * BAR_WIDTH, height - barHeight, BAR_WIDTH, barHeight);
        }

        NumberFormat.getNumberInstance().format(35634646);
        int y = h;

        g.setColor(Color.BLACK);
        g.drawString("Running for: " + this.intFormatter.format(runtime) + " seconds", 0, y);
        y += h;
        g.drawString("Generated: " + this.intFormatter.format(gen) + " thousand numbers", 0, y);
        y += h;
        g.drawString("Range: " + this.formatter.format(this.low)
                + " to " + this.formatter.format(this.high), 0, y);
        y += h;
        g.drawString("Rate: " + this.intFormatter.format(this.evalRate) + " nums/ms", 0, y);

    }
}


text:
set -e

cell='test'
keyspace='test_keyspace'
shard=0
uid_base=100
tablet_type='replica'
port_base=15100
grpc_port_base=16100
mysql_port_base=33100

script_root=`dirname "${BASH_SOURCE}"`
source $script_root/env.sh

dbconfig_flags="\
    -db-config-app-uname vt_app \
    -db-config-app-dbname vt_$keyspace \
    -db-config-app-charset utf8 \
    -db-config-dba-uname vt_dba \
    -db-config-dba-charset utf8 \
    -db-config-repl-uname vt_repl \
    -db-config-repl-dbname vt_$keyspace \
    -db-config-repl-charset utf8 \
    -db-config-filtered-uname vt_filtered \
    -db-config-filtered-dbname vt_$keyspace \
    -db-config-filtered-charset utf8"
init_db_sql_file="$VTROOT/config/init_db.sql"

case "$MYSQL_FLAVOR" in
  "MySQL56")
    export EXTRA_MY_CNF=$VTROOT/config/mycnf/master_mysql56.cnf
    ;;
  "MariaDB")
    export EXTRA_MY_CNF=$VTROOT/config/mycnf/master_mariadb.cnf
    ;;
  *)
    echo "Please set MYSQL_FLAVOR to MySQL56 or MariaDB."
    exit 1
    ;;
esac

mkdir -p $VTDATAROOT/backups

# Look for memcached.
memcached_path=`which memcached`
if [ -z "$memcached_path" ]; then
  echo "Can't find memcached. Please make sure it is available in PATH."
  exit 1
fi

# Start 3 vttablets by default.
# Pass a list of UID indices on the command line to override.
uids=${@:-'0 1 2'}

for uid_index in $uids; do
  uid=$[$uid_base + $uid_index]
  port=$[$port_base + $uid_index]
  grpc_port=$[$grpc_port_base + $uid_index]
  mysql_port=$[$mysql_port_base + $uid_index]
  printf -v alias '%s-%010d' $cell $uid
  printf -v tablet_dir 'vt_%010d' $uid

  echo "Starting MySQL for tablet $alias..."
  action="init -init_db_sql_file $init_db_sql_file"
  if [ -d $VTDATAROOT/$tablet_dir ]; then
    echo "Resuming from existing vttablet dir:"
    echo "    $VTDATAROOT/$tablet_dir"
    action='start'
  fi
  $VTROOT/bin/mysqlctl \
    -log_dir $VTDATAROOT/tmp \
    -tablet_uid $uid $dbconfig_flags \
    -mysql_port $mysql_port \
    $action

  echo "Starting vttablet for $alias..."
  $VTROOT/bin/vttablet \
    -log_dir $VTDATAROOT/tmp \
    -tablet-path $alias \
    -tablet_hostname `hostname -i` \
    -init_keyspace $keyspace \
    -init_shard $shard \
    -target_tablet_type $tablet_type \
    -health_check_interval 5s \
    -enable-rowcache \
    -rowcache-bin $memcached_path \
    -rowcache-socket $VTDATAROOT/$tablet_dir/memcache.sock \
    -backup_storage_implementation file \
    -file_backup_storage_root $VTDATAROOT/backups \
    -restore_from_backup \
    -port $port \
    -grpc_port $grpc_port \
    -binlog_player_protocol grpc \
    -service_map 'grpc-queryservice,grpc-tabletmanager,grpc-updatestream' \
    -pid_file $VTDATAROOT/$tablet_dir/vttablet.pid \
    $dbconfig_flags \
    > $VTDATAROOT/$tablet_dir/vttablet.out 2>&1 &

  echo "Access tablet $alias at http://$hostname:$port/debug/status"
done

disown -a


text:
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import alt from './utils/alt';
import Iso from 'iso';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';

const server = global.server = express();
const iso = new Iso();

server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname, 'public')));

//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const data = { title: '', description: '', css: '', body: '' };
    const css = [];
    const context = {
      onInsertCss: value => css.push(value),
      onSetTitle: value => data.title = value,
      onSetMeta: (key, value) => data[key] = value,
      onPageNotFound: () => statusCode = 404,
    };

    await Router.dispatch({ path: req.path, context }, (state, component) => {
      alt.bootstrap(alt.takeSnapshot());
      iso.add(
        ReactDOM.renderToString(component),
        alt.flush()
      );
      data.body = iso.render();
      data.css = css.join('');
    });

    const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
    res.status(statusCode).send('<!doctype html>\n' + html);
  } catch (err) {
    next(err);
  }
});

//
// Launch the server
// -----------------------------------------------------------------------------

server.listen(server.get('port'), () => {
  /* eslint-disable no-console */
  console.log('The server is running at http://localhost:' + server.get('port'));
  if (process.send) {
    process.send('online');
  }
});


text:
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Web;
using System.Windows;
using System.Windows.Input;

using log4net;

namespace EnergonSoftware.BackpackPlanner.DriveFileExplorer
{
    public partial class MainWindow
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(MainWindow));

        public PlayServicesManager PlayServicesManager { get; }

        private readonly ObservableCollection<Google.Apis.Drive.v3.Data.File> _files = new ObservableCollection<Google.Apis.Drive.v3.Data.File>();

        public MainWindow()
        {
            InitializeComponent();

            PlayServicesManager = new PlayServicesManager();
            DataContext = PlayServicesManager;

            FileList.ItemsSource = _files;
        }

        private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            await PlayServicesManager.DisconnectAsync();
        }

        private void MenuFileExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private async void MenuFileConnect_Click(object sender, RoutedEventArgs e)
        {
            await PlayServicesManager.ConnectAsync();
            if(!PlayServicesManager.IsConnected) {
                MessageBox.Show("There was an error connecting to Google Services!", "Connection Error", MessageBoxButton.OK);
                return;
            }

            var fileList = await PlayServicesManager.ListDriveAppFolderFilesAsync();
            Logger.Debug($"Retrieved {fileList.Count} files");

            _files.Clear();
            foreach(Google.Apis.Drive.v3.Data.File file in fileList) {
                _files.Add(file);
            }
        }

        private async void MenuFileDisconnect_Click(object sender, RoutedEventArgs e)
        {
            await PlayServicesManager.DisconnectAsync();
            _files.Clear();
        }

        private async void MenuViewRefresh_Click(object sender, RoutedEventArgs e)
        {
            if(!PlayServicesManager.IsConnected) {
                return;
            }

            var fileList = await PlayServicesManager.ListDriveAppFolderFilesAsync();
            Logger.Debug($"Retrieved {fileList.Count} files");

            _files.Clear();
            foreach(Google.Apis.Drive.v3.Data.File file in fileList) {
                _files.Add(file);
            }
        }

        private async void FileList_Drop(object sender, DragEventArgs e)
        {
            if(!e.Data.GetDataPresent(DataFormats.FileDrop)) {
                return;
            }

            var files = (string[])e.Data.GetData(DataFormats.FileDrop) ?? new string[0];
            foreach(string filePath in files) {
                string fileName = Path.GetFileName(filePath);
                Google.Apis.Drive.v3.Data.File existingDriveFile = _files.FirstOrDefault(x => x.Name == fileName);
                using(Stream stream = new FileStream(filePath, FileMode.Open)) {
                    Google.Apis.Drive.v3.Data.File newDriveFile;
                    if(null != existingDriveFile) {
                        MessageBoxResult result = MessageBox.Show($"The file {fileName} already exists, do you wish to replace it?", "Replace File", MessageBoxButton.YesNo);
                        if(result == MessageBoxResult.No) {
                            return;
                        }

                        newDriveFile = await PlayServicesManager.UpdateFileInDriveAppFolderAsync(existingDriveFile, Path.GetFileName(filePath), MimeMapping.GetMimeMapping(filePath), stream);
                        if(null == newDriveFile) {
                            MessageBox.Show($"There was an error saving the file {filePath}!", "Save Error", MessageBoxButton.OK);
                            continue;
                        }

                        Logger.Debug($"Updated file: {newDriveFile.Name} ({newDriveFile.Id})");
                        _files.Remove(existingDriveFile);
                        _files.Add(newDriveFile);
                    } else {
                        newDriveFile = await PlayServicesManager.SaveFileToDriveAppFolderAsync(Path.GetFileName(filePath), MimeMapping.GetMimeMapping(filePath), stream);
                        if(null == newDriveFile) {
                            MessageBox.Show($"There was an error saving the file {filePath}!", "Save Error", MessageBoxButton.OK);
                            continue;
                        }

                        Logger.Debug($"Added new file: {newDriveFile.Name} ({newDriveFile.Id})");
                        _files.Add(newDriveFile);
                    }
                }
            }
        }

        private async void FileListItem_Download(object sender, RoutedEventArgs e)
        {
            Google.Apis.Drive.v3.Data.File selectedFile = _files.ElementAt(FileList.SelectedIndex);
            if(null == selectedFile) {
                return;
            }

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if(dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) {
                return;
            }

            string filePath = Path.Combine(dialog.SelectedPath, selectedFile.Name);
            if(File.Exists(filePath)) {
                MessageBoxResult result = MessageBox.Show($"The file {filePath} already exists, do you wish to replace it?", "Replace File", MessageBoxButton.YesNo);
                if(result == MessageBoxResult.No) {
                    return;
                }
            }

            using(Stream remoteStream = await PlayServicesManager.DownloadFileFromDriveAppFolderAsync(selectedFile)) {
                if(null == remoteStream) {
                    MessageBox.Show("There was an error downloading the file!", "Download Error", MessageBoxButton.OK);
                    return;
                }

                using(Stream localStream = new FileStream(filePath, FileMode.Create)) {
                    await remoteStream.CopyToAsync(localStream);
                }
            }
        }

        private async void FileListItem_Delete(object sender, RoutedEventArgs e)
        {
            Google.Apis.Drive.v3.Data.File selectedFile = _files.ElementAt(FileList.SelectedIndex);
            if(null == selectedFile) {
                return;
            }

            MessageBoxResult result = MessageBox.Show($"Are you sure you wish to delete {selectedFile.Name}?", "Confirm Delete", MessageBoxButton.YesNo);
            if(result == MessageBoxResult.No) {
                return;
            }

            await PlayServicesManager.DeleteFileFromDriveAppFolderAsync(selectedFile);
            _files.Remove(selectedFile);
        }

        private void FileListItem_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            Google.Apis.Drive.v3.Data.File selectedFile = _files.ElementAt(FileList.SelectedIndex);
            if(null == selectedFile) {
                return;
            }

Logger.Debug($"TODO: double click: {selectedFile.Name}");
        }
    }
}


text:
"""Tests for Gremlin database."""
import os
import requests
import pprint

from behave import given, then, when
from urllib.parse import urljoin
from semantic_version import Version
import time
from src.json_utils import *
from src.utils import split_comma_separated_list
from src.graph_db_query import Query

import logging

# set up the logging for this module
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

# no data should have timestamp with earlier date than 2015-01-01, simply because
# this project was started after this date
BAYESSIAN_PROJECT_START_DATE = time.mktime(time.strptime("2015-01-01", "%Y-%m-%d"))

@when('I access Gremlin API')
def gremlin_url_access(context):
    """Access the Gremlin service API using the HTTP POST method."""
    post_query(context, "")

@when('I ask Gremlin to find all vertexes having property {name} set to {value}')
def gremlin_search_vertexes(context, name, value):
    """Perform simple query to the Gremlin for all vertexes having the specified property."""
    query = Query().has(name, value)
    post_query(context, query)

@when('I ask Gremlin to find number of vertexes for the ecosystem {ecosystem}')
def gremlin_search_vertexes_for_the_ecosystem(context, ecosystem):
    """Perform simple query to the Gremlin for all vertexes having the specified property."""
    query = Query().has("pecosystem", ecosystem).count()
    post_query(context, query)

@when('I ask Gremlin to find all versions of the package {package:S} in the ecosystem {ecosystem}')
def gremlin_find_package(context, package, ecosystem):
    """Try to find all versions of the given package in the selected ecosystem."""
    query = Query().has("ecosystem", ecosystem).has("name", package).out("has_version")
    post_query(context, query)

@when('I ask Gremlin to find the package {package:S} version {version} in the ecosystem '
      '{ecosystem}')
def gremlin_find_package_version(context, package, version, ecosystem):
    """Try to find the package with version in the selected ecosystem."""
    query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version)
    post_query(context, query)

@when('I ask Gremlin to find the package {package:S} in the ecosystem {ecosystem}')
def gremlin_find_package(context, package, ecosystem):
    """Try to find the package in the selected ecosystem."""
    query = Query().has("ecosystem", ecosystem).has("name", package)
    post_query(context, query)

@when('I remember the current time')
def remember_current_time(context):
    """Remember the current time for further checks."""
    context.current_time = time.time()

@when('I read the last update time for the package {package:S} version {version} in the ecosystem'
      ' {ecosystem}')
def gremlin_read_last_update_time(context, package, version, ecosystem):
    """Read the last update timestamp."""
    query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version).\
        first().value("last_updated")
    post_query(context, query)

@when('I wait for the update in the graph database for the package {package:S} version {version}'
      ' in the ecosystem {ecosystem}')
def wait_for_update_in_graph_db(context, package, version, ecosystem):
    """Wait until the package metadata is not updated in the graph database."""
    timeout = 300 * 60
    sleep_amount = 10  # we don't want to overload the graph db, so 10 seconds seems to be good
    max_iters = timeout // sleep_amount

    start_time = time.time()
    log.info("start time: " + str(start_time))

    for i in range(max_iters):
        gremlin_read_last_update_time(context, package, version, ecosystem)
        timestamp = get_timestamp_from_gremlin(context)
        log.info("Iteration {i} of {max}: start time: {t1}, timestamp: {t2}".format(i=i,
                                                                                max=max_iters,
                                                                                t1=start_time,
                                                                                t2=timestamp))
        if timestamp > start_time:
            return
        time.sleep(sleep_amount)
    raise Exception('Timeout waiting for the new package metadata in graph DB!')

def post_query(context, query):
    """Post the already constructed query to the Gremlin."""
    data = {"gremlin": str(query)}
    context.response = requests.post(context.gremlin_url, json=data)

@then('I should get valid Gremlin response')
def valid_gremlin_response(context):
    """Check that the Gremlin response is valid."""
    check_request_id_value_in_json_response(context, "requestId")

    data = context.response.json()
    assert data, "Gremlin does not send a proper response"

    check_gremlin_status_node(data)
    check_gremlin_result_node(data)

@then('I should get zero vertexes')
@then('I should get {num:d} vertexes')
def check_vertexes_count(context, num=0):
    """Check the number of vertexes returned in Gremlin response."""
    data, meta = get_results_from_gremlin(context)
    vertexes = len(data)
    assert vertexes == num, "Expected %d vertexes, but got %d instead" % (num, vertexes)

@then('I should find at least one such vertex')
def check_non_zero_vertexes_count(context):
    """Check the number of vertexes returned in Gremlin response."""
    data, meta = get_results_from_gremlin(context)
    vertexes = len(data)
    assert vertexes > 0, "Expected at least one vertex, but got zero instead"

def get_node_value_from_properties_returned_by_gremlin(context, node_name):
    """Try to retrieve node value from the 'properties' node returned by Gremlin."""
    data, meta = get_results_from_gremlin(context)
    assert len(data) == 1, "Expected precisely one vertex with package data"
    assert data[0] is not None
    properties = check_and_get_attribute(data[0], "properties")
    return get_node_value(properties, node_name)

@then('I should find the package {package} name in the Gremlin response')
def check_package_name(context, package):
    """Check the package name in Gremlin response."""
    name = get_node_value_from_properties_returned_by_gremlin(context, "name")
    assert name == package, \
        "Returned package name '{name}' is different from expected name '{package}'" \
        .format(name=name, package=package)

@then('I should find the ecosystem {ecosystem} name in the Gremlin response')
def check_ecosystem_name(context, ecosystem):
    """Check the ecosystem name in Gremlin response."""
    name = get_node_value_from_properties_returned_by_gremlin(context, "ecosystem")
    assert name == ecosystem, \
        "Returned ecosystem name '{name}' is different from expected name '{ecosystem}'" \
        .format(name=name, ecosystem=ecosystem)

@then('I should find at least one package in the Gremlin response')
@then('I should find at least {expected:d} packages in the Gremlin response')
def check_number_of_packages_returned(context, expected=1):
    """Check the number of returned packages."""
    data, meta = get_results_from_gremlin(context)
    found = len(data)

    assert found >= expected, \
        "Expected at least %d packages, but %d was found instead" % (expected, found)

@then('I should find that all found packages have valid timestamp with the last update time')
def check_timestamp_for_all_packages_in_gremlin_response(context):
    """Check if the last_updated attribute exists and if it contain proper timestamp."""
    data, meta = get_results_from_gremlin(context)

    for package in data:
        properties = check_and_get_attribute(package, "properties")
        test_last_updated_attribute(properties)

@then('I should find that the package data is {comparison} than remembered time')
def package_data_timestamp_comparison_with_remembered_time(context, comparison):
    """Check if the last_updated attribute is older or newer than remembered time.

    The timestamp is checked for all package versions.
    """
    remembered_time = context.current_time
    data, meta = get_results_from_gremlin(context)

    for package in data:
        properties = check_and_get_attribute(package, "properties")
        last_updated = check_and_get_attribute(properties, "last_updated")
        value = check_and_get_attribute(last_updated[0], "value")
        if comparison == "older":
            assert value < remembered_time
        elif comparison == "newer":
            assert value > remembered_time

def get_results_from_gremlin(context):
    """Try to take the results from the Gremlin response."""
    data = context.response.json()
    result = check_and_get_attribute(data, "result")
    data = check_and_get_attribute(result, "data")
    meta = check_and_get_attribute(result, "meta")
    return data, meta

def check_gremlin_status_node(data):
    """Check the basic structure of the 'status' node in Gremlin response."""
    status = check_and_get_attribute(data, "status")
    message = check_and_get_attribute(status, "message")
    code = check_and_get_attribute(status, "code")
    attributes = check_and_get_attribute(status, "attributes")

    assert message == ""
    assert code == 200

    # this node should be empty
    assert not attributes

def check_gremlin_result_node(data):
    """Check the basic structure of the 'result' node in Gremlin response."""
    result = check_and_get_attribute(data, "result")
    data = check_and_get_attribute(result, "data")
    meta = check_and_get_attribute(result, "meta")

    assert type(data) is list
    assert type(meta) is dict

@then('I should find the following properties ({properties}) in all found packages')
def check_properties_in_results(context, properties):
    """Check if all given properties can be found in all packages returned by Gremlin."""
    data, meta = get_results_from_gremlin(context)

    expected_properties = split_comma_separated_list(properties)

    # we need to check if all expected properties are really returned by the Gremlin
    for package in data:
        check_attribute_presence(package, "properties")
        properties = package["properties"].keys()

        assert properties is not None

        for expected_property in expected_properties:
            if expected_property not in properties:
                # print examined data so users would know what happened
                formatted_data = pprint.pformat(package)
                message = "Required property could not be found: {prop}\n" \
                          "Tested Gremlin results:\n{r}"
                raise Exception(message.format(prop=expected_property, r=formatted_data))

@then('I should not find any property apart from ({properties}) in all found packages')
def check_unexpected_properties_in_results(context, properties):
    """Check if only given optional properties can be found in all packages returned by Gremlin."""
    data, meta = get_results_from_gremlin(context)

    expected_properties = split_comma_separated_list(properties)

    for package in data:
        check_attribute_presence(package, "properties")
        properties = package["properties"].keys()

        assert properties is not None

        for prop in properties:
            # check that the property is contained in a list of expected properties
            if prop not in expected_properties:
                raise Exception("Unexpected property has been found: {prop}".format(
                                prop=prop))

def get_timestamp_from_gremlin(context):
    """Get the value of timestamp attribute."""
    data, meta = get_results_from_gremlin(context)
    assert len(data) == 1
    return data[0]

@then('I should get a valid timestamp represented as UNIX time')
def check_unix_timestamp(context):
    """Check that only proper timestamp is returned in Gremlin response."""
    timestamp = get_timestamp_from_gremlin(context)
    assert type(timestamp) is float

@then('I should find that the returned timestamp is {comparison} than remembered time')
def check_package_version_timestamp_comparison_with_remembered_time(context, comparison):
    """Check if the last_updated attribute is older or newer than remembered time."""
    remembered_time = context.current_time
    timestamp = get_timestamp_from_gremlin(context)
    if comparison == "older":
        assert timestamp < remembered_time
    elif comparison == "newer":
        assert timestamp > remembered_time

def read_property_value_from_gremlin_response(context, property_name):
    """Read property value from the Gremlin response with all checks."""
    data, meta = get_results_from_gremlin(context)
    package = data[0]
    properties = check_and_get_attribute(package, "properties")

    # try to retrieve list of id+value pairs
    id_values = check_and_get_attribute(properties, property_name)

    # we expect list with one value only
    assert type(id_values) is list and len(id_values) == 1
    id_value = id_values[0]

    # check the content of 'value' attribute
    return check_and_get_attribute(id_value, "value")

@then('I should find that the {property_name} property is set to {expected_value} in the package '
      'properties')
def check_property_value(context, property_name, expected_value):
    """Check if the property is set to expected value for the first package returned by Gremlin."""
    value = read_property_value_from_gremlin_response(context, property_name)

    assert value == expected_value, ("The property {p} value is set to '{value}', not to "
                                     "'{expected_value}").format(p=property_name, value=value,
                                                                 expected_value=expected_value)

@then('I should find that the {property_name} property is higher than or equal to '
      '{expected_value} in the package properties')
def check_latest_version_property_value(context, property_name, expected_value):
    """Check if the latest_version property contains expected value."""
    value = read_property_value_from_gremlin_response(context, property_name)
    try:
        assert Version.coerce(value) >= Version(expected_value)
    except Exception:
        data, meta = get_results_from_gremlin(context)
        print("Metadata returned by Gremlin:")
        pprint.pprint(meta)
        print("Data returned by Gremlin:")
        pprint.pprint(data)
        raise

@then('I should find that the {property_name} property has numeric value greater than or equal '
      'to {expected:d}')
def check_numeric_property_value(context, property_name, expected):
    """Check if the property has assigned numeric value that is greater than or equal to X."""
    value = read_property_value_from_gremlin_response(context, property_name)

    numeric = convert_to_number(value)
    assert numeric >= expected, ("The property {p} value is set to '{value}', but it should be "
                                 "greater than or equal to {expected").format(p=property_name,
                                                                              value=value,
                                                                              expected=expected)

@then('I should find that all information about package have correct structure')
def check_package_structure(context):
    """Check all items with package metadata returned by Gremlin."""
    data, meta = get_results_from_gremlin(context)
    assert len(data) == 1, "Exactly one vertex expected, but {n} has been found".format(n=len(data))

    # now we know we have exactly one vertex, so let's check its content
    item = data[0]

    labelValue = check_and_get_attribute(item, "label")
    assert labelValue == "vertex" or labelValue == "Package"

    properties = check_and_get_attribute(item, "properties")
    test_last_updated_attribute(properties)
    test_vertex_label(properties, "Package")
    test_github_related_properties(properties, False)
    test_libio_related_properties(properties, False)

@then('I should find that all information about package versions have correct structure')
def check_package_versions_structure(context):
    """Check all items with package version metadata returned by Gremlin."""
    data, meta = get_results_from_gremlin(context)
    assert len(data) > 0, "At least one vertex expected, but 0 has been found"

    # check all n items found in data
    for item in data:
        labelValue = check_and_get_attribute(item, "label")
        # the following check is blocked by: 1934
        # assert labelValue == "vertex" or labelValue == "Version"
        properties = check_and_get_attribute(item, "properties")
        test_last_updated_attribute(properties)
        test_cm_loc(properties)
        test_cm_num_files(properties)
        test_cm_avg_cyclomatic_complexity(properties)
        test_cve_ids(properties)

def convert_to_number(value):
    """Convert the value, that can be string, int, or float, to number."""
    if isinstance(value, (int, float)):
        return value

    scale = get_scale(value)
    if scale is not None:
        return float(value[:-1]) * scale
    else:
        return float(value)

def get_scale(value):
    """Get the scale for a numeric value stored as a string.

    The scale is used for store libio attributes, dunno why.
    """
    scales = {
        "k": 1000,
        "m": 1000000}
    return scales.get(value[-1].lower())

def test_last_updated_attribute(properties):
    """Check that the 'last_updated' attribute contains proper timestamp."""
    now = time.time()
    last_updated = check_and_get_attribute(properties, "last_updated")
    value = check_and_get_attribute(last_updated[0], "value")
    assert value >= BAYESSIAN_PROJECT_START_DATE
    assert value <= now

def get_node_value(properties, property_name):
    """Retrieve the value of node taken from properties returned by Gremlin.

    Please note, that each property is an array of id+value pairs and in
    this case we are interested only in the first pair.
    """
    node = check_and_get_attribute(properties, property_name)
    assert node[0] is not None
    return check_and_get_attribute(node[0], "value")

def check_integer_property_value(properties, property_name, additional_check=None):
    """Check if the node value is valid integer."""
    value = get_node_value(properties, property_name)
    assert type(value) is int

    # additional_check might be lambda expression
    if additional_check is not None:
        assert additional_check(value),\
            "Additional check has failed for the integer value {v}".format(v=value)

def check_libio_number_property_value(properties, property_name, additional_check=None):
    """Check the 'numeric' value used in libraries.io properties.

    Such values are stored as string with format like:
    100
    92.9K
    10M

    Please see https://github.com/openshiftio/openshift.io/issues/2023 for further info.
    """
    value = get_node_value(properties, "libio_dependents_projects")
    value = convert_to_number(value)
    # additional_check might be lambda expression
    if additional_check is not None:
        assert additional_check(value),\
            "Additional check has failed for the numeric value {v}".format(v=value)

def check_float_property_value(properties, property_name, additional_check=None):
    """Check if the node value is valid float."""
    value = get_node_value(properties, property_name)
    assert type(value) is float

    # additional_check might be lambda expression
    if additional_check is not None:
        assert additional_check(value),\
            "Additional check has failed for the floating point value {v}".format(v=value)

def check_string_property_value(properties, property_name, expected_value):
    """Check if the node value is a string with expected value."""
    value = get_node_value(properties, property_name)
    assert value == expected_value, "Property '{p}' should have the value '{e}', " + \
        "but the value '{v}' was found instead.".format(p=property_name, e=expected_value, v=value)

def test_cm_loc(properties, expected_property=False):
    """Check the property 'cm_loc'."""
    if expected_property or "cm_loc" in properties:
        check_integer_property_value(properties, "cm_loc")

def test_cm_avg_cyclomatic_complexity(properties, expected_property=False):
    """Check the property 'cm_avg_cyclomatic_complexity'."""
    if expected_property or "cm_avg_cyclomatic_complexity" in properties:
        check_float_property_value(properties, "cm_avg_cyclomatic_complexity")

def test_cm_num_files(properties, expected_property=False):
    """Check the property 'cm_num_files'."""
    if expected_property or "cm_num_files" in properties:
        check_integer_property_value(properties, "cm_num_files")

def test_libio_related_properties(properties, expected_properties=False):
    """Check all properties related to Libraries.io."""
    if expected_properties or "libio_latest_release" in properties:
        check_float_property_value(properties, "libio_latest_release", lambda v: v >= 0.0)

    numeric_property_names = [
        "libio_dependents_projects",
        "libio_dependents_repos",
        "libio_total_releases"
    ]
    for numeric_property_name in numeric_property_names:
        if expected_properties or numeric_property_name in properties:
            check_libio_number_property_value(properties, "libio_dependents_projects",
                                              lambda v: v >= -1)

def test_github_related_properties(properties, expected_properties=False):
    """Check all properties related to GitHub."""
    integer_property_names = [
        "gh_contributors_count",
        "gh_forks",
        "gh_open_issues_count",
        "gh_issues_last_month_closed",
        "gh_issues_last_year_closed",
        "gh_prs_last_month_closed",
        "gh_prs_last_month_opened",
        "gh_prs_last_year_closed",
        "gh_prs_last_year_opened",
        "gh_stargazers",
        "gh_subscribers_count"
    ]
    for integer_property_name in integer_property_names:
        if expected_properties or integer_property_name in properties:
            check_integer_property_value(properties, integer_property_name, lambda cnt: cnt >= -1)

def test_vertex_label(properties, expected_value):
    """Check the property 'vertex_label'."""
    value = get_node_value(properties, "vertex_label")
    check_string_property_value(properties, "vertex_label", expected_value)

def test_cve_ids(properties, expected_property=False):
    """Check all CVE entries found for the package.

    The format for CVE is: CVE ID:score.
    """
    if expected_property or "cve_ids" in properties:
        cve_ids = check_and_get_attribute(properties, "cve_ids")
        for cve_id in cve_ids:
            cve = cve_id["value"]
            check_cve_value(cve, True)


text:
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.4.3...0.5.0)

**Merged pull requests:**

- Implements Data Source [\#7](https://github.com/pavankataria/SwiftDataTables/pull/7) ([pavankataria](https://github.com/pavankataria))

## [0.4.3](https://github.com/pavankataria/SwiftDataTables/tree/0.4.3) (2017-03-22)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.4.2...0.4.3)

## [0.4.2](https://github.com/pavankataria/SwiftDataTables/tree/0.4.2) (2017-03-22)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.4.1...0.4.2)

## [0.4.1](https://github.com/pavankataria/SwiftDataTables/tree/0.4.1) (2017-03-17)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.4.0...0.4.1)

## [0.4.0](https://github.com/pavankataria/SwiftDataTables/tree/0.4.0) (2017-03-17)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.3.1...0.4.0)

**Implemented enhancements:**

- Implements a Search Bar [\#6](https://github.com/pavankataria/SwiftDataTables/pull/6) ([pavankataria](https://github.com/pavankataria))

## [0.3.1](https://github.com/pavankataria/SwiftDataTables/tree/0.3.1) (2017-03-15)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.3.0...0.3.1)

**Implemented enhancements:**

- Trims the project [\#5](https://github.com/pavankataria/SwiftDataTables/pull/5) ([pavankataria](https://github.com/pavankataria))

## [0.3.0](https://github.com/pavankataria/SwiftDataTables/tree/0.3.0) (2017-03-13)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.7...0.3.0)

**Implemented enhancements:**

- Improved sorting algorithm - Automatically Infer the type of the data passed in! [\#4](https://github.com/pavankataria/SwiftDataTables/pull/4) ([pavankataria](https://github.com/pavankataria))

## [0.2.7](https://github.com/pavankataria/SwiftDataTables/tree/0.2.7) (2017-03-11)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.6...0.2.7)

**Implemented enhancements:**

- Implements Default ordering configuration [\#3](https://github.com/pavankataria/SwiftDataTables/pull/3) ([pavankataria](https://github.com/pavankataria))

## [0.2.6](https://github.com/pavankataria/SwiftDataTables/tree/0.2.6) (2017-03-11)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.4...0.2.6)

**Implemented enhancements:**

- Scale to fill content view [\#2](https://github.com/pavankataria/SwiftDataTables/pull/2) ([pavankataria](https://github.com/pavankataria))

**Fixed bugs:**

- Scale to fill content view [\#2](https://github.com/pavankataria/SwiftDataTables/pull/2) ([pavankataria](https://github.com/pavankataria))

## [0.2.4](https://github.com/pavankataria/SwiftDataTables/tree/0.2.4) (2017-03-10)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.3...0.2.4)

## [0.2.3](https://github.com/pavankataria/SwiftDataTables/tree/0.2.3) (2017-03-10)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.2...0.2.3)

## [0.2.2](https://github.com/pavankataria/SwiftDataTables/tree/0.2.2) (2017-03-10)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2.1...0.2.2)

## [0.2.1](https://github.com/pavankataria/SwiftDataTables/tree/0.2.1) (2017-03-10)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.2...0.2.1)

## [0.2](https://github.com/pavankataria/SwiftDataTables/tree/0.2) (2017-03-10)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.1.1...0.2)

**Implemented enhancements:**

- Image bundle [\#1](https://github.com/pavankataria/SwiftDataTables/pull/1) ([pavankataria](https://github.com/pavankataria))

## [0.1.1](https://github.com/pavankataria/SwiftDataTables/tree/0.1.1) (2017-03-09)
[Full Changelog](https://github.com/pavankataria/SwiftDataTables/compare/0.1.0...0.1.1)

## [0.1.0](https://github.com/pavankataria/SwiftDataTables/tree/0.1.0) (2017-03-09)

\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*


text:
trident
=======

My sample codes about using trident


text:
require "chef/node/common_api"
require "chef/node/mixin/state_tracking"
require "chef/node/mixin/immutablize_array"
require "chef/node/mixin/immutablize_hash"

class Chef
  class Node

    module Immutablize
      def immutablize(value)
        case value
        when Hash
          ImmutableMash.new(value, __root__, __node__, __precedence__)
        when Array
          ImmutableArray.new(value, __root__, __node__, __precedence__)
        else
          value
        end
      end
    end

    # == ImmutableArray
    # ImmutableArray is used to implement Array collections when reading node
    # attributes.
    #
    # ImmutableArray acts like an ordinary Array, except:
    # * Methods that mutate the array are overridden to raise an error, making
    #   the collection more or less immutable.
    # * Since this class stores values computed from a parent
    #   Chef::Node::Attribute's values, it overrides all reader methods to
    #   detect staleness and raise an error if accessed when stale.
    class ImmutableArray < Array
      include Immutablize

      alias :internal_push :<<
      private :internal_push

      def initialize(array_data = [])
        array_data.each do |value|
          internal_push(immutablize(value))
        end
      end

      # For elements like Fixnums, true, nil...
      def safe_dup(e)
        e.dup
      rescue TypeError
        e
      end

      def dup
        Array.new(map { |e| safe_dup(e) })
      end

      def to_a
        a = Array.new
        each do |v|
          a <<
            case v
            when ImmutableArray
              v.to_a
            when ImmutableMash
              v.to_hash
            else
              v
            end
        end
        a
      end

      # for consistency's sake -- integers 'converted' to integers
      def convert_key(key)
        key
      end

      prepend Chef::Node::Mixin::StateTracking
      prepend Chef::Node::Mixin::ImmutablizeArray
    end

    # == ImmutableMash
    # ImmutableMash implements Hash/Dict behavior for reading values from node
    # attributes.
    #
    # ImmutableMash acts like a Mash (Hash that is indifferent to String or
    # Symbol keys), with some important exceptions:
    # * Methods that mutate state are overridden to raise an error instead.
    # * Methods that read from the collection are overriden so that they check
    #   if the Chef::Node::Attribute has been modified since an instance of
    #   this class was generated. An error is raised if the object detects that
    #   it is stale.
    # * Values can be accessed in attr_reader-like fashion via method_missing.
    class ImmutableMash < Mash
      include Immutablize
      include CommonAPI

      alias :internal_set :[]=
      private :internal_set

      def initialize(mash_data = {})
        mash_data.each do |key, value|
          internal_set(key, immutablize(value))
        end
      end

      def public_method_that_only_deep_merge_should_use(key, value)
        internal_set(key, immutablize(value))
      end

      alias :attribute? :has_key?

      def method_missing(symbol, *args)
        if symbol == :to_ary
          super
        elsif args.empty?
          if key?(symbol)
            self[symbol]
          else
            raise NoMethodError, "Undefined method or attribute `#{symbol}' on `node'"
          end
          # This will raise a ImmutableAttributeModification error:
        elsif symbol.to_s =~ /=$/
          key_to_set = symbol.to_s[/^(.+)=$/, 1]
          self[key_to_set] = (args.length == 1 ? args[0] : args)
        else
          raise NoMethodError, "Undefined node attribute or method `#{symbol}' on `node'"
        end
      end

      # Mash uses #convert_value to mashify values on input.
      # Since we're handling this ourselves, override it to be a no-op
      def convert_value(value)
        value
      end

      # NOTE: #default and #default= are likely to be pretty confusing. For a
      # regular ruby Hash, they control what value is returned for, e.g.,
      #   hash[:no_such_key] #=> hash.default
      # Of course, 'default' has a specific meaning in Chef-land

      def dup
        Mash.new(self)
      end

      def to_hash
        h = Hash.new
        each_pair do |k, v|
          h[k] =
            case v
            when ImmutableMash
              v.to_hash
            when ImmutableArray
              v.to_a
            else
              v
            end
        end
        h
      end

      prepend Chef::Node::Mixin::StateTracking
      prepend Chef::Node::Mixin::ImmutablizeHash
    end
  end
end