text:
	FTC UI CREATION
	----------------------------------------------------------
	* Template functions for quickly setting up the UI elements used by FTC.
	* Eeach template accepts the primary arguments needed for the control type.
	* Additional advanced properties must be set manually after creation.
  ]]--

--[[
 * Configure custom fonts
 ]]--
FTC.Fonts = {}
function FTC.Fonts.meta( size )
	local size = size or 14
	return 'FoundryTacticalCombat/lib/fonts/Metamorphous.otf|'..size..'|soft-shadow-thick'
end

FTC.UI = {}

--[[
 * Top Level Window
 ]]--
function FTC.UI.TopLevelWindow( name , parent , dims , anchor , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( #dims ~= 2 ) then return end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	hidden = ( hidden == nil ) and false or hidden

	-- Create the container
	local window = FTC.Chain( WINDOW_MANAGER:CreateTopLevelWindow( name ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetHidden( hidden )
	.__END
	return window
end

--[[
 * Generic Control
 ]]--
function FTC.UI.Control( name , parent , dims , anchor , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	hidden = ( hidden == nil ) and false or hidden

	-- Create the control
	local control = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_CONTROL ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetHidden( hidden )
	.__END
	return control
end

--[[
 * Backdrop
 ]]--
function FTC.UI.Backdrop( name , parent , dims , anchor , center , edge , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	center = ( center ~= nil and #center == 4 ) and center or { 0,0,0,0.4 }
	edge = ( edge ~= nil and #edge == 4 ) and edge or { 0,0,0,0.6 }
	hidden = ( hidden == nil ) and false or hidden

	-- Create the backdrop
	local control = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_BACKDROP ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetCenterColor( center[1] , center[2] , center[3] , center[4] )
		:SetEdgeColor( edge[1] , edge[2] , edge[3] , edge[4] )
		:SetEdgeTexture("",8,1,2)
		:SetHidden( hidden )
	.__END
	return control
end

--[[
 * Label
 ]]--
function FTC.UI.Label( name , parent , dims , anchor , font , color , align , text , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	font 	= ( font == nil ) and "ZoFontGame" or font
	color 	= ( color ~= nil and #color == 4 ) and color or { 1 , 1 , 1 , 1 }
	align 	= ( align ~= nil and #align == 2 ) and align or { 1 , 1 }
	hidden 	= ( hidden == nil ) and false or hidden

	-- Create the label
	local label = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_LABEL ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetFont( font )
		:SetColor( color[1] , color[2] , color[3] , color[4] )
		:SetHorizontalAlignment( align[1] )
		:SetVerticalAlignment( align[2] )
		:SetText( text )
		:SetHidden( hidden )
	.__END
	return label
end

--[[
 * Status Bar
 ]]--
function FTC.UI.Statusbar( name , parent , dims , anchor , color , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	color = ( color ~= nil and #color == 4 ) and color or { 1 , 1 , 1 , 1 }
	hidden = ( hidden == nil ) and false or hidden

	-- Create the backdrop
	local backdrop = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_STATUSBAR ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetColor( color[1] , color[2] , color[3] , color[4] )
		:SetHidden( hidden )
	.__END
	return backdrop
end

--[[
 * Texture
 ]]--
function FTC.UI.Texture( name , parent , dims , anchor , tex , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	if ( tex == nil ) then tex = '/esoui/art/icons/icon_missing.dds' end
	hidden = ( hidden == nil ) and false or hidden

	-- Create the backdrop
	local texture = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_TEXTURE ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetTexture(tex)
		:SetHidden( hidden )
	.__END
	return texture
end

--[[
 * Cooldown
 ]]--
function FTC.UI.Cooldown( name , parent , dims , anchor , color , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	color = ( color ~= nil and #color == 4 ) and color or { 1 , 1 , 1 , 1 }
	hidden = ( hidden == nil ) and false or hidden

	-- Create the cooldown
	local cooldown = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_COOLDOWN ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetFillColor( color[1] , color[2] , color[3] , color[4] )
	.__END
	return cooldown
end

--[[
 * Button
 ]]--
function FTC.UI.Button( name , parent , dims , anchor , state , font , align , normal , pressed , mouseover , hidden )

	-- Validate arguments
	if ( name == nil or name == "" ) then return end
	parent = ( parent == nil ) and GuiRoot or parent
	if ( dims == "inherit" or #dims ~= 2 ) then dims = { parent:GetWidth() , parent:GetHeight() } end
	if ( #anchor ~= 4 and #anchor ~= 5 ) then return end
	state = ( state ~= nil ) and state or BSTATE_NORMAL
	font = ( font == nil ) and "ZoFontGame" or font
	align = ( align ~= nil and #align == 2 ) and align or { 1 , 1 }
	normal = ( normal ~= nil and #normal == 4 ) and normal or { 1 , 1 , 1 , 1 }
	pressed = ( pressed ~= nil and #pressed == 4 ) and pressed or { 1 , 1 , 1 , 1 }
	mouseover = ( mouseover ~= nil and #mouseover == 4 ) and mouseover or { 1 , 1 , 1 , 1 }
	hidden = ( hidden == nil ) and false or hidden

	-- Create the backdrop
	local button = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_BUTTON ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetState( state )
		:SetFont( font )
		:SetNormalFontColor( normal[1] , normal[2] , normal[3] , normal[4] )
		:SetPressedFontColor( pressed[1] , pressed[2] , pressed[3] , pressed[4] )
		:SetMouseOverFontColor( mouseover[1] , mouseover[2] , mouseover[3] , mouseover[4] )
		:SetHorizontalAlignment( align[1] )
		:SetVerticalAlignment( align[2] )
		:SetHidden( hidden )
	.__END
	return button
end

function FTC.UI.Line(name, parent, dims, anchor, hidden)
	local line = FTC.Chain( WINDOW_MANAGER:CreateControl( name , parent , CT_LINE ) )
		:SetDimensions( dims[1] , dims[2] )
		:SetAnchor( anchor[1] , #anchor == 5 and anchor[5] or parent , anchor[2] , anchor[3] , anchor[4] )
		:SetColor(255, 255, 255, 255)
		:SetThickness(10)
		:SetHidden( hidden )
	.__END
	return line
end


text:
package kube

import (
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
	"sort"
	"strings"
	"testing"
	"time"

	"k8s.io/api/core/v1"
	apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/cli-runtime/pkg/resource"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest/fake"
	cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
	kubectlscheme "k8s.io/kubernetes/pkg/kubectl/scheme"
)

func init() {
	err := apiextv1beta1.AddToScheme(scheme.Scheme)
	if err != nil {
		panic(err)
	}

	// Tiller use the scheme from go-client, but the cmdtesting
	// package used here is hardcoded to use the scheme from
	// kubectl. So for testing, we need to add the CustomResourceDefinition
	// type to both schemes.
	err = apiextv1beta1.AddToScheme(kubectlscheme.Scheme)
	if err != nil {
		panic(err)
	}
}

var (
	unstructuredSerializer = resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer
)

func getCodec() runtime.Codec {
	return scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
}

func objBody(obj runtime.Object) io.ReadCloser {
	return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(getCodec(), obj))))
}

func newPod(name string) v1.Pod {
	return newPodWithStatus(name, v1.PodStatus{}, "")
}

func newPodWithStatus(name string, status v1.PodStatus, namespace string) v1.Pod {
	ns := v1.NamespaceDefault
	if namespace != "" {
		ns = namespace
	}
	return v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: ns,
			SelfLink:  "/api/v1/namespaces/default/pods/" + name,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{{
				Name:  "app:v4",
				Image: "abc/app:v4",
				Ports: []v1.ContainerPort{{Name: "http", ContainerPort: 80}},
			}},
		},
		Status: status,
	}
}

func newPodList(names ...string) v1.PodList {
	var list v1.PodList
	for _, name := range names {
		list.Items = append(list.Items, newPod(name))
	}
	return list
}

func newService(name string) v1.Service {
	ns := v1.NamespaceDefault
	return v1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: ns,
			SelfLink:  "/api/v1/namespaces/default/services/" + name,
		},
		Spec: v1.ServiceSpec{},
	}
}

func notFoundBody() *metav1.Status {
	return &metav1.Status{
		Code:    http.StatusNotFound,
		Status:  metav1.StatusFailure,
		Reason:  metav1.StatusReasonNotFound,
		Message: " \"\" not found",
		Details: &metav1.StatusDetails{},
	}
}

func newResponse(code int, obj runtime.Object) (*http.Response, error) {
	header := http.Header{}
	header.Set("Content-Type", runtime.ContentTypeJSON)
	body := ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(getCodec(), obj))))
	return &http.Response{StatusCode: code, Header: header, Body: body}, nil
}

type testClient struct {
	*Client
	*cmdtesting.TestFactory
}

func newTestClient() *testClient {
	tf := cmdtesting.NewTestFactory()
	c := &Client{
		Factory: tf,
		Log:     nopLogger,
	}
	return &testClient{
		Client:      c,
		TestFactory: tf,
	}
}

func TestUpdate(t *testing.T) {
	listA := newPodList("starfish", "otter", "squid")
	listB := newPodList("starfish", "otter", "dolphin")
	listC := newPodList("starfish", "otter", "dolphin")
	listB.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}
	listC.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}

	var actions []string

	tf := cmdtesting.NewTestFactory()
	defer tf.Cleanup()

	tf.UnstructuredClient = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			p, m := req.URL.Path, req.Method
			actions = append(actions, p+":"+m)
			t.Logf("got request %s %s", p, m)
			switch {
			case p == "/namespaces/default/pods/starfish" && m == "GET":
				return newResponse(200, &listA.Items[0])
			case p == "/namespaces/default/pods/otter" && m == "GET":
				return newResponse(200, &listA.Items[1])
			case p == "/namespaces/default/pods/dolphin" && m == "GET":
				return newResponse(404, notFoundBody())
			case p == "/namespaces/default/pods/starfish" && m == "PATCH":
				data, err := ioutil.ReadAll(req.Body)
				if err != nil {
					t.Fatalf("could not dump request: %s", err)
				}
				req.Body.Close()
				expected := `{"spec":{"$setElementOrder/containers":[{"name":"app:v4"}],"containers":[{"$setElementOrder/ports":[{"containerPort":443}],"name":"app:v4","ports":[{"containerPort":443,"name":"https"},{"$patch":"delete","containerPort":80}]}]}}`
				if string(data) != expected {
					t.Errorf("expected patch\n%s\ngot\n%s", expected, string(data))
				}
				return newResponse(200, &listB.Items[0])
			case p == "/namespaces/default/pods" && m == "POST":
				return newResponse(200, &listB.Items[1])
			case p == "/namespaces/default/pods/squid" && m == "DELETE":
				return newResponse(200, &listB.Items[1])
			case p == "/namespaces/default/pods/squid" && m == "GET":
				return newResponse(200, &listA.Items[2])
			default:
				t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
				return nil, nil
			}
		}),
	}

	c := &Client{
		Factory: tf,
		Log:     nopLogger,
	}

	if err := c.Update(v1.NamespaceDefault, objBody(&listA), objBody(&listB), false, false, 0, false); err != nil {
		t.Fatal(err)
	}
	// TODO: Find a way to test methods that use Client Set
	// Test with a wait
	// if err := c.Update("test", objBody(&listB), objBody(&listC), false, 300, true); err != nil {
	// 	t.Fatal(err)
	// }
	// Test with a wait should fail
	// TODO: A way to make this not based off of an extremely short timeout?
	// if err := c.Update("test", objBody(&listC), objBody(&listA), false, 2, true); err != nil {
	// 	t.Fatal(err)
	// }
	expectedActions := []string{
		"/namespaces/default/pods/starfish:GET",
		"/namespaces/default/pods/starfish:PATCH",
		"/namespaces/default/pods/otter:GET",
		"/namespaces/default/pods/otter:GET",
		"/namespaces/default/pods/dolphin:GET",
		"/namespaces/default/pods:POST",
		"/namespaces/default/pods/squid:GET",
		"/namespaces/default/pods/squid:DELETE",
	}
	if len(expectedActions) != len(actions) {
		t.Errorf("unexpected number of requests, expected %d, got %d", len(expectedActions), len(actions))
		return
	}
	for k, v := range expectedActions {
		if actions[k] != v {
			t.Errorf("expected %s request got %s", v, actions[k])
		}
	}

	// Test resource policy is respected
	actions = nil
	listA.Items[2].ObjectMeta.Annotations = map[string]string{ResourcePolicyAnno: "keep"}
	if err := c.Update(v1.NamespaceDefault, objBody(&listA), objBody(&listB), false, false, 0, false); err != nil {
		t.Fatal(err)
	}
	for _, v := range actions {
		if v == "/namespaces/default/pods/squid:DELETE" {
			t.Errorf("should not have deleted squid - it has helm.sh/resource-policy=keep")
		}
	}
}

func TestUpdateNonManagedResourceError(t *testing.T) {
	actual := newPodList("starfish")
	current := newPodList()
	target := newPodList("starfish")

	tf := cmdtesting.NewTestFactory()
	defer tf.Cleanup()

	tf.UnstructuredClient = &fake.RESTClient{
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			p, m := req.URL.Path, req.Method
			t.Logf("got request %s %s", p, m)
			switch {
			case p == "/namespaces/default/pods/starfish" && m == "GET":
				return newResponse(200, &actual.Items[0])
			default:
				t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
				return nil, nil
			}
		}),
	}

	c := &Client{
		Factory: tf,
		Log:     nopLogger,
	}

	if err := c.Update(v1.NamespaceDefault, objBody(&current), objBody(&target), false, false, 0, false); err != nil {
		if err.Error() != "kind Pod with the name \"starfish\" already exists in the cluster and wasn't defined in the previous release. Before upgrading, please either delete the resource from the cluster or remove it from the chart" {
			t.Fatal(err)
		}
	} else {
		t.Fatalf("error expected")
	}
}

func TestBuild(t *testing.T) {
	tests := []struct {
		name      string
		namespace string
		reader    io.Reader
		count     int
		err       bool
	}{
		{
			name:      "Valid input",
			namespace: "test",
			reader:    strings.NewReader(guestbookManifest),
			count:     6,
		}, {
			name:      "Invalid schema",
			namespace: "test",
			reader:    strings.NewReader(testInvalidServiceManifest),
			err:       true,
		},
	}

	c := newTestClient()
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c.Cleanup()

			// Test for an invalid manifest
			infos, err := c.Build(tt.namespace, tt.reader)
			if err != nil && !tt.err {
				t.Errorf("Got error message when no error should have occurred: %v", err)
			} else if err != nil && strings.Contains(err.Error(), "--validate=false") {
				t.Error("error message was not scrubbed")
			}

			if len(infos) != tt.count {
				t.Errorf("expected %d result objects, got %d", tt.count, len(infos))
			}
		})
	}
}

func TestGet(t *testing.T) {
	list := newPodList("starfish", "otter")
	c := newTestClient()
	defer c.Cleanup()
	c.TestFactory.UnstructuredClient = &fake.RESTClient{
		GroupVersion:         schema.GroupVersion{Version: "v1"},
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			p, m := req.URL.Path, req.Method
			t.Logf("got request %s %s", p, m)
			switch {
			case p == "/namespaces/default/pods/starfish" && m == "GET":
				return newResponse(404, notFoundBody())
			case p == "/namespaces/default/pods/otter" && m == "GET":
				return newResponse(200, &list.Items[1])
			default:
				t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
				return nil, nil
			}
		}),
	}

	// Test Success
	data := strings.NewReader("kind: Pod\napiVersion: v1\nmetadata:\n  name: otter")
	o, err := c.Get("default", data)
	if err != nil {
		t.Errorf("Expected missing results, got %q", err)
	}
	if !strings.Contains(o, "==> v1/Pod") && !strings.Contains(o, "otter") {
		t.Errorf("Expected v1/Pod otter, got %s", o)
	}

	// Test failure
	data = strings.NewReader("kind: Pod\napiVersion: v1\nmetadata:\n  name: starfish")
	o, err = c.Get("default", data)
	if err != nil {
		t.Errorf("Expected missing results, got %q", err)
	}
	if !strings.Contains(o, "MISSING") && !strings.Contains(o, "pods\t\tstarfish") {
		t.Errorf("Expected missing starfish, got %s", o)
	}
}

func TestResourceTypeSortOrder(t *testing.T) {
	pod := newPod("my-pod")
	service := newService("my-service")
	c := newTestClient()
	defer c.Cleanup()
	c.TestFactory.UnstructuredClient = &fake.RESTClient{
		GroupVersion:         schema.GroupVersion{Version: "v1"},
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			p, m := req.URL.Path, req.Method
			t.Logf("got request %s %s", p, m)
			switch {
			case p == "/namespaces/default/pods/my-pod" && m == "GET":
				return newResponse(200, &pod)
			case p == "/namespaces/default/services/my-service" && m == "GET":
				return newResponse(200, &service)
			default:
				t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
				return nil, nil
			}
		}),
	}

	// Test sorting order
	data := strings.NewReader(testResourceTypeSortOrder)
	o, err := c.Get("default", data)
	if err != nil {
		t.Errorf("Expected missing results, got %q", err)
	}
	podIndex := strings.Index(o, "my-pod")
	serviceIndex := strings.Index(o, "my-service")
	if podIndex == -1 {
		t.Errorf("Expected v1/Pod my-pod, got %s", o)
	}
	if serviceIndex == -1 {
		t.Errorf("Expected v1/Service my-service, got %s", o)
	}
	if !sort.IntsAreSorted([]int{podIndex, serviceIndex}) {
		t.Errorf("Expected order: [v1/Pod v1/Service], got %s", o)
	}
}

func TestResourceSortOrder(t *testing.T) {
	list := newPodList("albacore", "coral", "beluga")
	c := newTestClient()
	defer c.Cleanup()
	c.TestFactory.UnstructuredClient = &fake.RESTClient{
		GroupVersion:         schema.GroupVersion{Version: "v1"},
		NegotiatedSerializer: unstructuredSerializer,
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			p, m := req.URL.Path, req.Method
			t.Logf("got request %s %s", p, m)
			switch {
			case p == "/namespaces/default/pods/albacore" && m == "GET":
				return newResponse(200, &list.Items[0])
			case p == "/namespaces/default/pods/coral" && m == "GET":
				return newResponse(200, &list.Items[1])
			case p == "/namespaces/default/pods/beluga" && m == "GET":
				return newResponse(200, &list.Items[2])
			default:
				t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
				return nil, nil
			}
		}),
	}

	// Test sorting order
	data := strings.NewReader(testResourceSortOrder)
	o, err := c.Get("default", data)
	if err != nil {
		t.Errorf("Expected missing results, got %q", err)
	}
	albacoreIndex := strings.Index(o, "albacore")
	belugaIndex := strings.Index(o, "beluga")
	coralIndex := strings.Index(o, "coral")
	if albacoreIndex == -1 {
		t.Errorf("Expected v1/Pod albacore, got %s", o)
	}
	if belugaIndex == -1 {
		t.Errorf("Expected v1/Pod beluga, got %s", o)
	}
	if coralIndex == -1 {
		t.Errorf("Expected v1/Pod coral, got %s", o)
	}
	if !sort.IntsAreSorted([]int{albacoreIndex, belugaIndex, coralIndex}) {
		t.Errorf("Expected order: [albacore beluga coral], got %s", o)
	}
}

func TestWaitUntilCRDEstablished(t *testing.T) {
	testCases := map[string]struct {
		conditions            []apiextv1beta1.CustomResourceDefinitionCondition
		returnConditionsAfter int
		success               bool
	}{
		"crd reaches established state after 2 requests": {
			conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
				{
					Type:   apiextv1beta1.Established,
					Status: apiextv1beta1.ConditionTrue,
				},
			},
			returnConditionsAfter: 2,
			success:               true,
		},
		"crd does not reach established state before timeout": {
			conditions:            []apiextv1beta1.CustomResourceDefinitionCondition{},
			returnConditionsAfter: 100,
			success:               false,
		},
		"crd name is not accepted": {
			conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
				{
					Type:   apiextv1beta1.NamesAccepted,
					Status: apiextv1beta1.ConditionFalse,
				},
			},
			returnConditionsAfter: 1,
			success:               false,
		},
	}

	for tn, tc := range testCases {
		func(name string) {
			c := newTestClient()
			defer c.Cleanup()

			crdWithoutConditions := newCrdWithStatus("name", apiextv1beta1.CustomResourceDefinitionStatus{})
			crdWithConditions := newCrdWithStatus("name", apiextv1beta1.CustomResourceDefinitionStatus{
				Conditions: tc.conditions,
			})

			requestCount := 0
			c.TestFactory.UnstructuredClient = &fake.RESTClient{
				GroupVersion:         schema.GroupVersion{Version: "v1"},
				NegotiatedSerializer: unstructuredSerializer,
				Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
					var crd apiextv1beta1.CustomResourceDefinition
					if requestCount < tc.returnConditionsAfter {
						crd = crdWithoutConditions
					} else {
						crd = crdWithConditions
					}
					requestCount += 1
					return newResponse(200, &crd)
				}),
			}

			err := c.WaitUntilCRDEstablished(strings.NewReader(crdManifest), 5*time.Second)
			if err != nil && tc.success {
				t.Errorf("%s: expected no error, but got %v", name, err)
			}
			if err == nil && !tc.success {
				t.Errorf("%s: expected error, but didn't get one", name)
			}
		}(tn)
	}
}

func newCrdWithStatus(name string, status apiextv1beta1.CustomResourceDefinitionStatus) apiextv1beta1.CustomResourceDefinition {
	crd := apiextv1beta1.CustomResourceDefinition{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: metav1.NamespaceDefault,
		},
		Spec:   apiextv1beta1.CustomResourceDefinitionSpec{},
		Status: status,
	}
	return crd
}

func TestPerform(t *testing.T) {
	tests := []struct {
		name       string
		namespace  string
		reader     io.Reader
		count      int
		err        bool
		errMessage string
	}{
		{
			name:      "Valid input",
			namespace: "test",
			reader:    strings.NewReader(guestbookManifest),
			count:     6,
		}, {
			name:       "Empty manifests",
			namespace:  "test",
			reader:     strings.NewReader(""),
			err:        true,
			errMessage: "no objects visited",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			results := []*resource.Info{}

			fn := func(info *resource.Info) error {
				results = append(results, info)

				if info.Namespace != tt.namespace {
					t.Errorf("expected namespace to be '%s', got %s", tt.namespace, info.Namespace)
				}
				return nil
			}

			c := newTestClient()
			defer c.Cleanup()
			infos, err := c.Build(tt.namespace, tt.reader)
			if err != nil && err.Error() != tt.errMessage {
				t.Errorf("Error while building manifests: %v", err)
			}

			err = perform(infos, fn)
			if (err != nil) != tt.err {
				t.Errorf("expected error: %v, got %v", tt.err, err)
			}
			if err != nil && err.Error() != tt.errMessage {
				t.Errorf("expected error message: %v, got %v", tt.errMessage, err)
			}

			if len(results) != tt.count {
				t.Errorf("expected %d result objects, got %d", tt.count, len(results))
			}
		})
	}
}

func TestReal(t *testing.T) {
	t.Skip("This is a live test, comment this line to run")
	c := New(nil)
	if err := c.Create("test", strings.NewReader(guestbookManifest), 300, false); err != nil {
		t.Fatal(err)
	}

	testSvcEndpointManifest := testServiceManifest + "\n---\n" + testEndpointManifest
	c = New(nil)
	if err := c.Create("test-delete", strings.NewReader(testSvcEndpointManifest), 300, false); err != nil {
		t.Fatal(err)
	}

	if err := c.Delete("test-delete", strings.NewReader(testEndpointManifest)); err != nil {
		t.Fatal(err)
	}

	// ensures that delete does not fail if a resource is not found
	if err := c.Delete("test-delete", strings.NewReader(testSvcEndpointManifest)); err != nil {
		t.Fatal(err)
	}
}

const testResourceTypeSortOrder = `
kind: Service
apiVersion: v1
metadata:
  name: my-service
---
kind: Pod
apiVersion: v1
metadata:
  name: my-pod
`

const testResourceSortOrder = `
kind: Pod
apiVersion: v1
metadata:
  name: albacore
---
kind: Pod
apiVersion: v1
metadata:
  name: coral
---
kind: Pod
apiVersion: v1
metadata:
  name: beluga
`

const testServiceManifest = `
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: myapp
  ports:
    - port: 80
      protocol: TCP
      targetPort: 9376
`

const testInvalidServiceManifest = `
kind: Service
apiVersion: v1
spec:
  ports:
    - port: "80"
`

const testEndpointManifest = `
kind: Endpoints
apiVersion: v1
metadata:
  name: my-service
subsets:
  - addresses:
      - ip: "1.2.3.4"
    ports:
      - port: 9376
`

const guestbookManifest = `
apiVersion: v1
kind: Service
metadata:
  name: redis-master
  labels:
    app: redis
    tier: backend
    role: master
spec:
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app: redis
    tier: backend
    role: master
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-master
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: redis
        role: master
        tier: backend
    spec:
      containers:
      - name: master
        image: k8s.gcr.io/redis:e2e  # or just image: redis
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        ports:
        - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: redis-slave
  labels:
    app: redis
    tier: backend
    role: slave
spec:
  ports:
    # the port that this service should serve on
  - port: 6379
  selector:
    app: redis
    tier: backend
    role: slave
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-slave
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: redis
        role: slave
        tier: backend
    spec:
      containers:
      - name: slave
        image: gcr.io/google_samples/gb-redisslave:v1
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: GET_HOSTS_FROM
          value: dns
        ports:
        - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
  labels:
    app: guestbook
    tier: frontend
spec:
  ports:
  - port: 80
  selector:
    app: guestbook
    tier: frontend
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: guestbook
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google-samples/gb-frontend:v4
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: GET_HOSTS_FROM
          value: dns
        ports:
        - containerPort: 80
`

const crdManifest = `
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  creationTimestamp: null
  labels:
    controller-tools.k8s.io: "1.0"
  name: applications.app.k8s.io
spec:
  group: app.k8s.io
  names:
    kind: Application
    plural: applications
  scope: Namespaced
  validation:
    openAPIV3Schema:
      properties:
        apiVersion:
          description: 'Description'
          type: string
        kind:
          description: 'Kind'
          type: string
        metadata:
          type: object
        spec:
          type: object
        status:
          type: object
  version: v1beta1
status:
  acceptedNames:
    kind: ""
    plural: ""
  conditions: []
  storedVersions: []
`

redpajama_set_name: RedPajamaGithub


text:
const path = require('path');
const _ = require('lodash');

// eslint-disable-next-line unicorn/import-index
const customFonts = require('../');

const options = {
  text: 'Make something people want',
  fontNameOrPath: path.join(
    __dirname,
    '..',
    'test',
    'fixtures',
    'GoudyBookletter1911'
  ),
  fontColor: 'white',
  backgroundColor: '#ff6600',
  fontSize: 40
};

const data = _.map(['svg', 'img', 'png', 'png2x', 'png3x'], method => {
  return customFonts[method](options);
});
_.each(data, str => {
  console.log(`<br />\n${str}\n<br />`);
});


text:
#include <aws/workmail/model/CreateAliasRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::WorkMail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateAliasRequest::CreateAliasRequest() :
    m_organizationIdHasBeenSet(false),
    m_entityIdHasBeenSet(false),
    m_aliasHasBeenSet(false)
{
}

Aws::String CreateAliasRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_organizationIdHasBeenSet)
  {
   payload.WithString("OrganizationId", m_organizationId);

  }

  if(m_entityIdHasBeenSet)
  {
   payload.WithString("EntityId", m_entityId);

  }

  if(m_aliasHasBeenSet)
  {
   payload.WithString("Alias", m_alias);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection CreateAliasRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "WorkMailService.CreateAlias"));
  return headers;

}


text:
/*!
 *
 * {%= projectTitle %} config.
 *
 * Grunt Nautilus:
 * https://github.com/kitajchuk/grunt-nautilus
 *
 * Available grunt-nautilus tasks:
 * grunt nautilus:build [, flags...]
 * grunt nautilus:deploy [, flags...]
 * grunt nautilus:module [, flags...]
 *
 */
module.exports = function ( grunt ) {

    "use strict";

    // Default project paths.
    var pubRoot = "{%= pubRoot %}",
        sassRoot = "{%= sassRoot %}",
        cssRoot = "{%= cssRoot %}",
        jsRoot = "{%= jsRoot %}",
        appRoot = jsRoot + "/app",
        libRoot = jsRoot + "/lib",
        distRoot = jsRoot + "/dist";

    // Project configuration.
    grunt.initConfig({
        // Project meta.
        meta: {
            version: "0.1.0"
        },

        // Nautilus config.
        nautilus: {
            options: {
                jsAppRoot: appRoot,
                jsDistRoot: distRoot,
                jsLibRoot: libRoot,
                jsRoot: jsRoot,
                pubRoot: pubRoot,
                cssRoot: cssRoot,
                sassRoot: sassRoot
                jsGlobals: {},
                hintOn: [
                    "watch",
                    "build",
                    "deploy"
                ]
            }
        }

    });

    // Load the nautilus plugin.
    grunt.loadNpmTasks( "grunt-contrib-jshint" );
    grunt.loadNpmTasks( "grunt-contrib-concat" );
    grunt.loadNpmTasks( "grunt-contrib-uglify" );
    grunt.loadNpmTasks( "grunt-contrib-watch" );
    grunt.loadNpmTasks( "grunt-contrib-sass" );
    grunt.loadNpmTasks( "grunt-contrib-clean" );
    grunt.loadNpmTasks( "grunt-jsdoc" );
    grunt.loadNpmTasks( "grunt-postcss" );
    grunt.loadNpmTasks( "grunt-nautilus" );

    // Register default task.
    grunt.registerTask( "default", ["nautilus:build"] );

};


text:
angular.module('puszekApp')
    .controller('notificationsSenderController', function notificationsSenderController($scope, $http, Config, AuthUser) {

        $scope.notification = {
            sender: AuthUser.getFullName(),
            receivers: '*',
            message: {
                type: 'notification',
                message: ''
            }
        };

        $scope.sendNotification = function() {
            $http.post(Config.baseUrl + '/messages/send', $scope.notification).then(function() {
                $scope.notification.message.message = '';
            });
        };
    });


text:
package handler

import (
	"io/ioutil"
	"testing"
)

func TestBasicHandlerLevel(t *testing.T) {
	testHandlerLevel(t, NewBasicHandler(ioutil.Discard))
}

func TestBasicHandlerOutput(t *testing.T) {
	testHandlerOutput(t, NewBasicHandler(ioutil.Discard))
}

func BenchmarkBasicHandler(b *testing.B) {
	benchmarkHandler(b, NewBasicHandler(ioutil.Discard))
}

func TestFlushHandlerLevel(t *testing.T) {
	testHandlerLevel(t, NewFlushHandler(ioutil.Discard))
}

func TestFlushHandlerOutput(t *testing.T) {
	testHandlerOutput(t, NewFlushHandler(ioutil.Discard))
}

func BenchmarkFlushHandler(b *testing.B) {
	benchmarkHandler(b, NewFlushHandler(ioutil.Discard))
}


text:
// Calculate rectangle's perimeter and area by given width and height
using System;

class Rectangles
{
    static void Main()
    {
        Console.Write("Please enter height: ");
        double height = double.Parse(Console.ReadLine());
        Console.Write("Please enter width: ");
        double width = double.Parse(Console.ReadLine());

        Console.WriteLine("Perimeter is " + (height * 2 + width * 2));
        Console.WriteLine("Area is " + height * width);
    }
}


text:
"""Provides generic classes for interacting with persistent storage."""

# pylint: disable=broad-except

import abc
import json
import threading
from typing import Any, AnyStr, Callable, List, Optional, Text, Tuple, Union

from absl import logging
import retrying

from hypebot.core import params_lib
from hypebot.core import schedule_lib
from hypebot.hype_types import JsonType

class HypeTransaction(abc.ABC):
  """A base class for transactions used by implementations of HypeStore.

  HypeTransactions are NOT thread-safe.
  """

  def __init__(self, tx_name: AnyStr):
    self._name = tx_name

  def __str__(self) -> AnyStr:
    return '[TX %s]' % self.name

  @property
  def name(self) -> AnyStr:
    return self._name

  @abc.abstractmethod
  def Commit(self) -> bool:
    """Commits this transaction to the backing store.

    Raises:
      Subclass-specific errors if committing the transaction failed in a way
      that can't be retried. Implementation should take care to catch Exceptions
      they can handle and retry them internally, as anything raised here will
      lead to a permanent transaction abort, and bubble up to the caller.

    Returns:
      If the transaction was successfully committed or not. False indicates that
      something went wrong and the transaction should be retried.
    """

class HypeStore(abc.ABC):
  """Abstract base class for HypeBot storage."""

  DEFAULT_PARAMS = params_lib.HypeParams()

  def __init__(self, params):
    self._params = params_lib.HypeParams(self.DEFAULT_PARAMS)
    self._params.Override(params)
    self._params.Lock()

  @abc.abstractproperty
  def engine(self):
    """The name of the backing engine. Should be all lowercase."""

  @abc.abstractmethod
  def GetValue(self,
               key: AnyStr,
               subkey: AnyStr,
               tx: Optional[HypeTransaction] = None) -> Optional[AnyStr]:
    """Fetch the value for key and subkey.

    Args:
      key: The primary key used to find the entry.
      subkey: The subkey used to find the entry.
      tx: Optional transaction to run the underlying storage call within.

    Raises:
      If an error occurs during fetching the value from the store. This will
      abort any transaction GetValue is called with.

    Returns:
      The value found, or None if no value is found.
    """

  @abc.abstractmethod
  def SetValue(self,
               key: AnyStr,
               subkey: AnyStr,
               value: Union[int, AnyStr],
               tx: Optional[HypeTransaction] = None) -> None:
    """Replaces the current value (if any) for key and subkey with value.

    Args:
      key: The primary key used to find the entry.
      subkey: The subkey used to find the entry.
      value: The new value to overwrite any existing value with.
      tx: Optional transaction to run the underlying storage call within.

    Raises:
      If an error occurs during setting the value from the store. This will
      abort any transaction SetValue is called with.

    Returns:
      None.
    """

  @abc.abstractmethod
  def DeleteKey(self,
                key: AnyStr,
                tx: Optional[HypeTransaction] = None) -> None:
    """Removes key from the store."""

  @abc.abstractmethod
  def GetSubkey(self, subkey: AnyStr, tx: Optional[HypeTransaction] = None
               ) -> List[Tuple[AnyStr, AnyStr]]:
    """Returns (key, value) tuples for all keys with a value for subkey."""

  @abc.abstractmethod
  def GetHistoricalValues(
      self,
      key: AnyStr,
      subkey: AnyStr,
      num_past_values: int,
      tx: Optional[HypeTransaction] = None) -> List[JsonType]:
    """Like GetJsonValue, but allows for getting past values for key/subkey.

    Args:
      key: The primary key used to find the entry.
      subkey: The subkey used to find the entry.
      num_past_values: The maximum number of historical values to return. If
        fewer values are found (including 0 values), only that many values will
        be returned.
      tx: Optional transaction to run the underlying storage call within.

    Raises:
      If an error occurs during fetching the values from the store. This will
      abort any transaction GetHistoricalValues is called with.

    Returns:
      A list of the values found in reverse chronological order (newest values
      first). When no values are found, returns an empty list.
    """

  @abc.abstractmethod
  def PrependValue(self,
                   key: AnyStr,
                   subkey: AnyStr,
                   new_value: JsonType,
                   max_length: Optional[int] = None,
                   tx: Optional[HypeTransaction] = None) -> None:
    """Like SetJsonValue, but keeps past values upto an optional max_length.

    Args:
      key: The primary key used to find the entry.
      subkey: The subkey used to find the entry.
      new_value: The new value to add to the entry.
      max_length: The maximum number of past values to keep. Note that not all
        storage engines will respect this value, so it may be set to None.
      tx: Optional transaction to run the underlying storage call within.

    Raises:
      If an error occurs during setting the value from the store. This will
      abort any transaction PrependValue is called with.

    Returns:
      None.
    """

  @abc.abstractmethod
  def NewTransaction(self, tx_name: AnyStr) -> HypeTransaction:
    """Returns a new concrete transaction.

    Args:
      tx_name: Short description for this transaction, used in logging to
        clarify what operations are attempted within this transaction.

    Returns:
      An implementation-specific subclass of HypeTransaction.
    """

  def UpdateValue(self,
                  key: AnyStr,
                  subkey: AnyStr,
                  delta: int,
                  tx: Optional[HypeTransaction] = None) -> None:
    """Reads the current value for key/subkey and adds delta, atomically."""
    if not tx:
      tx_name = '%s/%s += %s' % (key, subkey, delta)
      self.RunInTransaction(
          self.UpdateValue, key, subkey, delta, tx_name=tx_name)
      return
    cur_value = self.GetValue(key, subkey, tx) or '0'
    cur_type = type(cur_value)
    try:
      cur_value = int(cur_value)
    except Exception as e:
      logging.error(
          'Can\'t call UpdateValue on (%s, %s), value %s isn\'t an int [%s]',
          key, subkey, cur_value, cur_type)
      raise e
    new_value = cur_type(cur_value + delta)
    self.SetValue(key, subkey, new_value, tx)

  def GetJsonValue(self,
                   key: AnyStr,
                   subkey: AnyStr,
                   tx: Optional[HypeTransaction] = None
                  ) -> (Optional[JsonType]):
    """Gets and deserializes the JSON object for key and subkey."""
    value = None
    try:
      serialized_value = self.GetValue(key, subkey, tx)
      if serialized_value:
        value = json.loads(serialized_value)
      return value
    except Exception as e:
      logging.error('Error fetching JSON value for %s/%s:', key, subkey)
      raise e

  def SetJsonValue(self,
                   key: AnyStr,
                   subkey: AnyStr,
                   json_value: JsonType,
                   tx: Optional[HypeTransaction] = None) -> None:
    """Serializes and stores json_value as a string."""
    try:
      value = json.dumps(json_value)
      self.SetValue(key, subkey, value, tx)
    except Exception as e:
      logging.error('Error storing JSON value for %s/%s.', key, subkey)
      # Re-raise so that transactions will be aborted.
      raise e

  def UpdateJson(self,
                 key: AnyStr,
                 subkey: AnyStr,
                 transform_fn: Callable[[JsonType], Any],
                 success_fn: Callable[[JsonType], bool] = lambda _: True,
                 is_set: bool = False,
                 tx: Optional[HypeTransaction] = None) -> bool:
    """Fetches a JSON object and stores it after applying transform_fn.

    Args:
      key: The storage key to operate on.
      subkey: The storage subkey to operate on.
      transform_fn: A function that accepts a deserialized JSON object (e.g.
        python dict or list) and modifies it in place. Return value is ignored.
      success_fn: A function that accepts a deserialized JSON object and returns
        a boolean, which is used as the final return value of UpdateJson. Note
        this function is applied to the deserialized object BEFORE transform_fn.
      is_set: If the JSON object should be treated as a set. This is required
        because JSON does not natively support sets, but a set can be easily
        represented by a list of members.
      tx: Optional transaction to include this update in. If no transaction is
        passed, a new transaction will be created to ensure the Update is
        atomic.

    Returns:
      The result of success_fn applied to the JSON object as it was when fetched
      from table.
    """
    if not tx:
      tx_name = 'UpdateJson on %s/%s' % (key, subkey)
      return self.RunInTransaction(
          self.UpdateJson,
          key,
          subkey,
          transform_fn,
          success_fn,
          is_set,
          tx_name=tx_name)

    raw_structure = self.GetJsonValue(key, subkey, tx) or {}
    if is_set:
      raw_structure = set(raw_structure)
    success = success_fn(raw_structure)
    transform_fn(raw_structure)
    if is_set:
      raw_structure = list(raw_structure)
    self.SetJsonValue(key, subkey, raw_structure, tx)
    return success

  def RunInTransaction(self, fn: Callable, *args, **kwargs) -> Any:
    """Retriably attemps to execute fn within a single transaction.

    The normal use of this function is as follows:

    store.RunInTransaction(self._DoWorkThatNeedsToBeAtomic, arg_1, arg_2)
    ...
    def _DoWorkThatNeedsToBeAtomic(self, arg_1, arg_2, tx=None):
      a = store.GetValue(arg_1, arg_2, tx)
      a += '-foo'
      store.SetValue(arg_1, arg_2, a, tx)

    With the above, _DoWorkThatNeedsToBeAtomic will be done inside a transaction
    and retried if committing the transaction fails for a storage-engine defined
    reason which means that retrying to commit the transaction might be
    successful.

    Args:
      fn: The function which is executed within a transaction. It must be safe
        to run multiple times in the case of a transaction abort (e.g.
        contention on one of the key/subkey pairs), and must accept the kwarg
        "tx", which is a HypeTransaction.
      *args: Positional arguments to pass to fn.
      **kwargs: Keyword arguments to pass to fn. Will always include "tx".

    Raises:
      If fn or tx.Commit raises any exception, this function will not retry and
      will re-raise that exception.

    Returns:
      If fn does not raise an Exception and the transaction (eventually) commits
      successfully, returns the return value of fn.
    """
    fn_return_val = None

    @retrying.retry(
        retry_on_result=lambda commit_retval: not commit_retval,
        retry_on_exception=lambda exc: False,
        stop_max_attempt_number=6,
        wait_exponential_multiplier=200)
    def _Internal(tx):
      nonlocal fn_return_val
      kwargs['tx'] = tx
      fn_return_val = fn(*args, **kwargs)
      return tx.Commit()  # Must return True/False to indicate success or retry

    tx_name = kwargs.pop('tx_name', '%s: %s %s' % (fn.__name__, args, kwargs))
    tx = self.NewTransaction(tx_name)
    # If your storage engine needs retries done a different way than simply
    # calling _Internal again when the transaction fails to commit, you'll need
    # to override this function and add your own retrying logic here.
    try:
      _Internal(tx)
    except Exception:
      logging.error('%s threw, aborting %s:', fn.__name__, tx)
      raise
    return fn_return_val

class CommitAbortError(RuntimeError):
  """Exception indicating a transaction commit aborted, permanently failing."""

class SyncedDict(dict):
  """A "synced" version of a dict which is persisted to a store.

  When a SyncedDict is constructed, it loads contents from the store, allowing
  users to treat it like a normal dict, but have items persisted across process
  restarts. SyncedDict does not stay synchronized across concurrently running
  objects or processes. If you need to see the changes made from another copy
  with the same storage_key, you must first call Sync().
  """

  _POP_SENTINEL = object()
  _DEFAULT_SUBKEY = 'synced_object'

  def __init__(self, store, storage_key, storage_subkey=None):
    super(SyncedDict, self).__init__()
    self._store = store
    self._storage_key = storage_key
    self._subkey = storage_subkey or self._DEFAULT_SUBKEY
    self.Sync()

  def __delitem__(self, key):
    super(SyncedDict, self).__delitem__(key)
    self._FlushToStorage()

  def __setitem__(self, key, value):
    super(SyncedDict, self).__setitem__(key, value)
    self._FlushToStorage()

  def pop(self, key, default=_POP_SENTINEL):
    # We use a sentinel here because pop() has different behavior when you pass
    # a default, even if that default is None.
    if default is self._POP_SENTINEL:
      super(SyncedDict, self).pop(key)
    else:
      super(SyncedDict, self).pop(key, default)
    self._FlushToStorage()

  def update(self, *args, **kwargs):
    super(SyncedDict, self).update(*args, **kwargs)
    self._FlushToStorage()

  def _FlushToStorage(self):
    self._store.SetJsonValue(self._storage_key, self._subkey,
                             super(SyncedDict, self).__self__)  # pytype: disable=attribute-error

  def Sync(self):
    """(Re)loads all data from the backing storage."""
    store = self._store.GetJsonValue(self._storage_key, self._subkey)
    self.clear()
    # Do not use SyncedDict.update since it will FlushToStorage unnecessarily.
    super(SyncedDict, self).update(store or {})

class HypeQueue:
  """A durable message queue built on top of an existing HypeStore.

  Any JSONType can be added to the queue via Enqueue(), and will be processes
  in a best-effort FIFO order at a later time. Messages are processed with a
  user-provided function that should be idempotent as it may be called more than
  once.

  Note that while HypeQueue is designed to be thread-safe, it is not meant to be
  used across processes. Put another way, for a given queue_name, only one
  HypeQueue object should be created globally.
  """
  _SUBKEY = 'hype_queue'

  def __init__(self, store: HypeStore, name: Text,
               scheduler: schedule_lib.HypeScheduler,
               process_fn: Callable[..., bool]):
    self._store = store
    self._scheduler = scheduler
    self._queue_name = '%s-queue' % name
    self._process_fn = process_fn

    # Ensures only one thread is trying to process the queue at a time.
    # Reentrant to support recursive calls to ProcessQueue via RunInTransaction.
    self._process_lock = threading.RLock()
    self._scheduler.FixedRate(30, 60, self.ProcessQueue)

  def Enqueue(self, payload: JsonType, tx: HypeTransaction = None) -> None:
    """Adds payload to the queue for processing.

    Args:
      payload: Any JSON-serializable type which will be passed to process_fn at
        a later time.
      tx: HypeTransaction which can be used to ensure a message is enqueued
        atomically with another operation on a HypeStore. Note only transactions
        created from the queue's underlying HypeStore are valid here.

    Returns:
      None.
    """
    if not tx:
      return self._store.RunInTransaction(self.Enqueue, payload)
    queue = self._store.GetJsonValue(self._queue_name, self._SUBKEY, tx) or []
    queue.append(payload)
    self._store.SetJsonValue(self._queue_name, self._SUBKEY, queue, tx)

  def ProcessQueue(self,
                   batch_size: int = 10,
                   tx: HypeTransaction = None) -> bool:
    """Processes items in the queue using the queue's process_fn.

    Args:
      batch_size: How many items to pull from the queue for processing. If
        process_fn throws for any of these items, all items will be retried
        again later.
      tx: Transaction to run the processing within. Shouldn't be set unless
        processing needs to be atomic with another write to the HypeStore.

    Returns:
      If ProcessQueue successfully ran. If another execution of ProcessQueue is
      running, ProcessQueue will do no work, and return False. Note that
      skipping execution due to there being no entries in the queue is
      considered a success and will return True.
    """
    if not self._process_lock.acquire(blocking=False):
      # Already running, just return.
      return False
    try:
      if not tx:
        return self._store.RunInTransaction(self.ProcessQueue, batch_size)

      queue = self._store.GetJsonValue(self._queue_name, self._SUBKEY, tx) or []
      for _ in range(min(len(queue), batch_size)):
        payload = queue.pop(0)
        # TODO: Run _process_fn on a separate thread to allow retries
        #   without blocking queue processing. We would need to ensure we still
        #   attempted to keep FIFO ordering.
        ack = self._process_fn(payload)
        if ack:
          self._store.SetJsonValue(self._queue_name, self._SUBKEY, queue, tx)
        else:
          queue.append(payload)
      return True
    finally:
      self._process_lock.release()


text:
<?php

require('connectToServer.php');
connect();

session_start();

$table='users';
$email = $_POST['email'];
$result = mysql_query("SELECT * FROM $table WHERE email='$email'");
//gets account info for email

if(mysql_num_rows($result))
{//if email is in system send them an email with a reset link
		$name = mysql_result($result, 0,"name");
		$password = mysql_result($result,0,"password");

		$subject = 'Password Reset';
		$message = "Hello $name,

	We have received a reset password request for your account. If this is an error please disregard this email. If not, you may reset your password using the following link: http://sgiordano.info/assassins/processReset.php?old=$password&email=$email

FTK!
The Assassins Staff";

		$headers = 'From: assassins@floridadm.com' . "\r\n" .
		    'X-Mailer: PHP/' . phpversion();

		mail($email, $subject, $message, $headers);

}
else
{// if email is not in system redirect and give an error

 $_SESSION['DM2-status']="
Error: No account registered to this email.
";

}
//redirect when done
 echo('');

?>


text:
package inst

import (
	"fmt"

	"github.com/github/orchestrator/go/config"
	"github.com/github/orchestrator/go/db"
	"github.com/github/orchestrator/go/process"
	"github.com/outbrain/golib/log"
	"github.com/outbrain/golib/sqlutils"
)

// ReadActiveMaintenance returns the list of currently active maintenance entries
func ReadActiveMaintenance() ([]Maintenance, error) {
	res := []Maintenance{}
	query := `
		select
			database_instance_maintenance_id,
			hostname,
			port,
			begin_timestamp,
			timestampdiff(second, begin_timestamp, now()) as seconds_elapsed,
			maintenance_active,
			owner,
			reason
		from
			database_instance_maintenance
		where
			maintenance_active = 1
		order by
			database_instance_maintenance_id
		`
	err := db.QueryOrchestratorRowsMap(query, func(m sqlutils.RowMap) error {
		maintenance := Maintenance{}
		maintenance.MaintenanceId = m.GetUint("database_instance_maintenance_id")
		maintenance.Key.Hostname = m.GetString("hostname")
		maintenance.Key.Port = m.GetInt("port")
		maintenance.BeginTimestamp = m.GetString("begin_timestamp")
		maintenance.SecondsElapsed = m.GetUint("seconds_elapsed")
		maintenance.IsActive = m.GetBool("maintenance_active")
		maintenance.Owner = m.GetString("owner")
		maintenance.Reason = m.GetString("reason")

		res = append(res, maintenance)
		return nil
	})

	if err != nil {
		log.Errore(err)
	}
	return res, err

}

// BeginBoundedMaintenance will make new maintenance entry for given instanceKey.
func BeginBoundedMaintenance(instanceKey *InstanceKey, owner string, reason string, durationSeconds uint, explicitlyBounded bool) (int64, error) {
	var maintenanceToken int64 = 0
	if durationSeconds == 0 {
		durationSeconds = config.Config.MaintenanceExpireMinutes * 60
	}
	res, err := db.ExecOrchestrator(`
			insert ignore
				into database_instance_maintenance (
					hostname, port, maintenance_active, begin_timestamp, end_timestamp, owner, reason,
					processing_node_hostname, processing_node_token, explicitly_bounded
				) VALUES (
					?, ?, 1, NOW(), NOW() + INTERVAL ? SECOND, ?, ?,
					?, ?, ?
				)
			`,
		instanceKey.Hostname,
		instanceKey.Port,
		durationSeconds,
		owner,
		reason,
		process.ThisHostname,
		process.ProcessToken.Hash,
		explicitlyBounded,
	)
	if err != nil {
		return maintenanceToken, log.Errore(err)
	}

	if affected, _ := res.RowsAffected(); affected == 0 {
		err = fmt.Errorf("Cannot begin maintenance for instance: %+v; maintenance reason: %+v", instanceKey, reason)
	} else {
		// success
		maintenanceToken, _ = res.LastInsertId()
		AuditOperation("begin-maintenance", instanceKey, fmt.Sprintf("maintenanceToken: %d, owner: %s, reason: %s", maintenanceToken, owner, reason))
	}
	return maintenanceToken, err
}

// BeginMaintenance will make new maintenance entry for given instanceKey. Maintenance time is unbounded
func BeginMaintenance(instanceKey *InstanceKey, owner string, reason string) (int64, error) {
	return BeginBoundedMaintenance(instanceKey, owner, reason, 0, false)
}

// EndMaintenanceByInstanceKey will terminate an active maintenance using given instanceKey as hint
func EndMaintenanceByInstanceKey(instanceKey *InstanceKey) error {
	res, err := db.ExecOrchestrator(`
			update
				database_instance_maintenance
			set
				maintenance_active = NULL,
				end_timestamp = NOW()
			where
				hostname = ?
				and port = ?
				and maintenance_active = 1
			`,
		instanceKey.Hostname,
		instanceKey.Port,
	)
	if err != nil {
		return log.Errore(err)
	}

	if affected, _ := res.RowsAffected(); affected == 0 {
		err = fmt.Errorf("Instance is not in maintenance mode: %+v", instanceKey)
	} else {
		// success
		AuditOperation("end-maintenance", instanceKey, "")
	}
	return err
}

// ReadMaintenanceInstanceKey will return the instanceKey for active maintenance by maintenanceToken
func ReadMaintenanceInstanceKey(maintenanceToken int64) (*InstanceKey, error) {
	var res *InstanceKey
	query := `
		select
			hostname, port
		from
			database_instance_maintenance
		where
			database_instance_maintenance_id = ?
			`

	err := db.QueryOrchestrator(query, sqlutils.Args(maintenanceToken), func(m sqlutils.RowMap) error {
		instanceKey, merr := NewInstanceKeyFromStrings(m.GetString("hostname"), m.GetString("port"))
		if merr != nil {
			return merr
		}

		res = instanceKey
		return nil
	})

	if err != nil {
		log.Errore(err)
	}
	return res, err
}

// EndMaintenance will terminate an active maintenance via maintenanceToken
func EndMaintenance(maintenanceToken int64) error {
	res, err := db.ExecOrchestrator(`
			update
				database_instance_maintenance
			set
				maintenance_active = NULL,
				end_timestamp = NOW()
			where
				database_instance_maintenance_id = ?
			`,
		maintenanceToken,
	)
	if err != nil {
		return log.Errore(err)
	}
	if affected, _ := res.RowsAffected(); affected == 0 {
		err = fmt.Errorf("Instance is not in maintenance mode; token = %+v", maintenanceToken)
	} else {
		// success
		instanceKey, _ := ReadMaintenanceInstanceKey(maintenanceToken)
		AuditOperation("end-maintenance", instanceKey, fmt.Sprintf("maintenanceToken: %d", maintenanceToken))
	}
	return err
}

// ExpireMaintenance will remove the maintenance flag on old maintenances and on bounded maintenances
func ExpireMaintenance() error {
	{
		res, err := db.ExecOrchestrator(`
			delete from
				database_instance_maintenance
			where
				maintenance_active is null
				and end_timestamp < NOW() - INTERVAL ? DAY
			`,
			config.Config.MaintenancePurgeDays,
		)
		if err != nil {
			return log.Errore(err)
		}
		if rowsAffected, _ := res.RowsAffected(); rowsAffected > 0 {
			AuditOperation("expire-maintenance", nil, fmt.Sprintf("Purged historical entries: %d", rowsAffected))
		}
	}
	{
		res, err := db.ExecOrchestrator(`
			update
				database_instance_maintenance
			set
				maintenance_active = NULL
			where
				maintenance_active = 1
				and end_timestamp < NOW()
			`,
		)
		if err != nil {
			return log.Errore(err)
		}
		if rowsAffected, _ := res.RowsAffected(); rowsAffected > 0 {
			AuditOperation("expire-maintenance", nil, fmt.Sprintf("Expired bounded: %d", rowsAffected))
		}
	}
	{
		res, err := db.ExecOrchestrator(`
			update
				database_instance_maintenance
				left join node_health on (processing_node_hostname = node_health.hostname AND processing_node_token = node_health.token)
			set
				database_instance_maintenance.maintenance_active = NULL
			where
				node_health.last_seen_active IS NULL
				and explicitly_bounded = 0
			`,
		)
		if err != nil {
			return log.Errore(err)
		}
		if rowsAffected, _ := res.RowsAffected(); rowsAffected > 0 {
			AuditOperation("expire-maintenance", nil, fmt.Sprintf("Expired dead: %d", rowsAffected))
		}
	}

	return nil
}


text:
layout: post
title: "Links"
date: 2015-01-21 10:35:00
categories:
- blog
---

[Girls Who Code](https://girlswhocode.fluidreview.com/)

[Code Day NYC](https://codeday.org/ny)


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class P01SecondNature {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Deque<Integer> flowers = new ArrayDeque<>(); //queue
        Deque<Integer> buckets = new ArrayDeque<>(); //stack;
        Deque<Integer> secondNature = new ArrayDeque<>(); //queue

        String[] tokens = br.readLine().split("\\s+");
        for (int i = 0; i < tokens.length; i++) {
            flowers.add(Integer.parseInt(tokens[i]));
        }

        tokens = br.readLine().split("\\s+");
        for (int i = 0; i < tokens.length; i++) {
            buckets.push(Integer.parseInt(tokens[i]));
        }

        while (!flowers.isEmpty() && !buckets.isEmpty()) {
            int currentBucket = buckets.pop();
            int currentFlower = flowers.poll();
            int diff = currentBucket - currentFlower;

            if (diff == 0) {
                secondNature.add(currentBucket);
            } else if (diff > 0) {
                if (!buckets.isEmpty()) {
                    int nextBucket = buckets.pop();
                    nextBucket += diff;
                    buckets.push(nextBucket);
                } else {
                    buckets.push(diff);
                }
            } else {
                currentFlower = Math.abs(diff);
                flowers.addFirst(currentFlower);   //// zapiswam w opashkata naj-otpred, a ne dobawqm naj-otzad
            }
        }

        if (!buckets.isEmpty()) {
            System.out.println(Arrays.toString(buckets.toArray()).replaceAll("[\\[\\],]", ""));
        }

        if (!flowers.isEmpty()) {
            System.out.println(Arrays.toString(flowers.toArray()).replaceAll("[\\[\\],]", ""));
        }

        System.out.println(!secondNature.isEmpty()
                ? Arrays.toString(secondNature.toArray()).replaceAll("[\\[\\],]", "")
                : "None");

    }
}


text:
package automation.base;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterSuite;

import automation.applogic.ApplicationManager;
import automation.model.User;

public class TestBaseModel {

	public static User ADMIN = new User().setLogin("admin").setPassword("admin");
	protected ApplicationManager app;

	@BeforeClass
	public void init() {
		app = new ApplicationManager();
	}

	@AfterSuite
	public void stop() {
		app.stop();
	}

}


text:
package operation

import (
	"context"
	"errors"
	"fmt"

	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/mongo/description"
	"go.mongodb.org/mongo-driver/mongo/writeconcern"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
	"go.mongodb.org/mongo-driver/x/mongo/driver"
	"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)

// DropCollection performs a drop operation.
type DropCollection struct {
	session      *session.Client
	clock        *session.ClusterClock
	collection   string
	monitor      *event.CommandMonitor
	crypt        *driver.Crypt
	database     string
	deployment   driver.Deployment
	selector     description.ServerSelector
	writeConcern *writeconcern.WriteConcern
	result       DropCollectionResult
	serverAPI    *driver.ServerAPIOptions
}

type DropCollectionResult struct {
	// The number of indexes in the dropped collection.
	NIndexesWas int32
	// The namespace of the dropped collection.
	Ns string
}

func buildDropCollectionResult(response bsoncore.Document, srvr driver.Server) (DropCollectionResult, error) {
	elements, err := response.Elements()
	if err != nil {
		return DropCollectionResult{}, err
	}
	dcr := DropCollectionResult{}
	for _, element := range elements {
		switch element.Key() {
		case "nIndexesWas":
			var ok bool
			dcr.NIndexesWas, ok = element.Value().AsInt32OK()
			if !ok {
				err = fmt.Errorf("response field 'nIndexesWas' is type int32, but received BSON type %s", element.Value().Type)
			}
		case "ns":
			var ok bool
			dcr.Ns, ok = element.Value().StringValueOK()
			if !ok {
				err = fmt.Errorf("response field 'ns' is type string, but received BSON type %s", element.Value().Type)
			}
		}
	}
	return dcr, nil
}

// NewDropCollection constructs and returns a new DropCollection.
func NewDropCollection() *DropCollection {
	return &DropCollection{}
}

// Result returns the result of executing this operation.
func (dc *DropCollection) Result() DropCollectionResult { return dc.result }

func (dc *DropCollection) processResponse(info driver.ResponseInfo) error {
	var err error
	dc.result, err = buildDropCollectionResult(info.ServerResponse, info.Server)
	return err
}

// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (dc *DropCollection) Execute(ctx context.Context) error {
	if dc.deployment == nil {
		return errors.New("the DropCollection operation must have a Deployment set before Execute can be called")
	}

	return driver.Operation{
		CommandFn:         dc.command,
		ProcessResponseFn: dc.processResponse,
		Client:            dc.session,
		Clock:             dc.clock,
		CommandMonitor:    dc.monitor,
		Crypt:             dc.crypt,
		Database:          dc.database,
		Deployment:        dc.deployment,
		Selector:          dc.selector,
		WriteConcern:      dc.writeConcern,
		ServerAPI:         dc.serverAPI,
	}.Execute(ctx, nil)

}

func (dc *DropCollection) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
	dst = bsoncore.AppendStringElement(dst, "drop", dc.collection)
	return dst, nil
}

// Session sets the session for this operation.
func (dc *DropCollection) Session(session *session.Client) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.session = session
	return dc
}

// ClusterClock sets the cluster clock for this operation.
func (dc *DropCollection) ClusterClock(clock *session.ClusterClock) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.clock = clock
	return dc
}

// Collection sets the collection that this command will run against.
func (dc *DropCollection) Collection(collection string) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.collection = collection
	return dc
}

// CommandMonitor sets the monitor to use for APM events.
func (dc *DropCollection) CommandMonitor(monitor *event.CommandMonitor) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.monitor = monitor
	return dc
}

// Crypt sets the Crypt object to use for automatic encryption and decryption.
func (dc *DropCollection) Crypt(crypt *driver.Crypt) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.crypt = crypt
	return dc
}

// Database sets the database to run this operation against.
func (dc *DropCollection) Database(database string) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.database = database
	return dc
}

// Deployment sets the deployment to use for this operation.
func (dc *DropCollection) Deployment(deployment driver.Deployment) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.deployment = deployment
	return dc
}

// ServerSelector sets the selector used to retrieve a server.
func (dc *DropCollection) ServerSelector(selector description.ServerSelector) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.selector = selector
	return dc
}

// WriteConcern sets the write concern for this operation.
func (dc *DropCollection) WriteConcern(writeConcern *writeconcern.WriteConcern) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.writeConcern = writeConcern
	return dc
}

// ServerAPI sets the server API version for this operation.
func (dc *DropCollection) ServerAPI(serverAPI *driver.ServerAPIOptions) *DropCollection {
	if dc == nil {
		dc = new(DropCollection)
	}

	dc.serverAPI = serverAPI
	return dc
}


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    # == Attributes
    #  text_node :brief_text, 'BriefText', :optional => true
    #  text_node :detailed_text, 'DetailedText', :optional => true
    #  numeric_node :code_id, '@codeID', :optional => true
    class ReasonCodeDetail
      include XML::Mapping
      include Initializer
      root_element_name 'ReasonCodeDetail'
      text_node :brief_text, 'BriefText', :optional => true
      text_node :detailed_text, 'DetailedText', :optional => true
      numeric_node :code_id, '@codeID', :optional => true
    end
  end
end


text:
/*
 * GET boomerang example.
 */

exports.get = function(req, res){
  res.render('example', { remoteAddress: req.connection.remoteAddress });
};


text:
package org.cagrid.gme.domain;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;

import junit.framework.TestCase;

/**
 * Tests the correct functionality of the utility methods of the XMLSchemaBundle
 * Class
 */
public class XMLSchemaBundleTestCase extends TestCase {

    private XMLSchemaNamespace nonExistantNamespace;

    private XMLSchemaNamespace s1_ns;
    private URI s1_uri;
    private XMLSchemaDocument s1_d1;
    private XMLSchemaDocument s1_d2;
    private XMLSchema s1;

    private XMLSchemaNamespace s2_ns;
    private URI s2_uri;
    private XMLSchemaDocument s2_d1;
    private XMLSchema s2;

    private XMLSchemaNamespace s3_ns;
    private URI s3_uri;
    private XMLSchema s3;
    private XMLSchemaDocument s3_d1;

    public void testEmptyBundle() {
        XMLSchemaBundle bundle = new XMLSchemaBundle();
        validateEmptyBundle(bundle);

        bundle.setImportInformation(null);
        bundle.setXMLSchemas(null);
        validateEmptyBundle(bundle);
    }

    public void testInvalidLookups() {
        XMLSchemaBundle bundle = new XMLSchemaBundle();

        Set<XMLSchema> xmlSchemaCollection = new HashSet<XMLSchema>();
        xmlSchemaCollection.add(this.s1);
        bundle.setXMLSchemas(xmlSchemaCollection);

        assertNull(bundle.getImportedXMLSchemasForTargetNamespace(this.nonExistantNamespace));
        assertNull(bundle.getXMLSchemaForTargetNamespace(this.nonExistantNamespace));
    }

    public void testValidLookupsNoImports() {
        XMLSchemaBundle bundle = new XMLSchemaBundle();

        Set<XMLSchema> xmlSchemaCollection = new HashSet<XMLSchema>();
        xmlSchemaCollection.add(this.s1);
        bundle.setXMLSchemas(xmlSchemaCollection);

        assertNull(bundle.getImportedXMLSchemasForTargetNamespace(this.s1_ns));
        assertNull(bundle.getImportInformationForTargetNamespace(this.s1_ns));
        assertNotNull(bundle.getXMLSchemaForTargetNamespace(this.s1_ns));
        assertEquals(this.s1, bundle.getXMLSchemaForTargetNamespace(this.s1_ns));

        Set<XMLSchemaNamespace> expected = new HashSet<XMLSchemaNamespace>();
        expected.add(this.s1_ns);
        assertEquals(expected, bundle.getXMLSchemaTargetNamespaces());
    }

    public void testValidLookupsWithImports() {
        XMLSchemaBundle bundle = new XMLSchemaBundle();

        // s1,s2
        Set<XMLSchema> xmlSchemaCollection = new HashSet<XMLSchema>();
        xmlSchemaCollection.add(this.s1);
        xmlSchemaCollection.add(this.s2);
        bundle.setXMLSchemas(xmlSchemaCollection);

        // s1 imports s2
        Set<XMLSchemaImportInformation> iiSet = new HashSet<XMLSchemaImportInformation>();
        XMLSchemaImportInformation ii = new XMLSchemaImportInformation();
        ii.setTargetNamespace(this.s1_ns);
        Set<XMLSchemaNamespace> imports = new HashSet<XMLSchemaNamespace>();
        imports.add(this.s2_ns);
        ii.setImports(imports);
        iiSet.add(ii);
        bundle.setImportInformation(iiSet);

        // should be able to retrieve s1's imports
        assertNotNull(bundle.getImportInformationForTargetNamespace(this.s1_ns));
        assertEquals(ii, bundle.getImportInformationForTargetNamespace(this.s1_ns));
        // should be able to see s2 has no imports
        assertNull(bundle.getImportInformationForTargetNamespace(this.s2_ns));

        // should be able to get back the s2 schema as an imported schema from
        // s1
        assertNotNull(bundle.getImportedXMLSchemasForTargetNamespace(this.s1_ns));
        Set<XMLSchema> resultSchemas = new HashSet<XMLSchema>();
        resultSchemas.add(this.s2);
        assertEquals(resultSchemas, bundle.getImportedXMLSchemasForTargetNamespace(this.s1_ns));
        // should be able to see s2 has no imports
        assertNull(bundle.getImportedXMLSchemasForTargetNamespace(this.s2_ns));

        // should be able to get back s1 by namespace
        assertNotNull(bundle.getXMLSchemaForTargetNamespace(this.s1_ns));
        assertEquals(this.s1, bundle.getXMLSchemaForTargetNamespace(this.s1_ns));
        // should be able to get back s2 by namespace
        assertNotNull(bundle.getXMLSchemaForTargetNamespace(this.s2_ns));
        assertEquals(this.s2, bundle.getXMLSchemaForTargetNamespace(this.s2_ns));

        // should be able to list the namespaces in the bundle as s1 and s2
        Set<XMLSchemaNamespace> expected = new HashSet<XMLSchemaNamespace>();
        expected.add(this.s1_ns);
        expected.add(this.s2_ns);
        assertEquals(expected, bundle.getXMLSchemaTargetNamespaces());
    }

    private void validateEmptyBundle(XMLSchemaBundle bundle) {
        assertNull(bundle.getImportedXMLSchemasForTargetNamespace(this.nonExistantNamespace));
        assertNull(bundle.getImportInformationForTargetNamespace(this.nonExistantNamespace));
        assertNull(bundle.getXMLSchemaForTargetNamespace(this.nonExistantNamespace));

        assertNotNull(bundle.getImportInformation());
        assertEquals(0, bundle.getImportInformation().size());

        assertNotNull(bundle.getXMLSchemas());
        assertEquals(0, bundle.getXMLSchemas().size());

        assertNotNull(bundle.getXMLSchemaTargetNamespaces());
        assertEquals(0, bundle.getXMLSchemaTargetNamespaces().size());
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(XMLSchemaBundleTestCase.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        try {
            this.nonExistantNamespace = new XMLSchemaNamespace("http://noschema");

            // SCHEMA 1 (root = s1_d1, docs=(s1_d2))
            this.s1_uri = new URI("http://s1");
            this.s1_ns = new XMLSchemaNamespace(this.s1_uri);

            this.s1_d1 = new XMLSchemaDocument();
            this.s1_d1.setSchemaText("<xml>This is the s1 schema, document s1_d1 text</xml>");
            this.s1_d1.setSystemID("s1_d1");

            this.s1_d2 = new XMLSchemaDocument();
            this.s1_d2.setSchemaText("<xml>This is the s1 schema, document s1_d2 text</xml>");
            this.s1_d2.setSystemID("s1_d2");

            this.s1 = new XMLSchema();
            this.s1.setRootDocument(this.s1_d1);
            this.s1.setTargetNamespace(this.s1_uri);
            Set<XMLSchemaDocument> s1_docs = new HashSet<XMLSchemaDocument>();
            this.s1.setAdditionalSchemaDocuments(s1_docs);

            // SCHEMA 2 (root = s2_d1, docs=())
            this.s2_uri = new URI("http://s2");
            this.s2_ns = new XMLSchemaNamespace(this.s2_uri);

            this.s2_d1 = new XMLSchemaDocument();
            this.s2_d1.setSchemaText("<xml>This is the s2 schema, document s2_d1 text</xml>");
            this.s2_d1.setSystemID("s2_d1");

            this.s2 = new XMLSchema();
            this.s2.setRootDocument(this.s2_d1);

            this.s2.setTargetNamespace(this.s2_uri);

            // SCHEMA 3 (root = s3_d1, docs=())
            this.s3_uri = new URI("http://s3");
            this.s3_ns = new XMLSchemaNamespace(this.s3_uri);

            this.s3_d1 = new XMLSchemaDocument();
            this.s3_d1.setSchemaText("<xml>This is the s3 schema, document s3_d1 text</xml>");
            this.s3_d1.setSystemID("s3_d1");

            this.s3 = new XMLSchema();
            this.s3.setRootDocument(this.s3_d1);

            this.s3.setTargetNamespace(this.s3_uri);

        } catch (URISyntaxException e) {
            fail("Unable to contruct namespaces");
        }
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

}


text:
jersey restful seed Project

使用到的项目

apache maven

oracle jersey

apache common dbutils

alibaba druid


text:
Synvert::Rewriter.new 'rspec', 'stub_and_mock_to_double' do
  description <<-EOF
It converts stub and mock to double.

    stub('something') => double('something')
    mock('something') => double('something')
  EOF

  if_gem 'rspec', {gte: '2.14.0'}

  within_files 'spec/**/*.rb' do
    # stub('something') => double('something')
    # mock('something') => double('something')
    with_node type: 'send', receiver: nil, message: 'stub' do
      replace_with "double({{arguments}})"
    end

    with_node type: 'send', receiver: nil, message: 'mock' do
      replace_with "double({{arguments}})"
    end
  end
end


text:
using System;
using Funq;
using RedisStackOverflow.ServiceInterface;
using ServiceStack;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Redis;
using IRepository = RedisStackOverflow.ServiceInterface.IRepository;

namespace RedisStackOverflow
{
    /// <summary>
    /// Create your ServiceStack web service application with a singleton AppHost.
    /// </summary>
    public class AppHost : AppHostBase
    {
        /// <summary>
        /// Initializes a new instance of your ServiceStack application, with the specified name and assembly containing the services.
        /// </summary>
        public AppHost() : base("Redis StackOverflow", typeof(QuestionsService).Assembly) { }

        /// <summary>
        /// Configure the container with the necessary routes for your ServiceStack application.
        /// </summary>
        /// <param name="container">The built-in IoC used with ServiceStack.</param>
        public override void Configure(Container container)
        {
            //Show StackTrace in Web Service Exceptions
            SetConfig(new HostConfig { DebugMode = true });

            //Register any dependencies you want injected into your services
            container.Register<IRedisClientsManager>(c => new PooledRedisClientManager());
            container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>()));
        }
    }

    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            if (ConfigUtils.GetAppSetting("log", false)) { LogManager.LogFactory = new ConsoleLogFactory(); }

            //Initialize your application
            (new AppHost()).Init();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TimePicker">
        <attr name="dial_color" format="color" />
        <attr name="text_color" format="color" />
        <attr name="clock_color" format="color" />
        <attr name="disable_touch" format="boolean"/>
    </declare-styleable>
</resources>


text:
@class LHLSquarItem;
@interface LHLSquareCell : UICollectionViewCell

@property (nonatomic, strong) LHLSquarItem *item;

@end


text:
<title>targetOptions.js by Matias Tofful 2015</title>

Zip code Required

<input style="padding:10px" type="text" placeholder="Enter Zip code"/>

You can Find your Zip code here.

Test another link


text:
package guitests;

import guitests.guihandles.TaskCardHandle;
import org.junit.Test;

import seedu.taskell.commons.core.Messages;
import seedu.taskell.logic.commands.AddCommand;
import seedu.taskell.logic.commands.HelpCommand;
import seedu.taskell.testutil.TestTask;
import seedu.taskell.testutil.TestUtil;

import static org.junit.Assert.assertTrue;
import static seedu.taskell.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

//@@author A0139257X-reused
public class AddCommandTest extends TaskManagerGuiTest {

    @Test
    public void add() {
        //add one task
        TestTask[] currentList = td.getTypicalTasks();
        TestTask taskToAdd = td.holdMeeting;
        assertAddSuccess(taskToAdd, currentList);
        currentList = TestUtil.addTasksToList(currentList, taskToAdd);

        //add another task
        taskToAdd = td.inspectWarehouse;
        assertAddSuccess(taskToAdd, currentList);
        currentList = TestUtil.addTasksToList(currentList, taskToAdd);

        //add duplicate task
        commandBox.runCommand(td.holdMeeting.getAddCommand());
        assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK);
        assertTrue(taskListPanel.isListMatching(currentList));

        //add to empty list
        commandBox.runCommand("clear");
        assertAddSuccess(td.archivePastEmails);

        //invalid command
        commandBox.runCommand("adds Johnny");
        assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);

       //add valid floating task
        commandBox.runCommand("clear");
        assertAddFloatingSuccess(td.floatingTask_Valid);

        commandBox.runCommand("clear");
        assertAddFloatingSuccess(td.floatingTask_NonIntuitiveDescription);

    }

    private void assertAddSuccess(TestTask taskToAdd, TestTask... currentList) {
        commandBox.runCommand(taskToAdd.getAddCommand());

        //confirm the new card contains the right data
        TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToAdd.getDescription().description);
        assertMatching(taskToAdd, addedCard);

        //confirm the list now contains all previous tasks plus the new task
        TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd);
        assertTrue(taskListPanel.isListMatching(expectedList));
    }

    private void assertAddFloatingSuccess(TestTask taskToAdd, TestTask... currentList) {
        commandBox.runCommand(taskToAdd.getAddFloatingCommand());

        //confirm the new card contains the right data
        TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToAdd.getDescription().description);
        assertMatching(taskToAdd, addedCard);

        //confirm the list now contains all previous tasks plus the new task
        TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd);
        assertTrue(taskListPanel.isListMatching(expectedList));
    }

}


text:
'use strict';

app.controller('PackageController', function($scope, $state, $stateParams,
      $mdDialog, KpmApi, Package, Session) {

  // Methods

  $scope.selectVersion = function() {
    var name = $scope.package.name + '/' + $scope.package.version;
    $state.go('package', {name: name});
  };

  $scope.toggleStar = function() {
    if (Session.isAuthenticated()) {
      var action = $scope.package.starred ? 'unstar' : 'star'
      KpmApi.put('packages/' + $scope.package.name + '/' + action)
      .success(function(data) {
        // Refresh attributes
        $scope.package.starred = !$scope.package.starred;
        $scope.package.stars = data.stars;
      })
      .error(function() {
        console.log('Cannot ' + action + ' package');
      });
    }
    else {
      $state.go('login');
    }
  };

  $scope.toggleResource = function(resource) {
    if (resource.content) {
      delete resource.content;
    }
    else {
      KpmApi.get('packages/' + $scope.package.name + '/file/templates/' + resource.file)
      .success(function(data) {
        resource.content = data;
      });
    }
  };

  $scope.downloadTarball = function(ev) {
    var confirm = $mdDialog.prompt()
      .title('Select namespace')
      .textContent('The name of your Kubernetes namespace.')
      .placeholder('namespace')
      .targetEvent(ev)
      .ok('Download')
      .cancel('Cancel');

    $mdDialog.show(confirm).then(function(result) {
      // Trigger download from URL with FileSaver library
      var url = Config.backend_url + 'packages/' + $scope.package.name +
        '/generate-tar?version=' + $scope.package.version + '&namespace=' + result;
      window.location = url;
    }, function() {
    });
  };

  $scope.setPackage = function(object) {
    $scope.package = new Package(object);
  };

  // Init

   var package_name = $stateParams.name;

    if (package_name) {
	var sp = package_name.split("/");
	var version = null;
	if (sp.length > 2) {
    	    version = sp[2]
    	    package_name = sp[0] + "/" + sp[1]
	}
	$scope.ui.loading = true;
	KpmApi.get('packages/' + package_name, {version: version})
	    .success(function(data) {
		$scope.ui.loading = false;
		$scope.setPackage(data);
	    })
	    .error(function(data) {
		$scope.ui.loading = false;
		$scope.error = $scope.build_error(data);
	    });
    }
});


text:
package org.jikesrvm.mm.mmtk;

import org.jikesrvm.ArchitectureSpecific;
import org.jikesrvm.VM;
import org.jikesrvm.Services;
import org.jikesrvm.classloader.MemberReference;
import org.jikesrvm.classloader.RVMMethod;
import org.jikesrvm.classloader.RVMType;
import org.jikesrvm.compilers.baseline.BaselineCompiledMethod;
import org.jikesrvm.compilers.common.CompiledMethod;
import org.jikesrvm.compilers.common.CompiledMethods;
import org.jikesrvm.compilers.opt.runtimesupport.OptCompiledMethod;
import org.jikesrvm.compilers.opt.runtimesupport.OptEncodedCallSiteTree;
import org.jikesrvm.compilers.opt.runtimesupport.OptMachineCodeMap;
import org.jikesrvm.objectmodel.MiscHeader;
import org.jikesrvm.objectmodel.ObjectModel;
import org.jikesrvm.objectmodel.TIB;
import org.jikesrvm.runtime.Magic;
import org.jikesrvm.scheduler.Scheduler;
import org.vmmagic.pragma.Inline;
import org.vmmagic.pragma.Interruptible;
import org.vmmagic.pragma.NoInline;
import org.vmmagic.pragma.Uninterruptible;
import org.vmmagic.unboxed.Address;
import org.vmmagic.unboxed.ObjectReference;
import org.vmmagic.unboxed.Offset;
import org.vmmagic.unboxed.Word;

/**
 * Class that supports scanning Objects or Arrays for references
 * during tracing, handling those references, and computing death times
 */
@Uninterruptible public final class TraceInterface extends org.mmtk.vm.TraceInterface implements ArchitectureSpecific.ArchConstants {

  /***********************************************************************
   *
   * Class variables
   */
  private static byte[][] allocCallMethods;

  static {
    /* Build the list of "own methods" */
    allocCallMethods = new byte[13][];
    allocCallMethods[0] = "postAlloc".getBytes();
    allocCallMethods[1] = "traceAlloc".getBytes();
    allocCallMethods[2] = "allocateScalar".getBytes();
    allocCallMethods[3] = "allocateArray".getBytes();
    allocCallMethods[4] = "clone".getBytes();
    allocCallMethods[5] = "alloc".getBytes();
    allocCallMethods[6] = "buildMultiDimensionalArray".getBytes();
    allocCallMethods[7] = "resolvedNewScalar".getBytes();
    allocCallMethods[8] = "resolvedNewArray".getBytes();
    allocCallMethods[9] = "unresolvedNewScalar".getBytes();
    allocCallMethods[10] = "unresolvedNewArray".getBytes();
    allocCallMethods[11] = "cloneScalar".getBytes();
    allocCallMethods[12] = "cloneArray".getBytes();
  }

  /***********************************************************************
   *
   * Public Methods
   */

  /**
   * Returns if the VM is ready for a garbage collection.
   *
   * @return True if the RVM is ready for GC, false otherwise.
   */
  public boolean gcEnabled() {
    return Scheduler.gcEnabled();
  }

  /**
   * Given a method name, determine if it is a "real" method or one
   * used for allocation/tracing.
   *
   * @param name The method name to test as an array of bytes
   * @return True if the method is a "real" method, false otherwise.
   */
  private boolean isAllocCall(byte[] name) {
    for (int i = 0; i < allocCallMethods.length; i++) {
      byte[] funcName = Services.getArrayNoBarrier(allocCallMethods, i);
      if (Magic.getArrayLength(name) == Magic.getArrayLength(funcName)) {
        /* Compare the letters in the allocCallMethod */
        int j = Magic.getArrayLength(funcName) - 1;
        while (j >= 0) {
          if (Services.getArrayNoBarrier(name, j) !=
              Services.getArrayNoBarrier(funcName, j))
            break;
          j--;
        }
        if (j == -1)
          return true;
      }
    }
    return false;
  }

  /**
   * This adjusts the offset into an object to reflect what it would look like
   * if the fields were laid out in memory space immediately after the object
   * pointer.
   *
   * @param isScalar If this is a pointer store to a scalar object
   * @param src The address of the source object
   * @param slot The address within src into which
   * the update will be stored
   * @return The easy to understand offset of the slot
   */
  public Offset adjustSlotOffset(boolean isScalar,
                                              ObjectReference src,
                                              Address slot) {
    /* Offset scalar objects so that the fields appear to begin at offset 0
       of the object. */
    Offset offset = slot.diff(src.toAddress());
    if (isScalar)
      return offset.minus(getHeaderEndOffset());
    else
      return offset;
  }

  /**
   * This skips over the frames added by the tracing algorithm, outputs
   * information identifying the method the containts the "new" call triggering
   * the allocation, and returns the address of the first non-trace, non-alloc
   * stack frame.
   *
   * @param typeRef The type reference (tib) of the object just allocated
   * @return The frame pointer address for the method that allocated the object
   */
  @NoInline
  @Interruptible // This can't be uninterruptible --- it is an IO routine
  public Address skipOwnFramesAndDump(ObjectReference typeRef) {
    TIB tib = Magic.addressAsTIB(typeRef.toAddress());
    RVMMethod m = null;
    int bci = -1;
    int compiledMethodID = 0;
    Offset ipOffset = Offset.zero();
    Address fp = Magic.getFramePointer();
    Address ip = Magic.getReturnAddress(fp);
    fp = Magic.getCallerFramePointer(fp);
    // This code borrows heavily from Scheduler.dumpStack
    while (Magic.getCallerFramePointer(fp).NE(STACKFRAME_SENTINEL_FP)) {
      compiledMethodID = Magic.getCompiledMethodID(fp);
      if (compiledMethodID != INVISIBLE_METHOD_ID) {
        // normal java frame(s)
        CompiledMethod compiledMethod =
          CompiledMethods.getCompiledMethod(compiledMethodID);
        if (compiledMethod.getCompilerType() != CompiledMethod.TRAP) {
          ipOffset = compiledMethod.getInstructionOffset(ip);
          m = compiledMethod.getMethod();
          if (VM.BuildForOptCompiler && compiledMethod.getCompilerType() == CompiledMethod.OPT) {
            OptCompiledMethod optInfo = (OptCompiledMethod)compiledMethod;
            /* Opt stack frames may contain multiple inlined methods. */
            OptMachineCodeMap map = optInfo.getMCMap();
            int iei = map.getInlineEncodingForMCOffset(ipOffset);
            if (iei >= 0) {
              int[] inlineEncoding = map.inlineEncoding;
              boolean allocCall = true;
              bci = map.getBytecodeIndexForMCOffset(ipOffset);
              for (int j = iei; j >= 0 && allocCall;
                   j = OptEncodedCallSiteTree.getParent(j,inlineEncoding)) {
                int mid = OptEncodedCallSiteTree.getMethodID(j, inlineEncoding);
                m = MemberReference.getMemberRef(mid).asMethodReference().getResolvedMember();
                if (!isAllocCall(m.getName().getBytes()))
                  allocCall = false;
                if (j > 0)
                  bci = OptEncodedCallSiteTree.getByteCodeOffset(j,
                                                                    inlineEncoding);
              }
              if (!allocCall)
                break;
            }
          } else {
            if (!isAllocCall(m.getName().getBytes())) {
              BaselineCompiledMethod baseInfo =
                (BaselineCompiledMethod)compiledMethod;
              bci = baseInfo.findBytecodeIndexForInstruction(ipOffset.toWord().lsh(INSTRUCTION_WIDTH).toOffset());
              break;
            }
          }
        }
      }
      ip = Magic.getReturnAddress(fp);
      fp = Magic.getCallerFramePointer(fp);
    }
    if (m != null) {
      int allocid = (((compiledMethodID & 0x0000ffff) << 15) ^
                     ((compiledMethodID & 0xffff0000) >> 16) ^
                     ipOffset.toInt()) & ~0x80000000;

      /* Now print the location string. */
      VM.sysWrite('\n');
      VM.writeHex(allocid);
      VM.sysWrite('-');
      VM.sysWrite('>');
      VM.sysWrite('[');
      VM.writeHex(compiledMethodID);
      VM.sysWrite(']');
      m.getDeclaringClass().getDescriptor().sysWrite();
      VM.sysWrite(':');
      m.getName().sysWrite();
      m.getDescriptor().sysWrite();
      VM.sysWrite(':');
      VM.writeHex(bci);
      VM.sysWrite('\t');
      RVMType type = tib.getType();
      type.getDescriptor().sysWrite();
      VM.sysWrite('\n');
    }
    return fp;
  }

  /***********************************************************************
   *
   * Wrapper methods
   */

  @Inline
  public void updateDeathTime(ObjectReference obj) {
    MiscHeader.updateDeathTime(obj.toObject());
  }

  @Inline
  public void setDeathTime(ObjectReference ref, Word time_) {
    MiscHeader.setDeathTime(ref.toObject(), time_);
  }

  @Inline
  public void setLink(ObjectReference ref, ObjectReference link) {
    MiscHeader.setLink(ref.toObject(), link);
  }

  @Inline
  public void updateTime(Word time_) {
    MiscHeader.updateTime(time_);
  }

  @Inline
  public Word getOID(ObjectReference ref) {
    return MiscHeader.getOID(ref.toObject());
  }

  @Inline
  public Word getDeathTime(ObjectReference ref) {
    return MiscHeader.getDeathTime(ref.toObject());
  }

  @Inline
  public ObjectReference getLink(ObjectReference ref) {
    return MiscHeader.getLink(ref.toObject());
  }

  @Inline
  public Address getBootImageLink() {
    return MiscHeader.getBootImageLink();
  }

  @Inline
  public Word getOID() {
    return MiscHeader.getOID();
  }

  @Inline
  public void setOID(Word oid) {
    MiscHeader.setOID(oid);
  }

  @Inline
  public int getHeaderSize() {
    return MiscHeader.getHeaderSize();
  }

  @Inline
  public int getHeaderEndOffset() {
    return ObjectModel.getHeaderEndOffset();
  }
}


text:
package consulo.csharp.ide.debugger.expressionEvaluator;

import javax.annotation.Nonnull;

import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import consulo.annotation.access.RequiredReadAction;
import consulo.csharp.ide.debugger.CSharpEvaluateContext;
import consulo.csharp.lang.psi.CSharpLocalVariable;
import consulo.dotnet.debugger.nodes.DotNetDebuggerCompilerGenerateUtil;
import consulo.dotnet.debugger.proxy.DotNetFieldProxy;
import consulo.dotnet.debugger.proxy.DotNetLocalVariableProxy;
import consulo.dotnet.debugger.proxy.DotNetMethodProxy;
import consulo.dotnet.debugger.proxy.DotNetStackFrameProxy;
import consulo.dotnet.debugger.proxy.DotNetTypeProxy;
import consulo.dotnet.debugger.proxy.value.DotNetValueProxy;

/**
 * @author VISTALL
 * @since 05.08.2015
 */
public class LocalVariableEvaluator extends LocalVariableOrParameterEvaluator<CSharpLocalVariable>
{
	@RequiredReadAction
	public LocalVariableEvaluator(CSharpLocalVariable localVariable)
	{
		super(localVariable);
	}

	@Override
	protected boolean tryEvaluateFromStackFrame(@Nonnull CSharpEvaluateContext context, DotNetStackFrameProxy frame, DotNetMethodProxy method)
	{
		DotNetLocalVariableProxy[] locals = method.getLocalVariables(frame);

		DotNetLocalVariableProxy mirror = null;
		DotNetFieldProxy wrappedFieldLocal = null;
		for(DotNetLocalVariableProxy local : locals)
		{
			String name = local.getName();
			if(StringUtil.isEmpty(name))
			{
				continue;
			}

			if(Comparing.equal(myName, name))
			{
				mirror = local;
				break;
			}

			if(DotNetDebuggerCompilerGenerateUtil.isLocalVarWrapper(name))
			{
				DotNetTypeProxy type = local.getType();
				if(type == null)
				{
					continue;
				}

				DotNetFieldProxy[] fields = type.getFields();
				if(fields.length != 1)
				{
					continue;
				}

				DotNetFieldProxy field = fields[0];
				if(Comparing.equal(myName, field.getName()))
				{
					mirror = local;
					wrappedFieldLocal = field;
					break;
				}
			}
		}

		if(mirror != null)
		{
			DotNetValueProxy value = frame.getLocalValue(mirror);

			if(wrappedFieldLocal != null && value != null)
			{
				DotNetValueProxy localValue = wrappedFieldLocal.getValue(frame, value);
				if(localValue != null)
				{
					context.pull(localValue, mirror);
					return true;
				}
			}
			else if(value != null)
			{
				context.pull(value, mirror);
				return true;
			}
		}
		return false;
	}
}


text:
#ifndef FGAIRCRAFT_H
#define FGAIRCRAFT_H

#include "FgAircraft.h"
#include "FgVehicle.h"
#include "flightgear/FgTransport.h"

class FgAircraft : public FgVehicle
{
    Q_OBJECT
    QML_READONLY_AUTO_PROPERTY(qreal, heading)
    QML_READONLY_AUTO_PROPERTY(qreal, pitch)
    QML_READONLY_AUTO_PROPERTY(qreal, roll)
    QML_READONLY_AUTO_PROPERTY(qreal, yaw)
    QML_READONLY_AUTO_PROPERTY(qreal, yaw_rate)
    QML_READONLY_AUTO_PROPERTY(qreal, vertical_speed)
    QML_READONLY_AUTO_PROPERTY(qreal, airspeed)

    QML_WRITABLE_AUTO_PROPERTY(qreal, ailerons)
    QML_WRITABLE_AUTO_PROPERTY(qreal, elevator)
    QML_WRITABLE_AUTO_PROPERTY(qreal, rudder)
    QML_WRITABLE_AUTO_PROPERTY(qreal, throttle)

public:
    explicit FgAircraft(QObject *parent = 0)
        : FgVehicle(parent)
        , m_heading(0.0)
        , m_pitch(0.0)
        , m_roll(0.0)
        , m_yaw(0.0)
        , m_yaw_rate(0.0)
        , m_vertical_speed(0.0)
        , m_airspeed(0.0)
        , m_ailerons(0.0)
        , m_elevator(0.0)
        , m_rudder(0.0)
        , m_throttle(0.8)
    {
    }

    virtual ~FgAircraft()
    {
    }

public slots:
    virtual void onFdmDataChanged(FgTransport *transport)
    {
        FgVehicle::onFdmDataChanged(transport);
        update_pitch(transport->getFloat(PITCH));
        update_roll(transport->getFloat(ROLL));
        update_yaw(transport->getFloat(YAW));
        update_yaw_rate(transport->getFloat(YAW_RATE));
        update_heading(transport->getFloat(HEADING));
        update_airspeed(transport->getFloat(AIRSPEED));
        update_vertical_speed(transport->getFloat(VERTICAL_SPEED));
    }
};

Q_DECLARE_METATYPE(FgAircraft *)

#endif /* FGAIRCRAFT_H */