text:
package virtualbox

import (
	"errors"
	"fmt"
	"net"
	"reflect"
	"runtime"
	"strings"
	"testing"
	"time"

	"github.com/rancher/machine/libmachine/drivers"
	"github.com/rancher/machine/libmachine/state"
	"github.com/stretchr/testify/assert"
)

type VBoxManagerMock struct {
	args   string
	stdOut string
	stdErr string
	err    error
}

func (v *VBoxManagerMock) vbm(args ...string) error {
	_, _, err := v.vbmOutErr(args...)
	return err
}

func (v *VBoxManagerMock) vbmOut(args ...string) (string, error) {
	stdout, _, err := v.vbmOutErr(args...)
	return stdout, err
}

func (v *VBoxManagerMock) vbmOutErr(args ...string) (string, string, error) {
	if strings.Join(args, " ") == v.args {
		return v.stdOut, v.stdErr, v.err
	}
	return "", "", errors.New("Invalid args")
}

func newTestDriver(name string) *Driver {
	return NewDriver(name, "")
}

func TestDriverName(t *testing.T) {
	driverName := newTestDriver("default").DriverName()

	assert.Equal(t, "virtualbox", driverName)
}

func TestSSHHostname(t *testing.T) {
	hostname, err := newTestDriver("default").GetSSHHostname()

	assert.Equal(t, "127.0.0.1", hostname)
	assert.NoError(t, err)
}

func TestDefaultSSHUsername(t *testing.T) {
	username := newTestDriver("default").GetSSHUsername()

	assert.Equal(t, "docker", username)
}

var parseShareFolderTestCases = []struct {
	shareFolder       string
	expectedShareDir  string
	expectedShareName string
}{
	{"dir:name", "dir", "name"},
	{"C:\\dir:name", "C:\\dir", "name"},
	{"C:\\:name", "C:\\", "name"},
}

func TestParseShareFolder(t *testing.T) {
	for _, parseShareFolderTestCase := range parseShareFolderTestCases {
		shareDir, shareName := parseShareFolder(parseShareFolderTestCase.shareFolder)

		assert.Equal(t, shareDir, parseShareFolderTestCase.expectedShareDir)
		assert.Equal(t, shareName, parseShareFolderTestCase.expectedShareName)
	}
}

func TestState(t *testing.T) {
	var tests = []struct {
		stdOut string
		state  state.State
	}{
		{`VMState="running"`, state.Running},
		{`VMState="paused"`, state.Paused},
		{`VMState="saved"`, state.Saved},
		{`VMState="poweroff"`, state.Stopped},
		{`VMState="aborted"`, state.Stopped},
		{`VMState="whatever"`, state.None},
		{`VMState=`, state.None},
	}

	for _, expected := range tests {
		driver := newTestDriver("default")
		driver.VBoxManager = &VBoxManagerMock{
			args:   "showvminfo default --machinereadable",
			stdOut: expected.stdOut,
		}

		machineState, err := driver.GetState()

		assert.NoError(t, err)
		assert.Equal(t, expected.state, machineState)
	}
}

func TestStateErrors(t *testing.T) {
	var tests = []struct {
		stdErr   string
		err      error
		finalErr error
	}{
		{"Could not find a registered machine named 'unknown'", errors.New("Bug"), errors.New("machine does not exist")},
		{"", errors.New("Unexpected error"), errors.New("Unexpected error")},
	}

	for _, expected := range tests {
		driver := newTestDriver("default")
		driver.VBoxManager = &VBoxManagerMock{
			args:   "showvminfo default --machinereadable",
			stdErr: expected.stdErr,
			err:    expected.err,
		}

		machineState, err := driver.GetState()

		assert.Equal(t, err, expected.finalErr)
		assert.Equal(t, state.Error, machineState)
	}
}

func TestGetRandomIPinSubnet(t *testing.T) {
	driver := newTestDriver("default")

	// test IP 1.2.3.4
	testIP := net.IPv4(byte(1), byte(2), byte(3), byte(4))
	newIP, err := getRandomIPinSubnet(driver, testIP)
	if err != nil {
		t.Fatal(err)
	}

	if testIP.Equal(newIP) {
		t.Fatalf("expected different IP (source %s); received %s", testIP.String(), newIP.String())
	}

	if newIP[0] != testIP[0] {
		t.Fatalf("expected first octet of %d; received %d", testIP[0], newIP[0])
	}

	if newIP[1] != testIP[1] {
		t.Fatalf("expected second octet of %d; received %d", testIP[1], newIP[1])
	}

	if newIP[2] != testIP[2] {
		t.Fatalf("expected third octet of %d; received %d", testIP[2], newIP[2])
	}
}

func TestGetHostOnlyMACAddress(t *testing.T) {
	driver := newTestDriver("default")
	driver.VBoxManager = &VBoxManagerMock{
		args:   "showvminfo default --machinereadable",
		stdOut: "unrelatedfield=whatever\nhostonlyadapter2=\"vboxnet1\"\nmacaddress2=\"004488AABBCC\"\n",
	}

	result, err := driver.getHostOnlyMACAddress()
	expected := "004488aabbcc"
	assert.NoError(t, err)
	assert.Equal(t, expected, result)
}

func TestGetHostOnlyMACAddressWhenNoHostOnlyAdapter(t *testing.T) {
	driver := newTestDriver("default")
	driver.VBoxManager = &VBoxManagerMock{
		args:   "showvminfo default --machinereadable",
		stdOut: "unrelatedfield=whatever\n",
	}

	result, err := driver.getHostOnlyMACAddress()
	assert.Empty(t, result)
	assert.Equal(t, err, errors.New("Machine does not have a host-only adapter"))
}

func TestParseIPForMACFromIPAddr(t *testing.T) {
	driver := newTestDriver("default")

	ipAddrOutput := "1: eth0:\n    link/ether 00:44:88:aa:bb:cc\n    inet 1.2.3.4/24\n2: eth1:\n    link/ether 11:55:99:dd:ee:ff\n   inet 5.6.7.8/24"

	result, err := driver.parseIPForMACFromIPAddr(ipAddrOutput, "004488aabbcc")
	assert.NoError(t, err)
	assert.Equal(t, result, "1.2.3.4")

	result, err = driver.parseIPForMACFromIPAddr(ipAddrOutput, "115599ddeeff")
	assert.NoError(t, err)
	assert.Equal(t, result, "5.6.7.8")

	result, err = driver.parseIPForMACFromIPAddr(ipAddrOutput, "000000000000")
	assert.Empty(t, result)
	assert.Equal(t, err, errors.New("Could not find matching IP for MAC address 000000000000"))
}

func TestGetIPErrors(t *testing.T) {
	var tests = []struct {
		stdOut   string
		err      error
		finalErr error
	}{
		{`VMState="poweroff"`, nil, errors.New("Host is not running")},
		{"", errors.New("Unable to get state"), errors.New("Unable to get state")},
	}

	for _, expected := range tests {
		driver := newTestDriver("default")
		driver.VBoxManager = &VBoxManagerMock{
			args:   "showvminfo default --machinereadable",
			stdOut: expected.stdOut,
			err:    expected.err,
		}

		ip, err := driver.GetIP()

		assert.Empty(t, ip)
		assert.Equal(t, err, expected.finalErr)

		url, err := driver.GetURL()

		assert.Empty(t, url)
		assert.Equal(t, err, expected.finalErr)
	}
}

func TestParseValidCIDR(t *testing.T) {
	ip, network, err := parseAndValidateCIDR("192.168.100.1/24")

	assert.Equal(t, "192.168.100.1", ip.String())
	assert.Equal(t, "192.168.100.0", network.IP.String())
	assert.Equal(t, "ffffff00", network.Mask.String())
	assert.NoError(t, err)
}

func TestInvalidCIDR(t *testing.T) {
	ip, network, err := parseAndValidateCIDR("192.168.100.1")

	assert.EqualError(t, err, "invalid CIDR address: 192.168.100.1")
	assert.Nil(t, ip)
	assert.Nil(t, network)
}

func TestInvalidNetworkIpCIDR(t *testing.T) {
	ip, network, err := parseAndValidateCIDR("192.168.100.0/24")

	assert.Equal(t, ErrNetworkAddrCidr, err)
	assert.Nil(t, ip)
	assert.Nil(t, network)
}

// Tests detection of a conflict between an existing vbox host-only network and a host network interface.  This
// scenario would happen if the docker-machine was created with the host on one network, and then the host gets
// moved to another network (e.g. different wifi routers)
func TestCIDRHostIFaceCollisionExisting(t *testing.T) {
	vbox := &VBoxManagerMock{
		args:   "list hostonlyifs",
		stdOut: stdOutTwoHostOnlyNetwork,
	}
	mhi := newMockHostInterfaces()
	_, err := mhi.addMockIface("192.168.99.42", 24, net.IPv4len, "en0", net.FlagUp|net.FlagBroadcast)
	assert.NoError(t, err)

	nets, err := listHostOnlyAdapters(vbox)
	assert.NoError(t, err)
	m, listErr := listHostInterfaces(mhi, nets)
	assert.Nil(t, listErr)
	assert.NotEmpty(t, m)

	_, network, cidrErr := net.ParseCIDR("192.168.99.1/24")
	assert.Nil(t, cidrErr)
	err = validateNoIPCollisions(mhi, network, nets)
	assert.Equal(t, ErrNetworkAddrCollision, err)
}

// Tests operation of validateNoIPCollisions when no conflicts exist.
func TestCIDRHostIFaceNoCollision(t *testing.T) {
	vbox := &VBoxManagerMock{
		args:   "list hostonlyifs",
		stdOut: stdOutTwoHostOnlyNetwork,
	}
	mhi := newMockHostInterfaces()
	_, err := mhi.addMockIface("10.10.0.22", 24, net.IPv4len, "en0", net.FlagUp|net.FlagBroadcast)
	assert.NoError(t, err)

	nets, err := listHostOnlyAdapters(vbox)
	assert.NoError(t, err)
	m, listErr := listHostInterfaces(mhi, nets)
	assert.Nil(t, listErr)
	assert.NotEmpty(t, m)

	_, network, cidrErr := net.ParseCIDR("192.168.99.1/24")
	assert.Nil(t, cidrErr)
	err = validateNoIPCollisions(mhi, network, nets)
	assert.NoError(t, err)
}

// Tests detection of a conflict between a potential vbox host-only network and a host network interface.
func TestCIDRHostIFaceCollision(t *testing.T) {
	vbox := &VBoxManagerMock{
		args:   "list hostonlyifs",
		stdOut: "",
	}
	mhi := newMockHostInterfaces()
	_, err := mhi.addMockIface("192.168.99.42", 24, net.IPv4len, "en0", net.FlagUp|net.FlagBroadcast)
	assert.NoError(t, err)

	nets, err := listHostOnlyAdapters(vbox)
	assert.NoError(t, err)
	m, listErr := listHostInterfaces(mhi, nets)
	assert.Nil(t, listErr)
	assert.NotEmpty(t, m)

	_, network, cidrErr := net.ParseCIDR("192.168.99.1/24")
	assert.Nil(t, cidrErr)
	err = validateNoIPCollisions(mhi, network, nets)
	assert.Equal(t, ErrNetworkAddrCollision, err)
}

// Tests the behavior of getDHCPAddressRange with a variety of subnets.
func TestGetDHCPAddressRange(t *testing.T) {
	tests := []struct {
		name            string
		dhcpAddrCIDR    string
		expectedLowerIP net.IP
		expectedUpperIP net.IP
	}{
		{
			"Test /8 CIDR",
			"10.0.0.14/8",
			net.ParseIP("10.0.0.100"),
			net.ParseIP("10.0.0.254"),
		},
		{
			"Test /24 CIDR",
			"192.168.99.7/24",
			net.ParseIP("192.168.99.100"),
			net.ParseIP("192.168.99.254"),
		},
		{
			"Test /25 CIDR",
			"100.121.20.19/25",
			net.ParseIP("100.121.20.20"),
			net.ParseIP("100.121.20.126"),
		},
		{
			"Test /28 CIDR",
			"100.121.10.8/28",
			net.ParseIP("100.121.10.9"),
			net.ParseIP("100.121.10.14"),
		},
	}

	getTestArgsFromCIDR := func(cidr string) (dhcpAddr net.IP, network *net.IPNet) {
		var err error
		dhcpAddr, network, err = net.ParseCIDR(cidr)
		assert.NoError(t, err, "Invalid CIDR %s", cidr)
		return
	}

	for _, tt := range tests {
		dhcpAddr, network := getTestArgsFromCIDR(tt.dhcpAddrCIDR)
		t.Run(tt.name, func(t *testing.T) {
			lowerIP, upperIP := getDHCPAddressRange(dhcpAddr, network)
			if !reflect.DeepEqual(lowerIP, tt.expectedLowerIP) {
				t.Errorf("getDHCPAddressRange() lowerIP = %v, want %v", lowerIP, tt.expectedLowerIP)
			}
			if !reflect.DeepEqual(upperIP, tt.expectedUpperIP) {
				t.Errorf("getDHCPAddressRange() upperIP = %v, want %v", upperIP, tt.expectedUpperIP)
			}
		})
	}
}

func TestSetConfigFromFlags(t *testing.T) {
	driver := newTestDriver("default")

	checkFlags := &drivers.CheckDriverOptions{
		FlagsValues: map[string]interface{}{},
		CreateFlags: driver.GetCreateFlags(),
	}

	err := driver.SetConfigFromFlags(checkFlags)

	assert.NoError(t, err)
	assert.Empty(t, checkFlags.InvalidFlags)
}

type MockCreateOperations struct {
	test          *testing.T
	expectedCalls []Call
	call          int
}

type Call struct {
	signature string
	output    string
	err       error
}

func (v *MockCreateOperations) vbm(args ...string) error {
	_, _, err := v.vbmOutErr(args...)
	return err
}

func (v *MockCreateOperations) vbmOut(args ...string) (string, error) {
	stdout, _, err := v.vbmOutErr(args...)
	return stdout, err
}

func (v *MockCreateOperations) vbmOutErr(args ...string) (string, string, error) {
	output, err := v.doCall("vbm " + strings.Join(args, " "))
	return output, "", err
}

func (v *MockCreateOperations) UpdateISOCache(storePath, isoURL string) error {
	_, err := v.doCall("UpdateISOCache " + storePath + " " + isoURL)
	return err
}

func (v *MockCreateOperations) CopyIsoToMachineDir(storePath, machineName, isoURL string) error {
	_, err := v.doCall("CopyIsoToMachineDir " + storePath + " " + machineName + " " + isoURL)
	return err
}

func (v *MockCreateOperations) Generate(path string) error {
	_, err := v.doCall("Generate " + path)
	return err
}

func (v *MockCreateOperations) Create(size int, publicSSHKeyPath, diskPath string) error {
	_, err := v.doCall("Create " + fmt.Sprintf("%d %s %s", size, publicSSHKeyPath, diskPath))
	return err
}

func (v *MockCreateOperations) Read(path string) ([]string, error) {
	_, err := v.doCall("Read " + path)
	return []string{}, err
}

func (v *MockCreateOperations) Wait(d *Driver) error {
	_, err := v.doCall("WaitIP")
	return err
}

func (v *MockCreateOperations) RandomInt(n int) int {
	return 5
}

func (v *MockCreateOperations) Sleep(d time.Duration) {
	v.doCall("Sleep " + fmt.Sprintf("%v", d))
}

func (v *MockCreateOperations) Interfaces() ([]net.Interface, error) {
	_, err := v.doCall("Interfaces")
	return []net.Interface{}, err
}

func (v *MockCreateOperations) Addrs(iface *net.Interface) ([]net.Addr, error) {
	_, err := v.doCall("Addrs " + fmt.Sprintf("%v", iface))
	return []net.Addr{}, err
}

func (v *MockCreateOperations) expectCall(callSignature, output string, err error) {
	v.expectedCalls = append(v.expectedCalls, Call{
		signature: callSignature,
		output:    output,
		err:       err,
	})
}

func (v *MockCreateOperations) doCall(callSignature string) (string, error) {
	if v.call >= len(v.expectedCalls) {
		v.test.Fatal("Unexpected call", callSignature)

	}

	call := v.expectedCalls[v.call]
	if call.signature != "IGNORE CALL" && (callSignature != call.signature) {
		v.test.Fatal("Unexpected call", callSignature)
	}

	v.call++

	return call.output, call.err
}

func mockCalls(t *testing.T, driver *Driver, expectedCalls []Call) {
	mockOperations := &MockCreateOperations{
		test:          t,
		expectedCalls: expectedCalls,
	}

	driver.Boot2DockerURL = "http://b2d.org"
	driver.VBoxManager = mockOperations
	driver.b2dUpdater = mockOperations
	driver.sshKeyGenerator = mockOperations
	driver.diskCreator = mockOperations
	driver.logsReader = mockOperations
	driver.ipWaiter = mockOperations
	driver.randomInter = mockOperations
	driver.sleeper = mockOperations
	driver.HostInterfaces = mockOperations
}

func TestCreateVM(t *testing.T) {
	shareName, shareDir := getShareDriveAndName()

	modifyVMcommand := "vbm modifyvm default --firmware bios --bioslogofadein off --bioslogofadeout off --bioslogodisplaytime 0 --biosbootmenu disabled --ostype Linux26_64 --cpus 1 --memory 1024 --acpi on --ioapic on --rtcuseutc on --natdnshostresolver1 off --natdnsproxy1 on --cpuhotplug off --pae on --hpet on --hwvirtex on --nestedpaging on --largepages on --vtxvpid on --accelerate3d off --boot1 dvd"
	if runtime.GOOS == "windows" && runtime.GOARCH == "386" {
		modifyVMcommand += " --longmode on"
	}

	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"CopyIsoToMachineDir path default http://b2d.org", "", nil},
		{"Generate path/machines/default/id_rsa", "", nil},
		{"Create 20000 path/machines/default/id_rsa.pub path/machines/default/disk.vmdk", "", nil},
		{"vbm createvm --basefolder path/machines/default --name default --register", "", nil},
		{modifyVMcommand, "", nil},
		{"vbm modifyvm default --nic1 nat --nictype1 82540EM --cableconnected1 on", "", nil},
		{"vbm storagectl default --name SATA --add sata --hostiocache on", "", nil},
		{"vbm storageattach default --storagectl SATA --port 0 --device 0 --type dvddrive --medium path/machines/default/boot2docker.iso", "", nil},
		{"vbm storageattach default --storagectl SATA --port 1 --device 0 --type hdd --medium path/machines/default/disk.vmdk", "", nil},
		{"vbm guestproperty set default /VirtualBox/GuestAdd/SharedFolders/MountPrefix /", "", nil},
		{"vbm guestproperty set default /VirtualBox/GuestAdd/SharedFolders/MountDir /", "", nil},
		{"vbm sharedfolder add default --name " + shareName + " --hostpath " + shareDir + " --automount", "", nil},
		{"vbm setextradata default VBoxInternal2/SharedFoldersEnableSymlinksCreate/" + shareName + " 1", "", nil},
	})

	err := driver.CreateVM()

	assert.NoError(t, err)
}

func TestCreateVMWithSpecificNatNicType(t *testing.T) {
	shareName, shareDir := getShareDriveAndName()

	modifyVMcommand := "vbm modifyvm default --firmware bios --bioslogofadein off --bioslogofadeout off --bioslogodisplaytime 0 --biosbootmenu disabled --ostype Linux26_64 --cpus 1 --memory 1024 --acpi on --ioapic on --rtcuseutc on --natdnshostresolver1 off --natdnsproxy1 on --cpuhotplug off --pae on --hpet on --hwvirtex on --nestedpaging on --largepages on --vtxvpid on --accelerate3d off --boot1 dvd"
	if runtime.GOOS == "windows" && runtime.GOARCH == "386" {
		modifyVMcommand += " --longmode on"
	}

	driver := NewDriver("default", "path")
	driver.NatNicType = "Am79C973"
	mockCalls(t, driver, []Call{
		{"CopyIsoToMachineDir path default http://b2d.org", "", nil},
		{"Generate path/machines/default/id_rsa", "", nil},
		{"Create 20000 path/machines/default/id_rsa.pub path/machines/default/disk.vmdk", "", nil},
		{"vbm createvm --basefolder path/machines/default --name default --register", "", nil},
		{modifyVMcommand, "", nil},
		{"vbm modifyvm default --nic1 nat --nictype1 Am79C973 --cableconnected1 on", "", nil},
		{"vbm storagectl default --name SATA --add sata --hostiocache on", "", nil},
		{"vbm storageattach default --storagectl SATA --port 0 --device 0 --type dvddrive --medium path/machines/default/boot2docker.iso", "", nil},
		{"vbm storageattach default --storagectl SATA --port 1 --device 0 --type hdd --medium path/machines/default/disk.vmdk", "", nil},
		{"vbm guestproperty set default /VirtualBox/GuestAdd/SharedFolders/MountPrefix /", "", nil},
		{"vbm guestproperty set default /VirtualBox/GuestAdd/SharedFolders/MountDir /", "", nil},
		{"vbm sharedfolder add default --name " + shareName + " --hostpath " + shareDir + " --automount", "", nil},
		{"vbm setextradata default VBoxInternal2/SharedFoldersEnableSymlinksCreate/" + shareName + " 1", "", nil},
	})

	err := driver.CreateVM()

	assert.NoError(t, err)
}

func TestStart(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="poweroff"`, nil},
		{"vbm list hostonlyifs", "", nil},
		{"Interfaces", "", nil},
		{"vbm hostonlyif create", "Interface 'VirtualBox Host-Only Ethernet Adapter' was successfully created", nil},
		{"vbm list hostonlyifs", `
Name:            VirtualBox Host-Only Ethernet Adapter
GUID:            786f6276-656e-4074-8000-0a0027000000
DHCP:            Disabled
IPAddress:       192.168.99.1
NetworkMask:     255.255.255.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 0a:00:27:00:00:00
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter`, nil},
		{"vbm hostonlyif ipconfig VirtualBox Host-Only Ethernet Adapter --ip 192.168.99.1 --netmask 255.255.255.0", "", nil},
		{"vbm list dhcpservers", "", nil},
		{"vbm list dhcpservers", "", nil},
		{"vbm dhcpserver add --netname HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter --ip 192.168.99.6 --netmask 255.255.255.0 --lowerip 192.168.99.100 --upperip 192.168.99.254 --enable", "", nil},
		{"vbm modifyvm default --nic2 hostonly --nictype2 82540EM --nicpromisc2 deny --hostonlyadapter2 VirtualBox Host-Only Ethernet Adapter --cableconnected2 on", "", nil},
		{"IGNORE CALL", "", nil},
		{"IGNORE CALL", "", nil},
		{"vbm startvm default --type headless", "", nil},
		{"Read path/machines/default/default/Logs/VBox.log", "", nil},
		{"WaitIP", "", nil},
		{"vbm list hostonlyifs", `
Name:            VirtualBox Host-Only Ethernet Adapter
GUID:            786f6276-656e-4074-8000-0a0027000000
DHCP:            Disabled
IPAddress:       192.168.99.1
NetworkMask:     255.255.255.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 0a:00:27:00:00:00
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter`, nil},
		{"Interfaces", "", nil},
	})

	err := driver.Start()

	assert.NoError(t, err)
}

func TestStartWithHostOnlyAdapterCreationBug(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="poweroff"`, nil},
		{"vbm list hostonlyifs", "", nil},
		{"Interfaces", "", nil},
		{"vbm hostonlyif create", "", errors.New("error: Failed to create the host-only adapter")},
		{"vbm list hostonlyifs", "", nil},
		{"vbm list hostonlyifs", `
Name:            VirtualBox Host-Only Ethernet Adapter
GUID:            786f6276-656e-4074-8000-0a0027000000
DHCP:            Disabled
IPAddress:       192.168.99.1
NetworkMask:     255.255.255.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 0a:00:27:00:00:00
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter`, nil},
		{"vbm hostonlyif ipconfig VirtualBox Host-Only Ethernet Adapter --ip 192.168.99.1 --netmask 255.255.255.0", "", nil},
		{"vbm list dhcpservers", "", nil},
		{"vbm list dhcpservers", "", nil},
		{"vbm dhcpserver add --netname HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter --ip 192.168.99.6 --netmask 255.255.255.0 --lowerip 192.168.99.100 --upperip 192.168.99.254 --enable", "", nil},
		{"vbm modifyvm default --nic2 hostonly --nictype2 82540EM --nicpromisc2 deny --hostonlyadapter2 VirtualBox Host-Only Ethernet Adapter --cableconnected2 on", "", nil},
		{"IGNORE CALL", "", nil},
		{"IGNORE CALL", "", nil},
		{"vbm startvm default --type headless", "", nil},
		{"Read path/machines/default/default/Logs/VBox.log", "", nil},
		{"WaitIP", "", nil},
		{"vbm list hostonlyifs", `
Name:            VirtualBox Host-Only Ethernet Adapter
GUID:            786f6276-656e-4074-8000-0a0027000000
DHCP:            Disabled
IPAddress:       192.168.99.100
NetworkMask:     255.255.255.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 0a:00:27:00:00:00
MediumType:      Ethernet
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter`, nil},
		{"Interfaces", "", nil},
		{"vbm showvminfo default --machinereadable", `VMState="running"`, nil},
		{"vbm controlvm default acpipowerbutton", "", nil},
		{"vbm showvminfo default --machinereadable", `VMState="stopped"`, nil},
		{"Sleep 5s", "", nil},
		{"vbm hostonlyif ipconfig VirtualBox Host-Only Ethernet Adapter --ip 192.168.99.1 --netmask 255.255.255.0", "", nil},
		{"Sleep 5s", "", nil},
		{"vbm startvm default --type headless", "", nil},
		{"WaitIP", "", nil},
	})

	err := driver.Start()

	assert.NoError(t, err)
}

func TestRemoveStopped(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="poweroff"`, nil},
		{"vbm unregistervm --delete default", "", nil},
	})

	err := driver.Remove()

	assert.NoError(t, err)
}

func TestRemoveStarted(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="running"`, nil},
		{"vbm controlvm default poweroff", "", nil},
		{"vbm unregistervm --delete default", "", nil},
	})

	err := driver.Remove()

	assert.NoError(t, err)
}

func TestRemoveSaved(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="saved"`, nil},
		{"vbm unregistervm --delete default", "", nil},
	})

	err := driver.Remove()

	assert.NoError(t, err)
}

func TestRemovePaused(t *testing.T) {
	driver := NewDriver("default", "path")
	mockCalls(t, driver, []Call{
		{"vbm showvminfo default --machinereadable", `VMState="running"`, nil},
		{"vbm controlvm default poweroff", "", nil},
		{"vbm unregistervm --delete default", "", nil},
	})

	err := driver.Remove()

	assert.NoError(t, err)
}


text:
module UI {

  export var hawtioDrag = _module.directive("hawtioDrag", [() => {
    return {
      replace: false,
      transclude: true,
      restrict: 'A',
      template: '',
      scope: {
        data: '=hawtioDrag'
      },
      link: (scope, element:ng.IAugmentedJQuery, attrs) => {
        element.attr({
          draggable: 'true'
        });
        //log.debug("hawtioDrag, data: ", scope.data);
        var el = element[0];
        el.draggable = true;
        el.addEventListener('dragstart', (event:DragEvent) => {
          event.dataTransfer.effectAllowed = 'move';
          event.dataTransfer.setData('text', scope.data);
          element.addClass('drag-started');
          return false;
        }, false);

        el.addEventListener('dragend', (event:DragEvent) => {
          element.removeClass('drag-started');
        }, false);
      }
    }
  }]);

  export var hawtioDrop = _module.directive("hawtioDrop", [() => {
    return {
      replace: false,
      transclude: true,
      restrict: 'A',
      template: '',
      scope: {
        onDrop: '&?hawtioDrop',
        ngModel: '=',
        property: '@',
        prefix: '@'
      },
      link: (scope, element, attrs) => {
        //log.debug("hawtioDrop, onDrop: ", scope.onDrop);
        //log.debug("hawtioDrop, ngModel: ", scope.ngModel);
        //log.debug("hawtioDrop, property: ", scope.property);

        var dragEnter = (event:DragEvent) => {
          if (event.preventDefault) {
            event.preventDefault();
          }
          element.addClass('drag-over');
          return false;
        };

        var el = element[0];
        el.addEventListener('dragenter', dragEnter, false);
        el.addEventListener('dragover', dragEnter, false);
        el.addEventListener('dragleave', (event:DragEvent) => {
          element.removeClass('drag-over');
          return false;
        }, false);
        el.addEventListener('drop', (event:DragEvent) => {
          if (event.stopPropagation) {
            event.stopPropagation();
          }
          element.removeClass('drag-over');
          var data = event.dataTransfer.getData('text');
          if (scope.onDrop) {
            scope.$eval(scope.onDrop, {
              data: data,
              model: scope.ngModel,
              property: scope.property
            });
          }
          var eventName = 'hawtio-drop';
          if (!Core.isBlank(scope.prefix)) {
            eventName = scope.prefix + '-' + eventName;
          }
          // let's emit this too so parent scopes can watch for the data
          scope.$emit(eventName, {
            data: data,
            model: scope.ngModel,
            property: scope.property
          });
          Core.$apply(scope);
          return false;
        }, false);
      }
    }
  }]);

}

redpajama_set_name: RedPajamaGithub


text:
var testDigraphParams = require('./fixture/test-runner-digraph-in-params');

testDigraphParams({
    testName: "Undefined request",
    validatorFunction: 'verifyVertexReadRequest',
    validConfig: false,
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found when expecting vertex read request. Expected \'[object String]\'.',
    }
});

testDigraphParams({
    testName: "Bad request type",
    validatorFunction: 'verifyVertexReadRequest',
    validConfig: false,
    request: [ "Hey, man!" ],
    expectedResults: {
        error: 'Invalid value type \'[object Array]\' found when expecting vertex read request. Expected \'[object String]\'.',
    }
});

testDigraphParams({
    testName: "Valid request",
    validatorFunction: 'verifyVertexReadRequest',
    validConfig: true,
    request: "vertexID",
    expectedResults: {
        result: true
    }
});

testDigraphParams({
    testName: "Missing request",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: false,
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found when expecting a vertex write request object.'
    }
});

testDigraphParams({
    testName: "Empty request",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: false,
    request: {},
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for vertex ID string property \'u\' in vertex write request object.'
    }
});

testDigraphParams({
    testName: "Bad 'u' type",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: false,
    request: { u: [ "Hey, man!"] },
    expectedResults: {
        error: 'Invalid value type \'[object Array]\' found looking for vertex ID string property \'u\' in vertex write request object.'
    }
});

testDigraphParams({
    testName: "Valid 'u'",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: true,
    request: { u: "Hey, man!" },
    expectedResults: {
        result: true
    }
});

testDigraphParams({
    testName: "Invalid 'p' type",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: false,
    request: { u: "Hey, man!", p: function() {} },
    expectedResults: {
        error: 'Invalid value type \'[object Function] found while inspecting vertex property \'p\' in vertex write request object. Must be serializable to JSON!'
    }
});

testDigraphParams({
    testName: "Valid full request",
    validatorFunction: 'verifyVertexWriteRequest',
    validConfig: true,
    request: { u: "Hey, man!", p: "whatever" },
    expectedResults: {
        result: true
    }
});

testDigraphParams({
    testName: "Missing request",
    validatorFunction: 'verifyEdgeReadRequest',
    validConfig: false,
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found when expecting edge read request object.'
    }
});

testDigraphParams({
    testName: "Bad 'u'",
    validatorFunction: 'verifyEdgeReadRequest',
    validConfig: false,
    request: {},
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for vertex ID string property \'u\' in edge read request object.'
    }
});

testDigraphParams({
    testName: "Bad 'v'",
    validatorFunction: 'verifyEdgeReadRequest',
    validConfig: false,
    request: { u: 'vertexV' },
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for vertex ID string property \'v\' in edge read request object.'
    }
});

testDigraphParams({
    testName: "Valid 'v'",
    validatorFunction: 'verifyEdgeReadRequest',
    validConfig: true,
    request: { u: 'vertexU', v: 'vertexV' },
    expectedResults: {
        result: true
    }
});

testDigraphParams({
    testName: "Missing request",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: false,
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found when expecting edge write request object.'
    }
});

testDigraphParams({
    testName: "Bad 'e'",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: false,
    request: {},
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for edge descriptor object \'e\' in edge write request object.'
    }
});

testDigraphParams({
    testName: "Bad 'e.u'",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: false,
    request: { e: {} },
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for vertex ID string property \'e.u\' in edge write request object.'
    }
});

testDigraphParams({
    testName: "Bad 'e.v'",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: false,
    request: { e: { u: 'vertexU' } },
    expectedResults: {
        error: 'Invalid value type \'[object Undefined]\' found looking for vertex ID string property \'e.v\' in edge write request object.'
    }
});

testDigraphParams({
    testName: "Valid 'e'",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: true,
    request: { e: { u: 'vertexU', v: 'vertexV' } },
    expectedResults: {
        result: true
    }
});

testDigraphParams({
    testName: "Bad 'p'",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: false,
    request: { e: { u: 'vertexU', v: 'vertexV' }, p: function() {} },
    expectedResults: {
        error: 'Invalid value type \'[object Function]\' found while insecting edge property \'p\' in edge write request object. Must be serializable to JSON!'
    }
});

testDigraphParams({
    testName: "Valid full request",
    validatorFunction: 'verifyEdgeWriteRequest',
    validConfig: true,
    request: { e: { u: 'vertexU', v: 'vertexV' }, p: "whatever" },
    expectedResults: {
        result: true
    }
});


text:
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.RaytracingRenderer = function ( parameters ) {

	console.log( 'THREE.RaytracingRenderer', THREE.REVISION );

	parameters = parameters || {};

	var canvas = document.createElement( 'canvas' );
	var context = canvas.getContext( '2d', {
		alpha: parameters.alpha === true
	} );

	var maxRecursionDepth = 3;

	var canvasWidth, canvasHeight;
	var canvasWidthHalf, canvasHeightHalf;

	var clearColor = new THREE.Color( 0x000000 );

	var origin = new THREE.Vector3();
	var direction = new THREE.Vector3();

	var cameraPosition = new THREE.Vector3();

	var raycaster = new THREE.Raycaster( origin, direction );
	var raycasterLight = new THREE.Raycaster();

	var perspective;
	var modelViewMatrix = new THREE.Matrix4();
	var cameraNormalMatrix = new THREE.Matrix3();

	var objects;
	var lights = [];
	var cache = {};

	var animationFrameId = null;

	this.domElement = canvas;

	this.autoClear = true;

	this.setClearColor = function ( color, alpha ) {

		clearColor.set( color );

	};

	this.setPixelRatio = function () {};

	this.setSize = function ( width, height ) {

		canvas.width = width;
		canvas.height = height;

		canvasWidth = canvas.width;
		canvasHeight = canvas.height;

		canvasWidthHalf = Math.floor( canvasWidth / 2 );
		canvasHeightHalf = Math.floor( canvasHeight / 2 );

		context.fillStyle = 'white';

	};

	this.setSize( canvas.width, canvas.height );

	this.clear = function () {

	};

	//

	var spawnRay = ( function () {

		var diffuseColor = new THREE.Color();
		var specularColor = new THREE.Color();
		var lightColor = new THREE.Color();
		var schlick = new THREE.Color();

		var lightContribution = new THREE.Color();

		var eyeVector = new THREE.Vector3();
		var lightVector = new THREE.Vector3();
		var normalVector = new THREE.Vector3();
		var halfVector = new THREE.Vector3();

		var localPoint = new THREE.Vector3();
		var reflectionVector = new THREE.Vector3();

		var tmpVec = new THREE.Vector3();

		var tmpColor = [];

		for ( var i = 0; i < maxRecursionDepth; i ++ ) {

			tmpColor[ i ] = new THREE.Color();

		}

		return function ( rayOrigin, rayDirection, outputColor, recursionDepth ) {

			var ray = raycaster.ray;

			ray.origin = rayOrigin;
			ray.direction = rayDirection;

			//

			var rayLight = raycasterLight.ray;

			//

			outputColor.setRGB( 0, 0, 0 );

			//

			var intersections = raycaster.intersectObjects( objects, true );

			// ray didn't find anything
			// (here should come setting of background color?)

			if ( intersections.length === 0 ) {

				return;

			}

			// ray hit

			var intersection = intersections[ 0 ];

			var point = intersection.point;
			var object = intersection.object;
			var material = object.material;
			var face = intersection.face;

			var vertices = object.geometry.vertices;

			//

			var _object = cache[ object.id ];

			localPoint.copy( point ).applyMatrix4( _object.inverseMatrix );
			eyeVector.subVectors( raycaster.ray.origin, point ).normalize();

			// resolve pixel diffuse color

			if ( material instanceof THREE.MeshLambertMaterial ||
				 material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshBasicMaterial ) {

				diffuseColor.copyGammaToLinear( material.color );

			} else {

				diffuseColor.setRGB( 1, 1, 1 );

			}

			if ( material.vertexColors === THREE.FaceColors ) {

				diffuseColor.multiply( face.color );

			}

			// compute light shading

			rayLight.origin.copy( point );

			if ( material instanceof THREE.MeshBasicMaterial ) {

				for ( var i = 0, l = lights.length; i < l; i ++ ) {

					var light = lights[ i ];

					lightVector.setFromMatrixPosition( light.matrixWorld );
					lightVector.sub( point );

					rayLight.direction.copy( lightVector ).normalize();

					var intersections = raycasterLight.intersectObjects( objects, true );

					// point in shadow

					if ( intersections.length > 0 ) continue;

					// point visible

					outputColor.add( diffuseColor );

				}

			} else if ( material instanceof THREE.MeshLambertMaterial ||
						material instanceof THREE.MeshPhongMaterial ) {

				var normalComputed = false;

				for ( var i = 0, l = lights.length; i < l; i ++ ) {

					var light = lights[ i ];

					lightColor.copyGammaToLinear( light.color );

					lightVector.setFromMatrixPosition( light.matrixWorld );
					lightVector.sub( point );

					rayLight.direction.copy( lightVector ).normalize();

					var intersections = raycasterLight.intersectObjects( objects, true );

					// point in shadow

					if ( intersections.length > 0 ) continue;

					// point lit

					if ( normalComputed === false ) {

						// the same normal can be reused for all lights
						// (should be possible to cache even more)

						computePixelNormal( normalVector, localPoint, material.shading, face, vertices );
						normalVector.applyMatrix3( _object.normalMatrix ).normalize();

						normalComputed = true;

					}

					// compute attenuation

					var attenuation = 1.0;

					if ( light.physicalAttenuation === true ) {

						attenuation = lightVector.length();
						attenuation = 1.0 / ( attenuation * attenuation );

					}

					lightVector.normalize();

					// compute diffuse

					var dot = Math.max( normalVector.dot( lightVector ), 0 );
					var diffuseIntensity = dot * light.intensity;

					lightContribution.copy( diffuseColor );
					lightContribution.multiply( lightColor );
					lightContribution.multiplyScalar( diffuseIntensity * attenuation );

					outputColor.add( lightContribution );

					// compute specular

					if ( material instanceof THREE.MeshPhongMaterial ) {

						halfVector.addVectors( lightVector, eyeVector ).normalize();

						var dotNormalHalf = Math.max( normalVector.dot( halfVector ), 0.0 );
						var specularIntensity = Math.max( Math.pow( dotNormalHalf, material.shininess ), 0.0 ) * diffuseIntensity;

						var specularNormalization = ( material.shininess + 2.0 ) / 8.0;

						specularColor.copyGammaToLinear( material.specular );

						var alpha = Math.pow( Math.max( 1.0 - lightVector.dot( halfVector ), 0.0 ), 5.0 );

						schlick.r = specularColor.r + ( 1.0 - specularColor.r ) * alpha;
						schlick.g = specularColor.g + ( 1.0 - specularColor.g ) * alpha;
						schlick.b = specularColor.b + ( 1.0 - specularColor.b ) * alpha;

						lightContribution.copy( schlick );

						lightContribution.multiply( lightColor );
						lightContribution.multiplyScalar( specularNormalization * specularIntensity * attenuation );
						outputColor.add( lightContribution );

					}

				}

			}

			// reflection / refraction

			var reflectivity = material.reflectivity;

			if ( ( material.mirror || material.glass ) && reflectivity > 0 && recursionDepth < maxRecursionDepth ) {

				if ( material.mirror ) {

					reflectionVector.copy( rayDirection );
					reflectionVector.reflect( normalVector );

				} else if ( material.glass ) {

					var eta = material.refractionRatio;

					var dotNI = rayDirection.dot( normalVector )
					var k = 1.0 - eta * eta * ( 1.0 - dotNI * dotNI );

					if ( k < 0.0 ) {

						reflectionVector.set( 0, 0, 0 );

					} else {

						reflectionVector.copy( rayDirection );
						reflectionVector.multiplyScalar( eta );

						var alpha = eta * dotNI + Math.sqrt( k );
						tmpVec.copy( normalVector );
						tmpVec.multiplyScalar( alpha );
						reflectionVector.sub( tmpVec );

					}

				}

				var theta = Math.max( eyeVector.dot( normalVector ), 0.0 );
				var rf0 = reflectivity;
				var fresnel = rf0 + ( 1.0 - rf0 ) * Math.pow( ( 1.0 - theta ), 5.0 );

				var weight = fresnel;

				var zColor = tmpColor[ recursionDepth ];

				spawnRay( point, reflectionVector, zColor, recursionDepth + 1 );

				if ( material.specular !== undefined ) {

					zColor.multiply( material.specular );

				}

				zColor.multiplyScalar( weight );
				outputColor.multiplyScalar( 1 - weight );
				outputColor.add( zColor );

			}

		};

	}() );

	var computePixelNormal = ( function () {

		var tmpVec1 = new THREE.Vector3();
		var tmpVec2 = new THREE.Vector3();
		var tmpVec3 = new THREE.Vector3();

		return function ( outputVector, point, shading, face, vertices ) {

			var faceNormal = face.normal;
			var vertexNormals = face.vertexNormals;

			if ( shading === THREE.FlatShading ) {

				outputVector.copy( faceNormal );

			} else if ( shading === THREE.SmoothShading ) {

				// compute barycentric coordinates

				var vA = vertices[ face.a ];
				var vB = vertices[ face.b ];
				var vC = vertices[ face.c ];

				tmpVec3.crossVectors( tmpVec1.subVectors( vB, vA ), tmpVec2.subVectors( vC, vA ) );
				var areaABC = faceNormal.dot( tmpVec3 );

				tmpVec3.crossVectors( tmpVec1.subVectors( vB, point ), tmpVec2.subVectors( vC, point ) );
				var areaPBC = faceNormal.dot( tmpVec3 );
				var a = areaPBC / areaABC;

				tmpVec3.crossVectors( tmpVec1.subVectors( vC, point ), tmpVec2.subVectors( vA, point ) );
				var areaPCA = faceNormal.dot( tmpVec3 );
				var b = areaPCA / areaABC;

				var c = 1.0 - a - b;

				// compute interpolated vertex normal

				tmpVec1.copy( vertexNormals[ 0 ] );
				tmpVec1.multiplyScalar( a );

				tmpVec2.copy( vertexNormals[ 1 ] );
				tmpVec2.multiplyScalar( b );

				tmpVec3.copy( vertexNormals[ 2 ] );
				tmpVec3.multiplyScalar( c );

				outputVector.addVectors( tmpVec1, tmpVec2 );
				outputVector.add( tmpVec3 );

			}

		};

	}() );

	var renderBlock = ( function () {

		var blockSize = 64;

		var canvasBlock = document.createElement( 'canvas' );
		canvasBlock.width = blockSize;
		canvasBlock.height = blockSize;

		var contextBlock = canvasBlock.getContext( '2d', {

			alpha: parameters.alpha === true

		} );

		var imagedata = contextBlock.getImageData( 0, 0, blockSize, blockSize );
		var data = imagedata.data;

		var pixelColor = new THREE.Color();

		return function ( blockX, blockY ) {

			var index = 0;

			for ( var y = 0; y < blockSize; y ++ ) {

				for ( var x = 0; x < blockSize; x ++, index += 4 ) {

					// spawn primary ray at pixel position

					origin.copy( cameraPosition );

					direction.set( x + blockX - canvasWidthHalf, - ( y + blockY - canvasHeightHalf ), - perspective );
					direction.applyMatrix3( cameraNormalMatrix ).normalize();

					spawnRay( origin, direction, pixelColor, 0 );

					// convert from linear to gamma

					data[ index ]     = Math.sqrt( pixelColor.r ) * 255;
					data[ index + 1 ] = Math.sqrt( pixelColor.g ) * 255;
					data[ index + 2 ] = Math.sqrt( pixelColor.b ) * 255;

				}

			}

			context.putImageData( imagedata, blockX, blockY );

			blockX += blockSize;

			if ( blockX >= canvasWidth ) {

				blockX = 0;
				blockY += blockSize;

				if ( blockY >= canvasHeight ) return;

			}

			context.fillRect( blockX, blockY, blockSize, blockSize );

			animationFrameId = requestAnimationFrame( function () {

				renderBlock( blockX, blockY );

			} );

		};

	}() );

	this.render = function ( scene, camera ) {

		if ( this.autoClear === true ) this.clear();

		cancelAnimationFrame( animationFrameId );

		// update scene graph

		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();

		// update camera matrices

		if ( camera.parent === undefined ) camera.updateMatrixWorld();

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );
		cameraPosition.setFromMatrixPosition( camera.matrixWorld );

		//

		cameraNormalMatrix.getNormalMatrix( camera.matrixWorld );
		origin.copy( cameraPosition );

		perspective = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * canvasHeight;

		objects = scene.children;

		// collect lights and set up object matrices

		lights.length = 0;

		scene.traverse( function ( object ) {

			if ( object instanceof THREE.Light ) {

				lights.push( object );

			}

			if ( cache[ object.id ] === undefined ) {

				cache[ object.id ] = {
					normalMatrix: new THREE.Matrix3(),
					inverseMatrix: new THREE.Matrix4()
				};

			}

			modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld )

			var _object = cache[ object.id ];

			_object.normalMatrix.getNormalMatrix( modelViewMatrix );
			_object.inverseMatrix.getInverse( object.matrixWorld );

		} );

		renderBlock( 0, 0 );

	};

};


text:
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ReplicationVaultHealthOperations operations.
    /// </summary>
    internal partial class ReplicationVaultHealthOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationVaultHealthOperations
    {
        /// <summary>
        /// Initializes a new instance of the ReplicationVaultHealthOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        internal ReplicationVaultHealthOperations(SiteRecoveryManagementClient client)
        {
            if (client == null)
            {
                throw new System.ArgumentNullException("client");
            }
            Client = client;
        }

        /// <summary>
        /// Gets a reference to the SiteRecoveryManagementClient
        /// </summary>
        public SiteRecoveryManagementClient Client { get; private set; }

        /// <summary>
        /// Gets the health summary for the vault.
        /// </summary>
        /// <remarks>
        /// Gets the health details of the vault.
        /// </remarks>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<VaultHealthDetails>> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.ResourceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
            }
            if (Client.ResourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultHealth").ToString();
            _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List<string> _queryParameters = new List<string>();
            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }

            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    CloudError _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<VaultHealthDetails>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VaultHealthDetails>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Refreshes health summary of the vault.
        /// </summary>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task<AzureOperationResponse<VaultHealthDetails>> RefreshWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send request
            AzureOperationResponse<VaultHealthDetails> _response = await BeginRefreshWithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false);
            return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Refreshes health summary of the vault.
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<VaultHealthDetails>> BeginRefreshWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.ResourceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
            }
            if (Client.ResourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginRefresh", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultHealth/default/refresh").ToString();
            _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List<string> _queryParameters = new List<string>();
            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }

            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    CloudError _errorBody =  Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<VaultHealthDetails>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VaultHealthDetails>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.test.implementation;

/**
 * Model class containing the metrics about a test run.
 */
public final class TestRunMetrics {
    private final String logPrefix;
    private final long startMillis;

    public TestRunMetrics(String logPrefix, long startMillis) {
        this.logPrefix = logPrefix;
        this.startMillis = startMillis;
    }

    public String getLogPrefix() {
        return logPrefix;
    }

    public long getStartMillis() {
        return startMillis;
    }
}


text:
module Azure::CDN::Mgmt::V2020_09_01
  module Models
    #
    # Model object.
    #
    #
    class ResourcesResponseEndpointsItem

      include MsRestAzure

      # @return [String]
      attr_accessor :id

      # @return [String]
      attr_accessor :name

      # @return [Boolean]
      attr_accessor :history

      # @return [Array<ResourcesResponseEndpointsItemCustomDomainsItem>]
      attr_accessor :custom_domains

      #
      # Mapper for ResourcesResponseEndpointsItem class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ResourcesResponse_endpointsItem',
          type: {
            name: 'Composite',
            class_name: 'ResourcesResponseEndpointsItem',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              history: {
                client_side_validation: true,
                required: false,
                serialized_name: 'history',
                type: {
                  name: 'Boolean'
                }
              },
              custom_domains: {
                client_side_validation: true,
                required: false,
                serialized_name: 'customDomains',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ResourcesResponseEndpointsItemCustomDomainsItemElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ResourcesResponseEndpointsItemCustomDomainsItem'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php
/**
 * Auto generated from PB_gm_tool.proto at 2018-01-24 16:26:41
 *
 * protos package
 */

namespace Protos {
/**
 * fish_card_rate_t message embedded in game_numerical message
 */
class game_numerical_fish_card_rate_t extends \ProtobufMessage
{
    /* Field index constants */
    const FC_MAX = 1;
    const RATE = 2;

    /* @var array Field descriptors */
    protected static $fields = array(
        self::FC_MAX => array(
            'name' => 'fc_max',
            'required' => true,
            'type' => \ProtobufMessage::PB_TYPE_INT,
        ),
        self::RATE => array(
            'name' => 'rate',
            'required' => true,
            'type' => \ProtobufMessage::PB_TYPE_FLOAT,
        ),
    );

    /**
     * Constructs new message container and clears its internal state
     */
    public function __construct()
    {
        $this->reset();
    }

    /**
     * Clears message values and sets default ones
     *
     * @return null
     */
    public function reset()
    {
        $this->values[self::FC_MAX] = null;
        $this->values[self::RATE] = null;
    }

    /**
     * Returns field descriptors
     *
     * @return array
     */
    public function fields()
    {
        return self::$fields;
    }

    /**
     * Sets value of 'fc_max' property
     *
     * @param integer $value Property value
     *
     * @return null
     */
    public function setFcMax($value)
    {
        return $this->set(self::FC_MAX, $value);
    }

    /**
     * Returns value of 'fc_max' property
     *
     * @return integer
     */
    public function getFcMax()
    {
        $value = $this->get(self::FC_MAX);
        return $value === null ? (integer)$value : $value;
    }

    /**
     * Sets value of 'rate' property
     *
     * @param double $value Property value
     *
     * @return null
     */
    public function setRate($value)
    {
        return $this->set(self::RATE, $value);
    }

    /**
     * Returns value of 'rate' property
     *
     * @return double
     */
    public function getRate()
    {
        $value = $this->get(self::RATE);
        return $value === null ? (double)$value : $value;
    }
}
}


text:
#ifndef	_MACHINE_WATCH_H_
#define	_MACHINE_WATCH_H_

int	watch_phys_set_mask(vm_paddr_t pa, u_long mask);
int	watch_phys_set(vm_paddr_t pa, int sz);
vm_paddr_t	watch_phys_get(int *bm);
void	watch_phys_clear(void);
int	watch_phys_active(void);
int	watch_virt_set_mask(vm_offset_t va, u_long mask);
int	watch_virt_set(vm_offset_t va, int sz);
vm_offset_t	watch_virt_get(int *bm);
void	watch_virt_clear(void);
int	watch_virt_active(void);

#endif	/* _MACHINE_WATCH_H_ */


text:
package com.hubspot.jinjava.el.ext.eager;

import com.hubspot.jinjava.el.ext.AstNamedParameter;
import com.hubspot.jinjava.el.ext.DeferredParsingException;
import de.odysseus.el.tree.Bindings;
import de.odysseus.el.tree.impl.ast.AstIdentifier;
import de.odysseus.el.tree.impl.ast.AstNode;
import javax.el.ELContext;

public class EagerAstNamedParameter
  extends AstNamedParameter
  implements EvalResultHolder {
  protected boolean hasEvalResult;
  protected Object evalResult;
  protected final AstIdentifier name;
  protected final EvalResultHolder value;

  public EagerAstNamedParameter(AstIdentifier name, AstNode value) {
    this(name, EagerAstNodeDecorator.getAsEvalResultHolder(value));
  }

  private EagerAstNamedParameter(AstIdentifier name, EvalResultHolder value) {
    super(name, (AstNode) value);
    this.name = name;
    this.value = value;
  }

  @Override
  public Object eval(Bindings bindings, ELContext context) {
    return EvalResultHolder.super.eval(
      () -> super.eval(bindings, context),
      bindings,
      context
    );
  }

  @Override
  public String getPartiallyResolved(
    Bindings bindings,
    ELContext context,
    DeferredParsingException deferredParsingException,
    boolean preserveIdentifier
  ) {
    return String.format(
      "%s=%s",
      name,
      EvalResultHolder.reconstructNode(
        bindings,
        context,
        value,
        deferredParsingException,
        false
      )
    );
  }

  @Override
  public Object getEvalResult() {
    return evalResult;
  }

  @Override
  public void setEvalResult(Object evalResult) {
    this.evalResult = evalResult;
    hasEvalResult = true;
  }

  @Override
  public boolean hasEvalResult() {
    return hasEvalResult;
  }
}


text:
package org.jtheque.films.view.impl.panels;

import org.jtheque.core.managers.error.JThequeError;
import org.jtheque.core.managers.view.impl.components.panel.FileChooserPanel;
import org.jtheque.core.utils.ui.builders.JThequePanelBuilder;
import org.jtheque.core.utils.ui.builders.PanelBuilder;
import org.jtheque.core.utils.ui.constraints.ConstraintManager;
import org.jtheque.films.persistence.od.able.Film;
import org.jtheque.films.utils.Constants.Properties;
import org.jtheque.films.view.able.IInfosOthersView;
import org.jtheque.films.view.impl.fb.IFilmFormBean;
import org.jtheque.primary.view.impl.listeners.ObjectChangedEvent;
import org.jtheque.utils.ui.GridBagUtils;

import javax.annotation.PostConstruct;
import javax.swing.JComponent;
import javax.swing.JPanel;

import java.util.Collection;

/**
 * Panel for the others informations about film.
 *
 * @author Baptiste Wicht
 */
public final class JPanelInfosOthers extends JPanel implements IInfosOthersView {
    private FileChooserPanel fieldFile;

    /**
     * Build the view.
     */
    @PostConstruct
    private void build() {
        PanelBuilder builder = new JThequePanelBuilder(this);

        fieldFile = new FileChooserPanel();
        fieldFile.setTextKey(Properties.Film.FILE_PATH);

        builder.add(fieldFile, builder.gbcSet(0, 0, GridBagUtils.BOTH, GridBagUtils.ABOVE_BASELINE_LEADING, 0, 0, 1.0, 1.0));
    }

    @Override
    public void objectChanged(ObjectChangedEvent event) {
        Film film = (Film) event.getObject();

        fieldFile.setFilePath(film.getFilePath());
    }

    /**
     * Fill the form bean.
     *
     * @param fb The form bean to fill.
     */
    @Override
    public void fillFilm(IFilmFormBean fb) {
        fb.setFilePath(fieldFile.getFilePath());
    }

    @Override
    public void setEnabled(boolean enabled) {
        fieldFile.setEnabled(enabled);

        super.setEnabled(enabled);
    }

    /**
     * Validate the view.
     *
     * @param errors The errors list to fill.
     */
    @Override
    public void validate(Collection<JThequeError> errors) {
        ConstraintManager.validate(Properties.Film.FILE_PATH, fieldFile.getFilePath(), errors);
    }

    @Override
    public JComponent getImpl() {
        return this;
    }
}


text:
#include <boringssl/bssl.h>
/* crypto/x509/x509_d2.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.] */

#include <boringssl/err.h>
#include <boringssl/x509.h>

#ifndef OPENSSL_NO_STDIO
int X509_STORE_set_default_paths(X509_STORE *ctx)
{
    X509_LOOKUP *lookup;

    lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file());
    if (lookup == NULL)
        return (0);
    X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);

    lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir());
    if (lookup == NULL)
        return (0);
    X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

    /* clear any errors */
    ERR_clear_error();

    return (1);
}

int X509_STORE_load_locations(X509_STORE *ctx, const char *file,
                              const char *path)
{
    X509_LOOKUP *lookup;

    if (file != NULL) {
        lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file());
        if (lookup == NULL)
            return (0);
        if (X509_LOOKUP_load_file(lookup, file, X509_FILETYPE_PEM) != 1)
            return (0);
    }
    if (path != NULL) {
        lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir());
        if (lookup == NULL)
            return (0);
        if (X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) != 1)
            return (0);
    }
    if ((path == NULL) && (file == NULL))
        return (0);
    return (1);
}

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/EventSockets.iml" filepath="$PROJECT_DIR$/EventSockets.iml" />
    </modules>
  </component>
</project>


text:
using std::string;
using std::vector;

namespace chromeos_update_engine {

const uint32_t kSignatureMessageCurrentVersion = 2;

namespace {

// The following is a standard PKCS1-v1_5 padding for SHA256 signatures, as
// defined in RFC3447. It is prepended to the actual signature (32 bytes) to
// form a sequence of 256 bytes (2048 bits) that is amenable to RSA signing. The
// padded hash will look as follows:
//
//    0x00 0x01 0xff ... 0xff 0x00  ASN1HEADER  SHA256HASH
//   |--------------205-----------||----19----||----32----|
//
// where ASN1HEADER is the ASN.1 description of the signed data. The complete 51
// bytes of actual data (i.e. the ASN.1 header complete with the hash) are
// packed as follows:
//
//  SEQUENCE(2+49) {
//   SEQUENCE(2+13) {
//    OBJECT(2+9) id-sha256
//    NULL(2+0)
//   }
//   OCTET STRING(2+32) <actual signature bytes...>
//  }
const unsigned char kRSA2048SHA256Padding[] = {
  // PKCS1-v1_5 padding
  0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  0xff, 0xff, 0xff, 0xff, 0x00,
  // ASN.1 header
  0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
  0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
  0x00, 0x04, 0x20,
};

// Given raw |signatures|, packs them into a protobuf and serializes it into a
// binary blob. Returns true on success, false otherwise.
bool ConvertSignatureToProtobufBlob(const vector<vector<char> >& signatures,
                                    vector<char>* out_signature_blob) {
  // Pack it into a protobuf
  Signatures out_message;
  uint32_t version = kSignatureMessageCurrentVersion + 1 - signatures.size();
  for (const vector<char>& signature : signatures) {
    Signatures_Signature* sig_message = out_message.add_signatures();
    sig_message->set_version(version++);
    sig_message->set_data(signature.data(), signature.size());
  }

  // Serialize protobuf
  string serialized;
  TEST_AND_RETURN_FALSE(out_message.AppendToString(&serialized));
  out_signature_blob->insert(out_signature_blob->end(),
                             serialized.begin(),
                             serialized.end());
  LOG(INFO) << "Signature blob size: " << out_signature_blob->size();
  return true;
}

// Given an unsigned payload under |payload_path| and the |signature_blob_size|
// generates an updated payload that includes a dummy signature op in its
// manifest. It populates |out_metadata_size| with the size of the final
// manifest after adding the dummy signature operation.  Returns true on
// success, false otherwise.
bool AddSignatureOpToPayload(const string& payload_path,
                             int signature_blob_size,
                             vector<char>* out_payload,
                             uint64_t* out_metadata_size) {
  const int kProtobufOffset = 20;
  const int kProtobufSizeOffset = 12;

  // Loads the payload.
  vector<char> payload;
  DeltaArchiveManifest manifest;
  uint64_t metadata_size;
  TEST_AND_RETURN_FALSE(PayloadSigner::LoadPayload(
      payload_path, &payload, &manifest, &metadata_size));
  TEST_AND_RETURN_FALSE(!manifest.has_signatures_offset() &&
                        !manifest.has_signatures_size());

  // Updates the manifest to include the signature operation.
  DeltaDiffGenerator::AddSignatureOp(payload.size() - metadata_size,
                                     signature_blob_size,
                                     manifest);

  // Updates the payload to include the new manifest.
  string serialized_manifest;
  TEST_AND_RETURN_FALSE(manifest.AppendToString(&serialized_manifest));
  LOG(INFO) << "Updated protobuf size: " << serialized_manifest.size();
  payload.erase(payload.begin() + kProtobufOffset,
                payload.begin() + metadata_size);
  payload.insert(payload.begin() + kProtobufOffset,
                 serialized_manifest.begin(),
                 serialized_manifest.end());

  // Updates the protobuf size.
  uint64_t size_be = htobe64(serialized_manifest.size());
  memcpy(&payload[kProtobufSizeOffset], &size_be, sizeof(size_be));
  LOG(INFO) << "Updated payload size: " << payload.size();
  out_payload->swap(payload);
  *out_metadata_size = serialized_manifest.size() + kProtobufOffset;
  return true;
}
}  // namespace {}

bool PayloadSigner::LoadPayload(const string& payload_path,
                 vector<char>* out_payload,
                 DeltaArchiveManifest* out_manifest,
                 uint64_t* out_metadata_size) {
  vector<char> payload;
  // Loads the payload and parses the manifest.
  TEST_AND_RETURN_FALSE(utils::ReadFile(payload_path, &payload));
  LOG(INFO) << "Payload size: " << payload.size();
  ActionExitCode error = kActionCodeSuccess;
  InstallPlan install_plan;
  DeltaPerformer delta_performer(NULL, NULL, &install_plan);
  TEST_AND_RETURN_FALSE(delta_performer.ParsePayloadMetadata(
      payload, out_manifest, out_metadata_size, &error) ==
                        DeltaPerformer::kMetadataParseSuccess);
  LOG(INFO) << "Metadata size: " << *out_metadata_size;
  out_payload->swap(payload);
  return true;
}

bool PayloadSigner::SignHash(const vector<char>& hash,
                             const string& private_key_path,
                             vector<char>* out_signature) {
  LOG(INFO) << "Signing hash with private key: " << private_key_path;
  string sig_path;
  TEST_AND_RETURN_FALSE(
      utils::MakeTempFile("/tmp/signature.XXXXXX", &sig_path, NULL));
  ScopedPathUnlinker sig_path_unlinker(sig_path);

  string hash_path;
  TEST_AND_RETURN_FALSE(
      utils::MakeTempFile("/tmp/hash.XXXXXX", &hash_path, NULL));
  ScopedPathUnlinker hash_path_unlinker(hash_path);
  // We expect unpadded SHA256 hash coming in
  TEST_AND_RETURN_FALSE(hash.size() == 32);
  vector<char> padded_hash(hash);
  PadRSA2048SHA256Hash(&padded_hash);
  TEST_AND_RETURN_FALSE(utils::WriteFile(hash_path.c_str(),
                                         padded_hash.data(),
                                         padded_hash.size()));

  // This runs on the server, so it's okay to cop out and call openssl
  // executable rather than properly use the library
  vector<string> cmd;
  base::SplitString("openssl rsautl -raw -sign -inkey x -in x -out x",
                    ' ',
                    &cmd);
  cmd[cmd.size() - 5] = private_key_path;
  cmd[cmd.size() - 3] = hash_path;
  cmd[cmd.size() - 1] = sig_path;

  int return_code = 0;
  TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code, NULL));
  TEST_AND_RETURN_FALSE(return_code == 0);

  vector<char> signature;
  TEST_AND_RETURN_FALSE(utils::ReadFile(sig_path, &signature));
  out_signature->swap(signature);
  return true;
}

bool PayloadSigner::SignPayload(const string& unsigned_payload_path,
                                const vector<string>& private_key_paths,
                                vector<char>* out_signature_blob) {
  vector<char> hash_data;
  TEST_AND_RETURN_FALSE(OmahaHashCalculator::RawHashOfFile(
      unsigned_payload_path, -1, &hash_data) ==
                        utils::FileSize(unsigned_payload_path));

  vector<vector<char> > signatures;
  for (const string& path : private_key_paths) {
    vector<char> signature;
    TEST_AND_RETURN_FALSE(SignHash(hash_data, path, &signature));
    signatures.push_back(signature);
  }
  TEST_AND_RETURN_FALSE(ConvertSignatureToProtobufBlob(signatures,
                                                       out_signature_blob));
  return true;
}

bool PayloadSigner::SignatureBlobLength(const vector<string>& private_key_paths,
                                        uint64_t* out_length) {
  DCHECK(out_length);

  string x_path;
  TEST_AND_RETURN_FALSE(
      utils::MakeTempFile("/tmp/signed_data.XXXXXX", &x_path, NULL));
  ScopedPathUnlinker x_path_unlinker(x_path);
  TEST_AND_RETURN_FALSE(utils::WriteFile(x_path.c_str(), "x", 1));

  vector<char> sig_blob;
  TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(x_path,
                                                   private_key_paths,
                                                   &sig_blob));
  *out_length = sig_blob.size();
  return true;
}

bool PayloadSigner::VerifySignature(const std::vector<char>& signature_blob,
                                    const std::string& public_key_path,
                                    std::vector<char>* out_hash_data) {
  return VerifySignatureBlob(signature_blob, public_key_path,
                                kSignatureMessageCurrentVersion, out_hash_data);
}

bool PayloadSigner::VerifySignatureBlob(
    const std::vector<char>& signature_blob,
    const std::string& public_key_path,
    uint32_t client_version,
    std::vector<char>* out_hash_data) {
  TEST_AND_RETURN_FALSE(!public_key_path.empty());

  Signatures signatures;
  LOG(INFO) << "signature size = " <<  signature_blob.size();
  TEST_AND_RETURN_FALSE(signatures.ParseFromArray(&signature_blob[0],
                                                  signature_blob.size()));

  // Finds a signature that matches the current version.
  int sig_index = 0;
  for (; sig_index < signatures.signatures_size(); sig_index++) {
    const Signatures_Signature& signature = signatures.signatures(sig_index);
    if (signature.has_version() &&
        signature.version() == client_version) {
      break;
    }
  }
  TEST_AND_RETURN_FALSE(sig_index < signatures.signatures_size());

  const Signatures_Signature& signature = signatures.signatures(sig_index);
  vector<char> sig_data(signature.data().begin(), signature.data().end());

  return GetRawHashFromSignature(sig_data, public_key_path, out_hash_data);
}

bool PayloadSigner::GetRawHashFromSignature(
    const std::vector<char>& sig_data,
    const std::string& public_key_path,
    std::vector<char>* out_hash_data) {
  TEST_AND_RETURN_FALSE(!public_key_path.empty());

  // The code below executes the equivalent of:
  //
  // openssl rsautl -verify -pubin -inkey |public_key_path|
  //   -in |sig_data| -out |out_hash_data|

  // Loads the public key.
  FILE* fpubkey = fopen(public_key_path.c_str(), "rb");
  if (!fpubkey) {
    LOG(ERROR) << "Unable to open public key file: " << public_key_path;
    return false;
  }

  char dummy_password[] = { ' ', 0 };  // Ensure no password is read from stdin.
  RSA* rsa = PEM_read_RSA_PUBKEY(fpubkey, NULL, NULL, dummy_password);
  fclose(fpubkey);
  TEST_AND_RETURN_FALSE(rsa != NULL);
  unsigned int keysize = RSA_size(rsa);
  if (sig_data.size() > 2 * keysize) {
    LOG(ERROR) << "Signature size is too big for public key size.";
    RSA_free(rsa);
    return false;
  }

  // Decrypts the signature.
  vector<char> hash_data(keysize);
  int decrypt_size = RSA_public_decrypt(
      sig_data.size(),
      reinterpret_cast<const unsigned char*>(sig_data.data()),
      reinterpret_cast<unsigned char*>(hash_data.data()),
      rsa,
      RSA_NO_PADDING);
  RSA_free(rsa);
  TEST_AND_RETURN_FALSE(decrypt_size > 0 &&
                        decrypt_size <= static_cast<int>(hash_data.size()));
  hash_data.resize(decrypt_size);
  out_hash_data->swap(hash_data);
  return true;
}

bool PayloadSigner::VerifySignedPayload(const std::string& payload_path,
                                        const std::string& public_key_path,
                                        uint32_t client_key_check_version) {
  vector<char> payload;
  DeltaArchiveManifest manifest;
  uint64_t metadata_size;
  TEST_AND_RETURN_FALSE(LoadPayload(
      payload_path, &payload, &manifest, &metadata_size));
  TEST_AND_RETURN_FALSE(manifest.has_signatures_offset() &&
                        manifest.has_signatures_size());
  CHECK_EQ(payload.size(),
           metadata_size + manifest.signatures_offset() +
           manifest.signatures_size());
  vector<char> signature_blob(
      payload.begin() + metadata_size + manifest.signatures_offset(),
      payload.end());
  vector<char> signed_hash;
  TEST_AND_RETURN_FALSE(VerifySignatureBlob(
      signature_blob, public_key_path, client_key_check_version, &signed_hash));
  TEST_AND_RETURN_FALSE(!signed_hash.empty());
  vector<char> hash;
  TEST_AND_RETURN_FALSE(OmahaHashCalculator::RawHashOfBytes(
      payload.data(), metadata_size + manifest.signatures_offset(), &hash));
  PadRSA2048SHA256Hash(&hash);
  TEST_AND_RETURN_FALSE(hash == signed_hash);
  return true;
}

bool PayloadSigner::HashPayloadForSigning(const string& payload_path,
                                          const vector<int>& signature_sizes,
                                          vector<char>* out_hash_data) {
  // TODO(petkov): Reduce memory usage -- the payload is manipulated in memory.

  // Loads the payload and adds the signature op to it.
  vector<vector<char> > signatures;
  for (int signature_size : signature_sizes) {
    signatures.emplace_back(signature_size, 0);
  }
  vector<char> signature_blob;
  TEST_AND_RETURN_FALSE(ConvertSignatureToProtobufBlob(signatures,
                                                       &signature_blob));
  vector<char> payload;
  uint64_t final_metadata_size;
  TEST_AND_RETURN_FALSE(AddSignatureOpToPayload(payload_path,
                                                signature_blob.size(),
                                                &payload,
                                                &final_metadata_size));
  // Calculates the hash on the updated payload. Note that the payload includes
  // the signature op but doesn't include the signature blob at the end.
  TEST_AND_RETURN_FALSE(OmahaHashCalculator::RawHashOfData(payload,
                                                           out_hash_data));
  return true;
}

bool PayloadSigner::HashMetadataForSigning(const string& payload_path,
                                           vector<char>* out_metadata_hash) {
  // Extract the manifest first.
  vector<char> payload;
  DeltaArchiveManifest manifest_proto;
  uint64_t metadata_size;
  TEST_AND_RETURN_FALSE(LoadPayload(
      payload_path, &payload, &manifest_proto, &metadata_size));

  // Calculates the hash on the manifest.
  TEST_AND_RETURN_FALSE(OmahaHashCalculator::RawHashOfBytes(&payload[0],
                                                            metadata_size,
                                                            out_metadata_hash));
  return true;
}

bool PayloadSigner::AddSignatureToPayload(
    const string& payload_path,
    const vector<vector<char> >& signatures,
    const string& signed_payload_path,
    uint64_t *out_metadata_size) {
  // TODO(petkov): Reduce memory usage -- the payload is manipulated in memory.

  // Loads the payload and adds the signature op to it.
  vector<char> signature_blob;
  TEST_AND_RETURN_FALSE(ConvertSignatureToProtobufBlob(signatures,
                                                       &signature_blob));
  vector<char> payload;
  TEST_AND_RETURN_FALSE(AddSignatureOpToPayload(payload_path,
                                                signature_blob.size(),
                                                &payload,
                                                out_metadata_size));
  // Appends the signature blob to the end of the payload and writes the new
  // payload.
  payload.insert(payload.end(), signature_blob.begin(), signature_blob.end());
  LOG(INFO) << "Signed payload size: " << payload.size();
  TEST_AND_RETURN_FALSE(utils::WriteFile(signed_payload_path.c_str(),
                                         payload.data(),
                                         payload.size()));
  return true;
}

bool PayloadSigner::PadRSA2048SHA256Hash(std::vector<char>* hash) {
  TEST_AND_RETURN_FALSE(hash->size() == 32);
  hash->insert(hash->begin(),
               reinterpret_cast<const char*>(kRSA2048SHA256Padding),
               reinterpret_cast<const char*>(kRSA2048SHA256Padding +
                                             sizeof(kRSA2048SHA256Padding)));
  TEST_AND_RETURN_FALSE(hash->size() == 256);
  return true;
}

}  // namespace chromeos_update_engine


text:
from django.apps import AppConfig

class MusicappConfig(AppConfig):
    name = 'MusicApp'


text:
(function($) {

var $body = $('body')
	// Make floaty labels
	.floatLabels({
		wrapper: '.input'
	})
	;

	// Enable transitions
	setTimeout(function() {
		$body.removeClass('preload');
	}, 10);

// Example for ajaxed forms:
$('#show-form').bind('click', function(e) {
	e.preventDefault();
	var $this = $(this);
	var $parent = $this.parent();
	var $formtpl = $('#form-template');
	var $form = $($formtpl.html());

	// If your code is properly coded with labels and has the "filled" class already you wont
	// need to call floatLabels again.
	// $body.addClass('preload');
	// $form.floatLabels();
	// You could also do $body.floatLabels(); again as the plugin checks for duplicate event delegation.

	$this.remove();
	$parent.append($form);

	// $body.floatLabels();
	// Like that. But here'd you'd have to mess with more setTimeouts if you wanted to suppress
	// the transitions because browsers are funny about class adding/removing timing.

	// setTimeout(function() {
	// 	$body.removeClass('preload');
	// }, 10);
})
;

})(window.jQuery || window.Zepto || window.$);


text:
@implementation Comment

- (instancetype)init {
  return [self initWithUid:@"" andAuthor:@"" andText:@""];
}

- (instancetype)initWithUid:(NSString *)uid andAuthor:(NSString *)author andText:(NSString *)text {
  self = [super init];
  if (self) {
    self.uid = uid;
    self.author = author;
    self.text = text;
  }
  return self;
}

@end