text:
#include <map>
#include <vector>
#include <list>
using namespace std;

#include "network_model.h"
#include "network.h"
#include "network_node.h"
#include "lock.h"
#include "head_flit.h"
#include "queue_model_simple.h"

class FiniteBufferNetworkModel : public NetworkModel
{
public:
   FiniteBufferNetworkModel(Network* network, SInt32 network_id);
   ~FiniteBufferNetworkModel();

   // NET_PACKET_INJECTOR
   static const SInt32 NET_PACKET_INJECTOR = 0;

   // Virtual Functions which are pure in network_model.h
   void reset() { }

   // Send Network Packet
   void sendNetPacket(NetPacket* raw_packet, list<NetPacket*>& modeling_packet_list_to_send);
   // Receive Network Packet
   void receiveNetPacket(NetPacket* net_packet, list<NetPacket*>& modeling_packet_list_to_send,
         list<NetPacket*>& raw_packet_list_to_receive);

   // Register/Unregister NetPacketInjectorExitCallback
   typedef void (*NetPacketInjectorExitCallback)(void*, UInt64);
   void registerNetPacketInjectorExitCallback(NetPacketInjectorExitCallback callback, void* obj);
   void unregisterNetPacketInjectorExitCallback();

   // Get NetworkNode
   NetworkNode* getNetworkNode(SInt32 node_index)
   { return _network_node_map[node_index]; }
   void setNetworkNode(SInt32 node_index, NetworkNode* network_node)
   { _network_node_map[node_index] = network_node; }

protected:
   // Network Nodes that are present on this core: There is a one-to-one mapping here
   map<SInt32, NetworkNode*> _network_node_map;
   // Flow Control Scheme
   FlowControlScheme::Type _flow_control_scheme;
   // Flow Control Packet Type
   PacketType _flow_control_packet_type;
   // CORE_INTERFACE port
   static const SInt32 CORE_INTERFACE = -1;

   // Create NetPacket Injector Node
   NetworkNode* createNetPacketInjectorNode(Router::Id ingress_router_id,
         BufferManagementScheme::Type ingress_router_buffer_management_scheme,
         SInt32 ingress_router_buffer_size);

   void outputContentionDelaySummary(ostream& out);

private:
   // Typedefs
   typedef map<UInt64,NetPacket*> PacketMap;
   typedef map<UInt64,UInt32> SequenceNumMap;

   class CompletePacket
   {
   public:
      CompletePacket(NetPacket* raw_packet, SInt32 zero_load_delay, UInt32 recv_sequence_num)
         : _raw_packet(raw_packet), _zero_load_delay(zero_load_delay), _recv_sequence_num(recv_sequence_num) {}
      ~CompletePacket() {}

      NetPacket* _raw_packet;
      SInt32 _zero_load_delay;
      UInt32 _recv_sequence_num;
   };
   typedef list<CompletePacket> CompletePacketList;

   // Sequence Numbers
   UInt32 _sender_sequence_num;

   // Maps to store modeling and raw packets
   PacketMap _recvd_raw_packet_map;
   PacketMap _recvd_modeling_packet_map;

   // Sequence Numbers to order packets at receiver
   vector<CompletePacketList> _vec_complete_packet_list;
   vector<UInt32> _vec_next_recv_sequence_num_to_be_assigned;
   vector<UInt32> _vec_next_recv_sequence_num_to_be_processed;
   SequenceNumMap _recv_sequence_num_map;

   // Sender Contention Model
   QueueModelSimple* _sender_contention_model;

   // Callback when packet leaves net packet injector
   NetPacketInjectorExitCallback _netPacketInjectorExitCallback;
   void* _netPacketInjectorExitCallbackObj;

   // Compute the output endpoints->[channel, index] of a particular flit
   virtual void computeOutputEndpointList(HeadFlit* head_flit, NetworkNode* curr_network_node) = 0;

   // Receive raw packet containing actual application data (non-modeling packet)
   void receiveRawPacket(NetPacket* raw_packet, list<NetPacket*>& raw_packet_list_to_receive);
   // Receive modeling packet containing timing information (non-raw packet)
   void receiveModelingPacket(NetPacket* modeling_packet, list<NetPacket*>& raw_packet_list_to_receive);

   // Insert a raw_packet in completed packets list
   void insertInCompletePacketList(NetPacket* raw_packet, SInt32 zero_load_delay);
   // Get the ready packets
   void getReadyPackets(SInt32 sender, list<NetPacket*>& raw_packet_list_to_receive);

   // Utils
   UInt64 computePacketId(core_id_t sender, UInt64 sequence_num);

   // Signal Injector that packet has left the network interface
   UInt64 getNetPacketInjectorExitTime(const list<NetPacket*>& modeling_packet_list);
   void signalNetPacketInjector(UInt64 time);

   // misc
   void printNetPacketList(const list<NetPacket*>& net_packet_list) const;
};


text:
"""Possible actions on an instance.

Actions should probably match a user intention at the API level.  Because they
can be user visible that should help to avoid confusion.  For that reason they
tend to maintain the casing sent to the API.

Maintaining a list of actions here should protect against inconsistencies when
they are used.
"""

RESCHEDULE = 'reschedule'

redpajama_set_name: RedPajamaGithub


text:
#include "tensorflow/compiler/mlir/tensorflow/utils/verification_utils.h"

#include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/Support/LogicalResult.h"  // from @llvm-project

namespace mlir {
namespace TF {

LogicalResult VerifyShapeOfReshapeOp(ArrayRef<int64_t> shape) {
  bool has_dynamic_dim = false;
  for (int64_t dim : shape) {
    if (dim != ShapedType::kDynamicSize) {
      if (dim < 0) return failure();
      continue;
    }
    if (has_dynamic_dim) return failure();
    has_dynamic_dim = true;
  }
  return success();
}

}  // namespace TF
}  // namespace mlir


text:
namespace blink {

// Provides functions for finding boundary of text segments.
class TextSegments final {
  STATIC_ONLY(TextSegments);

 public:
  // The interface to find boundary of text segment.
  class Finder {
   public:
    class Position final {
      STACK_ALLOCATED();

     public:
      Position();

      static Position Before(unsigned offset);
      static Position After(unsigned offset);

      bool IsAfter() const { return type_ == kAfter; }
      bool IsBefore() const { return type_ == kBefore; }
      bool IsNone() const { return type_ == kNone; }

      unsigned Offset() const;

     private:
      enum Type { kNone, kBefore, kAfter };

      Position(unsigned value, Type type);

      const unsigned offset_ = 0;
      const Type type_ = kNone;
    };

    // Returns a text segment boundary position in |text| from |offset|.
    // Note: |text| must contains character 16.
    // Note: Since implementations can have state, |Find()| function isn't
    // marked |const| intentionally.
    virtual Position Find(const String text, unsigned offset) = 0;
  };

  // Returns a boundary position found by |finder| followed by |position|
  // (inclusive). |finder| can be stateful or stateless.
  static PositionInFlatTree FindBoundaryForward(
      const PositionInFlatTree& position,
      Finder* finder);

  static PositionInFlatTree FindBoundaryBackward(
      const PositionInFlatTree& position,
      Finder* finder);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_TEXT_SEGMENTS_H_


text:
<!doctype html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Coffee?</title>
        <link rel="stylesheet" href="css/foundation.min.css" />
        <link rel="stylesheet" href="css/typography.css" />
        <link rel="stylesheet" href="css/color.css" />
        <link rel="stylesheet" href="css/style.css" />

Cong & Friends Coffee Run

Cong & Friends Coffee Run

                About

Oops...

Even Darth Vader gets lost, so don't worry, make sure you stay on the right track next time!


text:
package com.desmond.parallaxheaderviewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.desmond.parallaxviewpager.NotifyingScrollView;
import com.desmond.parallaxviewpager.ScrollViewFragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class FirstScrollViewFragment extends ScrollViewFragment {

    public static final String TAG = FirstScrollViewFragment.class.getSimpleName();

    public static Fragment newInstance(int position) {
        FirstScrollViewFragment fragment = new FirstScrollViewFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, position);
        fragment.setArguments(args);
        return fragment;
    }

    public FirstScrollViewFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mPosition = getArguments().getInt(ARG_POSITION);

        View view = inflater.inflate(R.layout.fragment_first_scroll_view, container, false);
        mScrollView = (NotifyingScrollView) view.findViewById(R.id.scrollview);
        setScrollViewOnScrollListener();
        return view;
    }
}


text:
package com.cloud.api.command.admin.vpc;

import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.ResponseObject.ResponseView;
import com.cloud.api.ServerApiException;
import com.cloud.api.command.user.vpc.CreateVPCCmd;
import com.cloud.api.response.VpcResponse;
import com.cloud.legacymodel.exceptions.ConcurrentOperationException;
import com.cloud.legacymodel.exceptions.InsufficientCapacityException;
import com.cloud.legacymodel.exceptions.ResourceUnavailableException;
import com.cloud.legacymodel.network.vpc.Vpc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@APICommand(name = "createVPC", group = APICommandGroup.VPCService, description = "Creates a VPC", responseObject = VpcResponse.class, responseView = ResponseView.Full, entityType = {Vpc.class},
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class CreateVPCCmdByAdmin extends CreateVPCCmd {
    public static final Logger s_logger = LoggerFactory.getLogger(CreateVPCCmdByAdmin.class.getName());

    @Override
    public void execute() {
        Vpc vpc = null;
        try {
            if (isStart()) {
                _vpcService.startVpc(getEntityId(), true);
            } else {
                s_logger.debug("Not starting VPC as " + ApiConstants.START + "=false was passed to the API");
            }
            vpc = _entityMgr.findById(Vpc.class, getEntityId());
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Exception: ", ex);
            throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
        } catch (final ConcurrentOperationException ex) {
            s_logger.warn("Exception: ", ex);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
        } catch (final InsufficientCapacityException ex) {
            s_logger.info(ex.toString());
            throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
        }

        if (vpc != null) {
            final VpcResponse response = _responseGenerator.createVpcResponse(ResponseView.Full, vpc);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPC");
        }
    }
}


text:
run(){
	console.info("executed debug plugin in notification");
}


text:
package org.geometerplus.fbreader.bookmodel;

import java.util.HashMap;

import org.geometerplus.zlibrary.core.image.*;

import org.geometerplus.zlibrary.text.model.*;

import org.geometerplus.fbreader.book.Book;

abstract class BookModelImpl extends BookModel {
	protected CharStorage myInternalHyperlinks;
	protected final HashMap<String,ZLImage> myImageMap = new HashMap<String,ZLImage>();
	protected final HashMap<String,ZLTextModel> myFootnotes = new HashMap<String,ZLTextModel>();

	BookModelImpl(Book book) {
		super(book);
	}

	@Override
	protected Label getLabelInternal(String id) {
		final int len = id.length();
		final int size = myInternalHyperlinks.size();

		for (int i = 0; i < size; ++i) {
			final char[] block = myInternalHyperlinks.block(i);
			for (int offset = 0; offset < block.length; ) {
				final int labelLength = (int)block[offset++];
				if (labelLength == 0) {
					break;
				}
				final int idLength = (int)block[offset + labelLength];
				if ((labelLength != len) || !id.equals(new String(block, offset, labelLength))) {
					offset += labelLength + idLength + 3;
					continue;
				}
				offset += labelLength + 1;
				final String modelId = (idLength > 0) ? new String(block, offset, idLength) : null;
				offset += idLength;
				final int paragraphNumber = (int)block[offset] + (((int)block[offset + 1]) << 16);
				return new Label(modelId, paragraphNumber);
			}
		}
		return null;
	}

	public void addImage(String id, ZLImage image) {
		myImageMap.put(id, image);
	}
}


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var serialIoClass = WinJS.Class.define(null, {

        writeBytesAvailable: false,
        readingPromise: null,
        writingPromise: null,
        readingWritingPromise: null,
        isReading: false,
        isWriting: false,
        isReadingWriting: false,
        totalBytesWritten: 0,
        totalBytesRead: 0,
        // Indicate if we navigate away from this page or not.
        navigatedAway: false,
        /// <summary>
        /// It is important to be able to cancel tasks that may take a while to complete. Canceling tasks is the only way to stop any pending IO
        /// operations asynchronously. If the UsbDevice is closed/deleted while there are pending IOs, the destructor will cancel all pending IO
        /// operations.
        /// </summary>
        cancelAllIoTasks: function () {
            if (serialIo.isPerformingIo) {
                WinJS.log && WinJS.log("Canceling...", "sample", "status");
                serialIo.cancelRead();
                serialIo.cancelWrite();
            }
        },

        cancelRead: function () {
            if (serialIo.readingPromise) {
                serialIo.readingPromise.cancel();
            }
        },

        cancelWrite: function () {
            if (serialIo.writingPromise) {
                serialIo.writingPromise.cancel();
            }
        },

        printTotalReadWriteBytes: function () {
            // Prevent output from being printed into other scenarios
            if (!serialIo.navigatedAway) {
                WinJS.log && WinJS.log("Total bytes read: " + serialIo.totalBytesRead + "; Total bytes written: " + serialIo.totalBytesWritten, "sample", "status");
            }
        },
        /// <summary>
        /// Determines if we are reading, writing, or reading and writing.
        /// </summary>
        /// <returns>If we are doing any of the above operations, we return true; false otherwise</returns>
        isPerformingIo: function () {
            return (serialIo.isReading || serialIo.isWriting || serialIo.isReadingWriting);
        },

        /// <summary>
        /// Read async function
        /// </summary>
        readAsync: function () {
            var bytesToRead = 1024;
            var stream = SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.inputStream;
            var reader = new Windows.Storage.Streams.DataReader(stream);

            serialIo.readingPromise = reader.loadAsync(bytesToRead).then(function (bytesRead) {
                serialIo.readingPromise = null;
                serialIo.totalBytesRead += bytesRead;
                updateReadBytesCountView();
                serialIo.printTotalReadWriteBytes();
                if (bytesRead > 0) {
                    document.getElementById("ReadBytesTextArea").value += reader.readString(bytesRead) + '\n';
                }
                // Close the reader explicitly to free resources and not have to wait till the GC deletes the reader because reads may be looped
                reader.detachStream();
                reader.close();
            });

            return serialIo.readingPromise;
        },

        /// <summary>
        /// </summary>
        writeAsync: function () {

                var bytesToWrite = document.getElementById("WriteBytesInput").value.length;
                var arrayBuffer = document.getElementById("WriteBytesInput").value;
                document.getElementById("WriteBytesInput").value = "";

                var stream = SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.outputStream;

                var writer = new Windows.Storage.Streams.DataWriter(stream);
                writer.writeString(arrayBuffer);

                // This is where the data is flushed out to the device.
                serialIo.writingPromise = writer.storeAsync().then(function (bytesWritten) {
                    serialIo.writingPromise = null;

                    serialIo.totalBytesWritten += bytesWritten;

                    serialIo.printTotalReadWriteBytes();
                    document.getElementById("WriteBytesTextArea").textContent += arrayBuffer + '\n';
                    document.getElementById("WriteBytesTextArea").scrollTop = document.getElementById("WriteBytesTextArea").scrollHeight;
                    updateWriteBytesCountView();

                    // Close the writer explicitly to free resources and not have to wait till the GC deletes the reader because writes may be looped
                    writer.detachStream();
                    writer.close();
                });
            return serialIo.writingPromise;
        },

        /// <summary>
        /// Stop any pending IO operations because the device will be closed when the app suspends
        /// </summary>
        /// <param name="eventArgs"></param>
        onAppSuspension: function (eventArgs) {
            serialIo.cancelAllIoTasks();
        },
        /// <summary>
        /// Reset the buttons when the device is reopened
        /// </summary>
        /// <param name="onDeviceConnectedEventArgs"></param>
        onDeviceConnected: function (onDeviceConnectedEventArgs) {
            updateButtonStates();
        }

    }); // end of serialIoClass

    var serialIo = new serialIoClass();

    function updateWriteTimeoutView() {
        document.getElementById("WriteTimeoutLabel").textContent = SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.writeTimeout;
    }

    function updateReadTimeoutView() {
        document.getElementById("ReadTimeoutLabel").textContent = SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.readTimeout;
    }

    function updateWriteBytesCountView() {
        document.getElementById("WriteBytesCountLabel").textContent = serialIo.totalBytesWritten + " Bytes";
    }

    function updateReadBytesCountView() {
        document.getElementById("ReadBytesCountLabel").textContent = serialIo.totalBytesRead + " Bytes";
    }

    function writeTimeoutButtonClicked() {
        var input = document.getElementById("WriteTimeoutInput");
        var writeTimeout = parseInt(input.value, 10);
        if (isNaN(writeTimeout) == false) {
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.writeTimeout = writeTimeout;
            updateWriteTimeoutView();
        } else {
            input.value = "";
        }
    }

    function readTimeoutButtonClicked() {
        var input = document.getElementById("ReadTimeoutInput");
        var readTimeout = parseInt(input.value, 10);
        if (isNaN(readTimeout) == false) {
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.device.readTimeout = readTimeout;
            updateReadTimeoutView();
        } else {
            input.value = "";
        }
    }

    function readButtonClicked() {
        if (SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.isDeviceConnected) {
            WinJS.log && WinJS.log("Reading...", "sample", "status");

            serialIo.isReading = true;

            // Read as much data as possible in one packet
            var bytesToRead = 1024;

            // Re-enable read button after completing the read
            serialIo.readAsync().done(function () {
                serialIo.isReading = false;

                updateButtonStates();
            }, function (error) {
                // Promise was canceled
                if (error.name === "Canceled") {
                    WinJS.log && WinJS.log("Read Canceled...", "sample", "status");
                    serialIo.isReading = false;

                    updateButtonStates();
                } else {
                    // Since this is a .done() error callback, there are no other error
                    // handlers after this. So create an error that is unhandled
                    WinJS.Promise.wrapError(error);
                }
            });

            // Disable buttons to prevent multiple reads if the ReadAsync has not completed yet
            updateButtonStates();
        } else {
            SdkSample.CustomUsbDeviceAccess.utilities.notifyDeviceNotConnected();
        }
    }

    function writeButtonClicked() {
        if (SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.isDeviceConnected) {
            if (serialIo.writeBytesAvailable && (document.getElementById("WriteBytesInput").value.length != 0)) {

                WinJS.log && WinJS.log("Writing...", "sample", "status");

                serialIo.isWriting = true;
                serialIo.writingPromise = null;

                // Re-enable write button after completing the write
                serialIo.writeAsync().done(function () {
                    serialIo.isWriting = false;

                    updateButtonStates();
                }, function (error) {
                    // Promise was canceled
                    if (error.name === "Canceled") {
                        WinJS.log && WinJS.log("Write Canceled...", "sample", "status");
                        serialIo.isWriting = false;
                        updateButtonStates();
                    } else {
                        // Since this is a .done() error callback, there are no other error
                        // handlers after this. So create an error that is unhandled
                        WinJS.Promise.wrapError(error);
                    }
                });

                // Disable buttons to prevent multiple writes if the WriteAsync has not completed yet
                updateButtonStates();
            }
        } else {
            SdkSample.CustomSerialDeviceAccess.utilities.notifyDeviceNotConnected();
        }
    }

    function writeCancelButtonClicked() {
        serialIo.cancelWrite();
    }

    function readCancelButtonClicked() {
        serialIo.cancelRead();
    }

    function writeBytesInputChanged() {
        if (serialIo.writeBytesAvailable == false) {
            serialIo.writeBytesAvailable = true;
            document.getElementById("WriteBytesInput").value = "";
        }
    }

    var page = WinJS.UI.Pages.define("/html/Scenario3_readWrite.html", {
        ready: function (element, options) {

            if (SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.isDeviceConnected == false) {
                document.getElementById("scenarioContent").hidden = true;
                WinJS.log && WinJS.log("Device is NOT connected", "sample", "status");
                return;
            }

            document.getElementById("scenarioContent").hidden = false;
            document.getElementById("WriteTimeoutButton").addEventListener("click", writeTimeoutButtonClicked, false);
            document.getElementById("WriteButton").addEventListener("click", writeButtonClicked, false);
            document.getElementById("WriteCancelButton").addEventListener("click", writeCancelButtonClicked, false);
            document.getElementById("WriteBytesInput").addEventListener("focus", writeBytesInputChanged, false);

            document.getElementById("ReadTimeoutButton").addEventListener("click", readTimeoutButtonClicked, false);
            document.getElementById("ReadButton").addEventListener("click", readButtonClicked, false);
            document.getElementById("ReadCancelButton").addEventListener("click", readCancelButtonClicked, false);

            updateWriteTimeoutView();
            updateReadTimeoutView();

            updateWriteBytesCountView();
            updateReadBytesCountView();

            updateButtonStates();

            // Reset the buttons if the app resumed and the device is reconnected
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.onAppSuspendCallback = serialIo.onAppSuspension;
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.onDeviceConnectedCallback = serialIo.onDeviceConnected;

        },

        unload: function () {
            serialIo.navigatedAway = true;

            serialIo.cancelAllIoTasks();

            // We don't need to worry about app suspend for this scenario anymore
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.onAppSuspendCallback = null;
            SdkSample.CustomSerialDeviceAccess.eventHandlerForDevice.current.onDeviceConnectedCallback = null;

            // The page is not "reloaded" when navigated away and back, so we need to make reset all button states
            updateButtonStates();
        }

    });

    function updateButtonStates() {
        if (serialIo.isWriting) {
            window.WriteButton.disabled = true;
            window.WriteCancelButton.disabled = false;
        } else {
            window.WriteButton.disabled = false;
            window.WriteCancelButton.disabled = true;
        }

        if (serialIo.isReading) {
            window.ReadButton.disabled = true;
            window.ReadCancelButton.disabled = false;
        } else {
            window.ReadButton.disabled = false;
            window.ReadCancelButton.disabled = true;
        }
    }

    function doSomething() {
        WinJS.log && WinJS.log("Error message here", "sample", "error");
    }
})();


text:
import time
import inspect
import unittest
import imath

import IECore
import IECoreScene
import IECoreImage

import Gaffer
import GafferTest
import GafferImage
import GafferScene
import GafferSceneTest

# Note that this is for testing subclasses of GafferScene.Preview.InteractiveRender
# rather than GafferScene.InteractiveRender, which we hope to phase out.
class InteractiveRenderTest( GafferSceneTest.SceneTestCase ) :

	@classmethod
	def setUpClass( cls ) :

		GafferSceneTest.SceneTestCase.setUpClass()

		if cls is InteractiveRenderTest :
			# The InteractiveRenderTest class is a base class to
			# derive from when wanting to test specific InteractiveRender
			# subclasses - on its own it has no renderer so can't
			# test anything.
			raise unittest.SkipTest( "No renderer available" )

	def testOutputs( self ):

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertTrue( isinstance( image, IECoreImage.ImagePrimitive ) )

	def testAddAndRemoveOutput( self ):

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["o"] = GafferScene.Outputs()

		s["o"].addOutput(
			"beauty1",
			IECoreScene.Output(
				"test1",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere1",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Check we have our first image, but not a second one.

		self.assertTrue( isinstance( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere1" ), IECoreImage.ImagePrimitive ) )
		self.assertTrue( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere2" ) is None )

		# Add a second image and check we can have that too.

		s["o"].addOutput(
			"beauty2",
			IECoreScene.Output(
				"test1",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere2",
				}
			)
		)

		time.sleep( 0.5 )

		self.assertTrue( isinstance( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere1" ), IECoreImage.ImagePrimitive ) )
		self.assertTrue( isinstance( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere2" ), IECoreImage.ImagePrimitive ) )

		# Remove the second image and check that it stops updating.

		IECoreImage.ImageDisplayDriver.removeStoredImage( "myLovelySphere2" )
		s["o"]["outputs"][1]["active"].setValue( False )

		time.sleep( 0.5 )

		self.assertTrue( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere2" ) is None )

		# Add a third image and check we can have that too.

		s["o"].addOutput(
			"beauty3",
			IECoreScene.Output(
				"test1",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere3",
				}
			)
		)

		time.sleep( 0.5 )

		self.assertTrue( isinstance( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere1" ), IECoreImage.ImagePrimitive ) )
		self.assertTrue( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere2" ) is None )
		self.assertTrue( isinstance( IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere3" ), IECoreImage.ImagePrimitive ) )

	def testAddAndRemoveLocation( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		s["s"]["enabled"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		s["s"]["enabled"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testAddAndRemoveObject( self ) :

		s = Gaffer.ScriptNode()

		# Switch between a sphere and a group, so
		# we can keep the hierarchy the same ( "/thing" )
		# but add and remove the sphere from the location.

		s["s"] = GafferScene.Sphere()
		s["s"]["name"].setValue( "thing" )

		s["g"] = GafferScene.Group()
		s["g"]["name"].setValue( "thing" )

		s["switch"] = GafferScene.SceneSwitch()
		s["switch"]["in"][0].setInput( s["s"]["out"] )
		s["switch"]["in"][1].setInput( s["g"]["out"] )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["switch"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Render the sphere.

		s["r"]["state"].setValue( s["r"].State.Running )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Switch to the empty group.

		s["switch"]["index"].setValue( 1 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Switch back to the sphere.

		s["switch"]["index"].setValue( 0 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testEditObjectVisibility( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["g"] = GafferScene.Group()
		s["g"]["in"].setInput( s["s"]["out"] )

		s["f"] = GafferScene.PathFilter()

		s["a"] = GafferScene.StandardAttributes()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["filter"].setInput( s["f"]["out"] )
		s["a"]["attributes"]["visibility"]["enabled"].setValue( True )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["a"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide /group/sphere

		s["f"]["paths"].setValue( IECore.StringVectorData( [ "/group/sphere" ] ) )
		s["a"]["attributes"]["visibility"]["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Tweak the sphere geometry - it should remain hidden

		s["s"]["radius"].setValue( 1.01 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show it again

		s["a"]["attributes"]["visibility"]["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide /group

		s["f"]["paths"].setValue( IECore.StringVectorData( [ "/group" ] ) )
		s["a"]["attributes"]["visibility"]["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show it again

		s["a"]["attributes"]["visibility"]["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testEditCameraVisibility( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["g"] = GafferScene.Group()
		s["g"]["in"].setInput( s["s"]["out"] )

		s["f"] = GafferScene.PathFilter()

		s["a"] = GafferScene.CustomAttributes()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["filter"].setInput( s["f"]["out"] )
		visibilityPlug = s["a"]["attributes"].addMember( self._cameraVisibilityAttribute(), False )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["a"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide /group/sphere

		s["f"]["paths"].setValue( IECore.StringVectorData( [ "/group/sphere" ] ) )
		visibilityPlug["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show it again

		visibilityPlug["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide /group

		s["f"]["paths"].setValue( IECore.StringVectorData( [ "/group" ] ) )
		visibilityPlug["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show it again

		visibilityPlug["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testEditObjectTransform( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Move to one side

		s["s"]["transform"]["translate"]["x"].setValue( 2 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Move back

		s["s"]["transform"]["translate"]["x"].setValue( 0 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testShaderEdits( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["shader"], colorPlug = self._createConstantShader()
		colorPlug.setValue( imath.Color3f( 1, 0, 0 ) )

		s["a"] = GafferScene.ShaderAssignment()
		s["a"]["in"].setInput( s["s"]["out"] )
		s["a"]["shader"].setInput( s["shader"]["out"] )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["a"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Render red sphere

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.__assertColorsAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ), imath.Color4f( 1, 0, 0, 1 ), delta = 0.01 )

		# Make it green

		colorPlug.setValue( imath.Color3f( 0, 1, 0 ) )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.__assertColorsAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ), imath.Color4f( 0, 1, 0, 1 ), delta = 0.01 )

		# Make it blue

		colorPlug.setValue( imath.Color3f( 0, 0, 1 ) )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.__assertColorsAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ), imath.Color4f( 0, 0, 1, 1 ), delta = 0.01 )

	def testEditCameraTransform( self ) :

		s = Gaffer.ScriptNode()

		s["s"] = GafferScene.Sphere()
		s["c"] = GafferScene.Camera()

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["s"]["out"] )
		s["g"]["in"][1].setInput( s["c"]["out"] )

		s["outputs"] = GafferScene.Outputs()
		s["outputs"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["outputs"]["in"].setInput( s["g"]["out"] )

		s["options"] = GafferScene.StandardOptions()
		s["options"]["in"].setInput( s["outputs"]["out"] )
		s["options"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["options"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["options"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Move to one side

		s["c"]["transform"]["translate"]["x"].setValue( 2 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Move back

		s["c"]["transform"]["translate"]["x"].setValue( 0 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testEditResolution( self ) :

		s = Gaffer.ScriptNode()

		s["sphere"] = GafferScene.Sphere()
		s["camera"] = GafferScene.Camera()

		s["group"] = GafferScene.Group()
		s["group"]["in"][0].setInput( s["sphere"]["out"] )
		s["group"]["in"][1].setInput( s["camera"]["out"] )

		s["outputs"] = GafferScene.Outputs()
		s["outputs"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["outputs"]["in"].setInput( s["group"]["out"] )

		s["options"] = GafferScene.StandardOptions()
		s["options"]["in"].setInput( s["outputs"]["out"] )
		s["options"]["options"]["renderCamera"]["enabled"].setValue( True )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["options"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		for withDefaultCamera in ( True, False ) :

			s["options"]["options"]["renderCamera"]["value"].setValue(
				"" if withDefaultCamera else "/group/camera"
			)

			time.sleep( 0.5 )

			# Use the default resolution to start with

			self.assertEqual(
				IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" ).displayWindow,
				imath.Box2i( imath.V2i( 0 ), imath.V2i( 639, 479 ) )
			)

			# Now specify a resolution

			s["options"]["options"]["renderResolution"]["enabled"].setValue( True )
			s["options"]["options"]["renderResolution"]["value"].setValue( imath.V2i( 200, 100 ) )

			time.sleep( 0.5 )

			self.assertEqual(
				IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" ).displayWindow,
				imath.Box2i( imath.V2i( 0 ), imath.V2i( 199, 99 ) )
			)

			# And specify another resolution

			s["options"]["options"]["renderResolution"]["value"].setValue( imath.V2i( 300, 100 ) )

			time.sleep( 0.5 )

			self.assertEqual(
				IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" ).displayWindow,
				imath.Box2i( imath.V2i( 0 ), imath.V2i( 299, 99 ) )
			)

			# And back to the default

			s["options"]["options"]["renderResolution"]["enabled"].setValue( False )

			time.sleep( 0.5 )

			self.assertEqual(
				IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" ).displayWindow,
				imath.Box2i( imath.V2i( 0 ), imath.V2i( 639, 479 ) )
			)

	def testDeleteWhilePaused( self ) :

		s = Gaffer.ScriptNode()

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["p"]["out"] )
		s["g"]["in"][1].setInput( s["c"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["g"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to get going, then pause it.
		s["r"]["state"].setValue( s["r"].State.Running )
		time.sleep( 2 )
		s["r"]["state"].setValue( s["r"].State.Paused )

		# Delete everything, and check that we don't hang.
		del s

	def testChangeInputWhilePaused( self ) :

		s = Gaffer.ScriptNode()

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["p"]["out"] )
		s["g"]["in"][1].setInput( s["c"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["g"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to get going, then pause it.

		s["r"]["state"].setValue( s["r"].State.Running )
		time.sleep( 2 )
		s["r"]["state"].setValue( s["r"].State.Paused )

		# Change the input to the render node, and check that we don't hang.

		s["o2"] = GafferScene.StandardOptions()
		s["o2"]["in"].setInput( s["o"]["out"] )

		s["r"]["in"].setInput( s["o2"]["out"] )

		# Start the render again, so we know we're not just testing
		# the same thing as testDeleteWhilePaused().
		s["r"]["state"].setValue( s["r"].State.Running )

	def testEditContext( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		# Sphere moves with time.
		s["e"] = Gaffer.Expression()
		s["e"].setExpression( """parent["s"]["transform"]["translate"]["x"] = context.getFrame() - 1""" )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Move to one side

		s.context().setFrame( 3 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Move back

		s.context().setFrame( 1 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Repeat, using a context we set directly ourselves.

		c = Gaffer.Context()
		c.setFrame( 3 )
		s["r"].setContext( c )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		c.setFrame( 1 )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testLights( self ) :

		s = Gaffer.ScriptNode()

		s["l"], colorPlug = self._createPointLight()
		colorPlug.setValue( imath.Color3f( 1, 0.5, 0.25 ) )
		s["l"]["transform"]["translate"]["z"].setValue( 1 )

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["l"]["out"] )
		s["g"]["in"][1].setInput( s["p"]["out"] )
		s["g"]["in"][2].setInput( s["c"]["out"] )

		s["s"], unused = self._createMatteShader()
		s["a"] = GafferScene.ShaderAssignment()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["shader"].setInput( s["s"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["a"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to finish, and check the output.

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[0], imath.Color3f( 1, 0.5, 0.25 ) )

		# Adjust a parameter, give it time to update, and check the output.

		colorPlug.setValue( imath.Color3f( 0.25, 0.5, 1 ) )

		time.sleep( 1 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[2], imath.Color3f( 0.25, 0.5, 1 ) )

		# Pause it, adjust a parameter, wait, and check that nothing changed.

		s["r"]["state"].setValue( s["r"].State.Paused )
		colorPlug.setValue( imath.Color3f( 1, 0.5, 0.25 ) )

		time.sleep( 1 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[2], imath.Color3f( 0.25, 0.5, 1 ) )

		# Unpause it, wait, and check that the update happened.

		s["r"]["state"].setValue( s["r"].State.Running )
		time.sleep( 1 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[0], imath.Color3f( 1, 0.5, 0.25 ) )

		# Stop the render, tweak a parameter and check that nothing happened.

		s["r"]["state"].setValue( s["r"].State.Stopped )
		colorPlug.setValue( imath.Color3f( 0.25, 0.5, 1 ) )
		time.sleep( 1 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[0], imath.Color3f( 1, 0.5, 0.25 ) )

	def testAddLight( self ) :

		s = Gaffer.ScriptNode()

		s["l"], colorPlug = self._createPointLight()
		colorPlug.setValue( imath.Color3f( 1, 0, 0 ) )
		s["l"]["transform"]["translate"]["z"].setValue( 1 )

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["l"]["out"] )
		s["g"]["in"][1].setInput( s["p"]["out"] )
		s["g"]["in"][2].setInput( s["c"]["out"] )

		s["s"], unused = self._createMatteShader()
		s["a"] = GafferScene.ShaderAssignment()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["shader"].setInput( s["s"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["a"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to finish, and check the output.

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[0], imath.Color3f( 1, 0, 0 ) )

		# Add a light

		s["l2"], colorPlug = self._createPointLight()
		colorPlug.setValue( imath.Color3f( 0, 1, 0 ) )
		s["l2"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"]["in"][3].setInput( s["l2"]["out"] )

		# Give it time to update, and check the output.

		time.sleep( 1 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c / c[0], imath.Color3f( 1, 1, 0 ) )

	def testRemoveLight( self ) :

		s = Gaffer.ScriptNode()

		s["l"], unused = self._createPointLight()
		s["l"]["transform"]["translate"]["z"].setValue( 1 )

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["l"]["out"] )
		s["g"]["in"][1].setInput( s["p"]["out"] )
		s["g"]["in"][2].setInput( s["c"]["out"] )

		s["s"], unused = self._createMatteShader()
		s["a"] = GafferScene.ShaderAssignment()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["shader"].setInput( s["s"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["a"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to finish, and check the output.

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertNotEqual( c[0], 0.0 )

		# Remove the light by disabling it.

		s["l"]["enabled"].setValue( False )
		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c[0], 0.0 )

		# Enable it again.

		s["l"]["enabled"].setValue( True )
		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertNotEqual( c[0], 0.0 )

	def testHideLight( self ) :

		s = Gaffer.ScriptNode()

		s["l"], unused = self._createPointLight()
		s["l"]["transform"]["translate"]["z"].setValue( 1 )

		s["v"] = GafferScene.StandardAttributes()
		s["v"]["attributes"]["visibility"]["enabled"].setValue( True )
		s["v"]["in"].setInput( s["l"]["out"] )

		s["p"] = GafferScene.Plane()

		s["c"] = GafferScene.Camera()
		s["c"]["transform"]["translate"]["z"].setValue( 1 )

		s["g"] = GafferScene.Group()
		s["g"]["in"][0].setInput( s["v"]["out"] )
		s["g"]["in"][1].setInput( s["p"]["out"] )
		s["g"]["in"][2].setInput( s["c"]["out"] )

		s["s"], unused = self._createMatteShader()
		s["a"] = GafferScene.ShaderAssignment()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["shader"].setInput( s["s"]["out"] )

		s["d"] = GafferScene.Outputs()
		s["d"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"quantize" : IECore.IntVectorData( [ 0, 0, 0, 0 ] ),
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelyPlane",
				}
			)
		)
		s["d"]["in"].setInput( s["a"]["out"] )

		s["o"] = GafferScene.StandardOptions()
		s["o"]["options"]["renderCamera"]["value"].setValue( "/group/camera" )
		s["o"]["options"]["renderCamera"]["enabled"].setValue( True )
		s["o"]["in"].setInput( s["d"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# Start a render, give it time to finish, and check the output.

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertNotEqual( c[0], 0.0 )

		# Remove the light by hiding it.

		s["v"]["attributes"]["visibility"]["value"].setValue( False )
		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)
		self.assertEqual( c[0], 0.0 )

		# Put the light back by showing it.

		s["v"]["attributes"]["visibility"]["value"].setValue( True )
		time.sleep( 2 )

		c = self.__color3fAtUV(
			IECoreImage.ImageDisplayDriver.storedImage( "myLovelyPlane" ),
			imath.V2f( 0.5 ),
		)

		self.assertNotEqual( c[0], 0.0 )

	def testGlobalAttributes( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["g"] = GafferScene.Group()
		s["g"]["in"].setInput( s["s"]["out"] )

		s["a"] = GafferScene.StandardAttributes()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["global"].setValue( True )
		s["a"]["attributes"]["visibility"]["enabled"].setValue( True )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["a"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide

		s["a"]["attributes"]["visibility"]["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show again

		s["a"]["attributes"]["visibility"]["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testGlobalCameraVisibility( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["g"] = GafferScene.Group()
		s["g"]["in"].setInput( s["s"]["out"] )

		s["a"] = GafferScene.CustomAttributes()
		s["a"]["in"].setInput( s["g"]["out"] )
		s["a"]["global"].setValue( True )
		visibilityPlug = s["a"]["attributes"].addMember( self._cameraVisibilityAttribute(), True )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["a"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Visible to start with

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

		# Hide

		visibilityPlug["value"].setValue( False )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0, delta = 0.01 )

		# Show again

		visibilityPlug["value"].setValue( True )
		time.sleep( 0.5 )

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.assertAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 1, delta = 0.01 )

	def testEffectiveContext( self ) :

		s = Gaffer.ScriptNode()

		s["s"] = GafferScene.Sphere()
		s["e"] = Gaffer.Expression()
		s["e"].setExpression(
			inspect.cleandoc(
				"""
				assert( context.getFrame() == 10 )
				parent["s"]["radius"] = 1
				"""
			)
		)

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		# No override context.
		self.assertEqual( s["r"].getContext(), None )
		# Meaning we should use the script context.
		# Set the frame to 10 to keep the expression happy.
		s.context().setFrame( 10 )

		# Arrange to catch the error the expression will throw
		# if it isn't happy.
		errors = GafferTest.CapturingSlot( s["r"].errorSignal() )

		# Start the render and assert that we're good.
		s["r"]["state"].setValue( s["r"].State.Running )
		time.sleep( 0.25 )
		self.assertEqual( len( errors ), 0 )
		s["r"]["state"].setValue( s["r"].State.Stopped )

		# Now, do the same using an InteractiveRender node
		# created in a box before parenting to the script

		box = Gaffer.Box()
		box["r"] = self._createInteractiveRender()
		self.assertEqual( box["r"].getContext(), None )
		s["b"] = box
		self.assertEqual( box["r"].getContext(), None )
		p = Gaffer.PlugAlgo.promote( box["r"]["in"] )
		p.setInput( s["o"]["out"] )

		errors = GafferTest.CapturingSlot( box["r"].errorSignal() )

		box["r"]["state"].setValue( box["r"].State.Running )
		time.sleep( 0.25 )
		self.assertEqual( len( errors ), 0 )
		box["r"]["state"].setValue( box["r"].State.Stopped )

		# Now, set the wrong frame on the script context,
		# and instead supply our own context with the right frame.

		s.context().setFrame( 1 )
		context = Gaffer.Context()
		context.setFrame( 10 )
		box["r"].setContext( context )
		self.assertTrue( box["r"].getContext().isSame( context ) )

		box["r"]["state"].setValue( box["r"].State.Running )
		time.sleep( 0.25 )
		self.assertEqual( len( errors ), 0 )
		box["r"]["state"].setValue( box["r"].State.Stopped )

	def testTraceSets( self ) :

		s = Gaffer.ScriptNode()

		s["reflector"] = GafferScene.Plane()
		s["reflector"]["name"].setValue( "reflector" )
		s["reflector"]["transform"]["translate"].setValue( imath.V3f( 0, 0, -1 ) )

		s["reflected"] = GafferScene.Plane()
		s["reflected"]["name"].setValue( "reflected" )
		s["reflected"]["transform"]["translate"].setValue( imath.V3f( 0, 0, 1 ) )

		s["group"] = GafferScene.Group()
		s["group"]["in"][0].setInput( s["reflector"]["out"] )
		s["group"]["in"][1].setInput( s["reflected"]["out"] )

		s["constant"], constantParameter = self._createConstantShader()
		s["constantAssignment"] = GafferScene.ShaderAssignment()
		s["constantAssignment"]["in"].setInput( s["group"]["out"] )
		s["constantAssignment"]["shader"].setInput( s["constant"]["out"] )

		traceShader, traceSetParameter = self._createTraceSetShader()
		if traceShader is None :
			self.skipTest( "Trace set shader not available" )

		s["traceShader"] = traceShader

		s["traceAssignmentFilter"] = GafferScene.PathFilter()
		s["traceAssignmentFilter"]["paths"].setValue( IECore.StringVectorData( [ "/group/reflector" ] ) )

		s["traceAssignment"] = GafferScene.ShaderAssignment()
		s["traceAssignment"]["in"].setInput( s["constantAssignment"]["out"] )
		s["traceAssignment"]["shader"].setInput( s["traceShader"]["out"] )
		s["traceAssignment"]["filter"].setInput( s["traceAssignmentFilter"]["out"] )

		s["set"] = GafferScene.Set()
		s["set"]["in"].setInput( s["traceAssignment"]["out"] )
		s["set"]["name"].setValue( "render:myTraceSet" )

		s["options"] = GafferScene.CustomOptions()
		s["options"]["in"].setInput( s["set"]["out"] )
		for o in self._traceDepthOptions() :
			s["options"]["options"].addMember( o, IECore.IntData( 1 ) )

		s["outputs"] = GafferScene.Outputs()
		s["outputs"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "traceSetsTest",
				}
			)
		)
		s["outputs"]["in"].setInput( s["options"]["out"] )

		s["render"] = self._createInteractiveRender()
		s["render"]["in"].setInput( s["outputs"]["out"] )
		s["render"]["state"].setValue( s["render"].State.Running )

		time.sleep( 0.5 )

		# We haven't used the trace sets yet, so should be able to see
		# the reflection.

		def assertReflected( reflected ) :

			image = IECoreImage.ImageDisplayDriver.storedImage( "traceSetsTest" )
			self.assertGreater( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).a, 0.9 )
			if reflected :
				self.assertGreater( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0.9 )
			else :
				self.assertLess( self.__color4fAtUV( image, imath.V2f( 0.5 ) ).r, 0.1 )

		assertReflected( True )

		# Ask to use a trace set. Reflection should disappear because
		# we haven't added anything to the set.

		traceSetParameter.setValue( "myTraceSet" )
		time.sleep( 0.5 )
		assertReflected( False )

		# Now add the reflected object into the set. Reflection should
		# come back.

		s["set"]["paths"].setValue( IECore.StringVectorData( [ "/group/reflected" ] ) )
		time.sleep( 0.5 )
		assertReflected( True )

		# Rename the set so that it's not a trace set any more. Reflection
		# should disappear.

		s["set"]["name"].setValue( "myTraceSet" )
		time.sleep( 0.5 )
		assertReflected( False )

		# Rename the set so that it is a trace set, but with a different namer.
		# Reflection should not reappear.

		s["set"]["name"].setValue( "render:myOtherTraceSet" )
		time.sleep( 0.5 )
		assertReflected( False )

		# Update the shader to use this new trace set. Reflection should
		# reappear.

		traceSetParameter.setValue( "myOtherTraceSet" )
		time.sleep( 0.5 )
		assertReflected( True )

	def testRendererContextVariable( self ):

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphereRenderedIn${scene:renderer}",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		renderer = s["r"]["renderer"].getValue() if "renderer" in s["r"] else s["r"]["__renderer"].getValue()
		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphereRenderedIn" + renderer )
		self.assertTrue( isinstance( image, IECoreImage.ImagePrimitive ) )

	def testAdaptors( self ) :

		s = Gaffer.ScriptNode()
		s["s"] = GafferScene.Sphere()

		def a() :

			result = GafferScene.SceneProcessor()

			result["__shader"], colorPlug = self._createConstantShader()
			colorPlug.setValue( imath.Color3f( 1, 0, 0 ) )

			result["__assignment"] = GafferScene.ShaderAssignment()
			result["__assignment"]["in"].setInput( result["in"] )
			result["__assignment"]["shader"].setInput( result["__shader"]["out"] )

			result["out"].setInput( result["__assignment"]["out"] )

			return result

		GafferScene.registerAdaptor( "Test", a )

		s["o"] = GafferScene.Outputs()
		s["o"].addOutput(
			"beauty",
			IECoreScene.Output(
				"test",
				"ieDisplay",
				"rgba",
				{
					"driverType" : "ImageDisplayDriver",
					"handle" : "myLovelySphere",
				}
			)
		)
		s["o"]["in"].setInput( s["s"]["out"] )

		s["r"] = self._createInteractiveRender()
		s["r"]["in"].setInput( s["o"]["out"] )

		s["r"]["state"].setValue( s["r"].State.Running )

		time.sleep( 0.5 )

		# Render red sphere

		image = IECoreImage.ImageDisplayDriver.storedImage( "myLovelySphere" )
		self.__assertColorsAlmostEqual( self.__color4fAtUV( image, imath.V2f( 0.5 ) ), imath.Color4f( 1, 0, 0, 1 ), delta = 0.01 )

	def tearDown( self ) :

		GafferSceneTest.SceneTestCase.tearDown( self )

		GafferScene.deregisterAdaptor( "Test" )

	## Should be implemented by derived classes to return an
	# appropriate InteractiveRender node.
	def _createInteractiveRender( self ) :

		raise NotImplementedError

	## Should be implemented by derived classes to return an
	# appropriate Shader node with a constant shader loaded,
	# along with the plug for the colour parameter.
	def _createConstantShader( self ) :

		raise NotImplementedError

	## Should be implemented by derived classes to return
	# an appropriate Shader node with a matte shader loaded,
	# along with the plug for the colour parameter.
	def _createMatteShader( self ) :

		raise NotImplementedError

	## Should be implemented by derived classes to return
	# a shader which traces against only geometry in a trace
	# set parameter.
	def _createTraceSetShader( self ) :

		raise NotImplementedError

	## Should be implemented by derived classes to return
	# the name of a bool attribute which controls camera
	# visibility.
	def _cameraVisibilityAttribute( self ) :

		raise NotImplementedError

	## Should be implemented by derived classes to return the
	# names of int options which control trace depth.
	def _traceDepthOptions( self ) :

		raise NotImplementedError

	# Should be implemented by derived classes to return
	# an appropriate Light node with a point light loaded,
	# along with the plug for the colour parameter.
	def _createPointLight( self ) :

		raise NotImplementedError

	def __color4fAtUV( self, image, uv ) :

		objectToImage = GafferImage.ObjectToImage()
		objectToImage["object"].setValue( image )

		sampler = GafferImage.ImageSampler()
		sampler["image"].setInput( objectToImage["out"] )
		sampler["pixel"].setValue(
			uv * imath.V2f(
				image.displayWindow.size().x,
				image.displayWindow.size().y
			)
		)

		return sampler["color"].getValue()

	def __color3fAtUV( self, image, uv ) :

		c = self.__color4fAtUV( image, uv )
		return imath.Color3f( c.r, c.g, c.b )

	def __assertColorsAlmostEqual( self, c0, c1, **kw ) :

		for i in range( 0, 4 ) :
			self.assertAlmostEqual( c0[i], c1[i], **kw )

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


text:
package org.apache.hadoop.hbase.procedure2;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
import org.apache.hadoop.hbase.procedure2.store.NoopProcedureStore;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category({MasterTests.class, SmallTests.class})
public class TestProcedureInMemoryChore {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestProcedureInMemoryChore.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestProcedureInMemoryChore.class);

  private static final int PROCEDURE_EXECUTOR_SLOTS = 1;

  private TestProcEnv procEnv;
  private NoopProcedureStore procStore;
  private ProcedureExecutor<TestProcEnv> procExecutor;

  private HBaseCommonTestingUtility htu;

  @Before
  public void setUp() throws IOException {
    htu = new HBaseCommonTestingUtility();

    procEnv = new TestProcEnv();
    procStore = new NoopProcedureStore();
    procExecutor = new ProcedureExecutor<>(htu.getConfiguration(), procEnv, procStore);
    procExecutor.testing = new ProcedureExecutor.Testing();
    procStore.start(PROCEDURE_EXECUTOR_SLOTS);
    ProcedureTestingUtility.initAndStartWorkers(procExecutor, PROCEDURE_EXECUTOR_SLOTS, true);
  }

  @After
  public void tearDown() throws IOException {
    procExecutor.stop();
    procStore.stop(false);
  }

  @Test
  public void testChoreAddAndRemove() throws Exception {
    final int timeoutMSec = 50;
    final int nCountDown = 5;

    // submit the chore and wait for execution
    CountDownLatch latch = new CountDownLatch(nCountDown);
    TestLatchChore chore = new TestLatchChore(timeoutMSec, latch);
    procExecutor.addChore(chore);
    assertTrue(chore.isWaiting());
    latch.await();

    // remove the chore and verify it is no longer executed
    assertTrue(chore.isWaiting());
    procExecutor.removeChore(chore);
    latch = new CountDownLatch(nCountDown);
    chore.setLatch(latch);
    latch.await(timeoutMSec * nCountDown, TimeUnit.MILLISECONDS);
    LOG.info("chore latch count=" + latch.getCount());
    assertFalse(chore.isWaiting());
    assertTrue("latchCount=" + latch.getCount(), latch.getCount() > 0);
  }

  public static class TestLatchChore extends ProcedureInMemoryChore<TestProcEnv> {
    private CountDownLatch latch;

    public TestLatchChore(final int timeoutMSec, final CountDownLatch latch) {
      super(timeoutMSec);
      setLatch(latch);
    }

    public void setLatch(final CountDownLatch latch) {
      this.latch = latch;
    }

    @Override
    protected void periodicExecute(final TestProcEnv env) {
      LOG.info("periodic execute " + this);
      latch.countDown();
    }
  }

  private static class TestProcEnv {
  }
}


text:
(function () {
	'use strict';

	angular.module('courierChat').controller('LoginController', LoginController);

	function LoginController($rootScope, $state, userResource) {
		var vm = this;

		vm.username = null;
		vm.error = null;

		vm.login = login;

		onLoad();

		function onLoad() {
			$rootScope.title = 'Login - CourierChat';

			if ($rootScope.user) {
				$state.go('rooms');
			}
		}

		function login() {
			if (vm.username === null || vm.username.length === 0) {

				vm.error = 'Wait a second, you still haven\'t introduced yourself.';
				return;
			}

			vm.error = null;

			userResource.login(vm.username,
				function (user) {
					$rootScope.user = user;
					$state.go('rooms');
				},
				function (response) {
					vm.error = response.data.error;
				}
			);
		}
	}
})();


text:
class AddColunmHaSidoMonitorToMonitoria < ActiveRecord::Migration[5.0]
  def change
    add_column :monitorias, :ha_sido_monitor, :boolean
    add_column :monitorias, :comentarios_estudiante, :text
    add_column :practicas, :fecha_limite, :string
  end
end


text:
package mesosphere.marathon
package core.appinfo

trait Selector[A] {

  def matches(a: A): Boolean
}

object Selector {

  def apply[A](f: A => Boolean): Selector[A] =
    new Selector[A] {
      override def matches(a: A): Boolean = f(a)
    }

  def all[A]: Selector[A] = Selector[A] { _ => true }

  def none[A]: Selector[A] = Selector[A] { _ => false }

  def forall[A](it: Seq[Selector[A]]): Selector[A] =
    new Selector[A] {
      override def matches(a: A): Boolean = it.forall(_.matches(a))
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
    <corners
        android:bottomLeftRadius="16dp"
        android:bottomRightRadius="16dp"
        android:topLeftRadius="16dp"
        android:topRightRadius="16dp"/>
    <gradient
    android:startColor="#ffffffff"
    android:endColor="#ffbbbbbb"
    android:angle="270" />

</shape>