text:
/// \file
/// \brief Automatically serializing and deserializing RPC system. Third generation of RPC.

#ifndef __RPC_3_H
#define __RPC_3_H

// Most of the internals of the boost code to make this work
#include "RPC3_Boost.h"
#include "PluginInterface2.h"
#include "PacketPriority.h"
#include "RakNetTypes.h"
#include "BitStream.h"
#include "RakString.h"
#include "NetworkIDObject.h"
#include "DS_Hash.h"
#include "DS_OrderedList.h"

#ifdef _MSC_VER
#pragma warning( push )
#endif

/// \defgroup RPC_3_GROUP RPC3
/// \brief Remote procedure calls, powered by the 3rd party library Boost
/// \details
/// \ingroup PLUGINS_GROUP

namespace RakNet
{
class RakPeerInterface;
class NetworkIDManager;

/// \ingroup RPC_3_GROUP
#define RPC3_REGISTER_FUNCTION(RPC3Instance, _FUNCTION_PTR_ ) (RPC3Instance)->RegisterFunction((#_FUNCTION_PTR_), (_FUNCTION_PTR_))

/// \brief Error codes returned by a remote system as to why an RPC function call cannot execute
/// \details Error code follows packet ID ID_RPC_REMOTE_ERROR, that is packet->data[1]

/// Name of the function will be appended starting at packet->data[2]
/// \ingroup RPC_3_GROUP
enum RPCErrorCodes
{
	/// RPC3::SetNetworkIDManager() was not called, and it must be called to call a C++ object member
	RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE,

	/// Cannot execute C++ object member call because the object specified by SetRecipientObject() does not exist on this system
	RPC_ERROR_OBJECT_DOES_NOT_EXIST,

	/// Internal error, index optimization for function lookup does not exist
	RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE,

	/// Named function was not registered with RegisterFunction(). Check your spelling.
	RPC_ERROR_FUNCTION_NOT_REGISTERED,

	/// Named function was registered, but later unregistered with UnregisterFunction() and can no longer be called.
	RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED,

	/// SetRecipientObject() was not called before Call(), but the registered pointer is a class member
	/// If you intended to call a class member function, call SetRecipientObject() with a valid object first.
	RPC_ERROR_CALLING_CPP_AS_C,

	/// SetRecipientObject() was called before Call(), but RegisterFunction() was called with isObjectMember=false
	/// If you intended to call a C function, call SetRecipientObject(UNASSIGNED_NETWORK_ID) first.
	RPC_ERROR_CALLING_C_AS_CPP,
};

/// \brief The RPC3 plugin allows you to call remote functions as if they were local functions, using the standard function call syntax
/// \details No serialization or deserialization is needed.

/// As of this writing, the system is not threadsafe.

/// Features:

///
Pointers to classes that derive from NetworkID are automatically looked up using NetworkIDManager
///
Types are written to BitStream, meaning built-in serialization operations are performed, including endian swapping
///
Types can customize autoserialization by providing an implementation of operator << and operator >> to and from BitStream
/// \note You cannot use RPC4 at the same time as RPC3
/// \ingroup RPC_3_GROUP
class RPC3 : public PluginInterface2
{
public:
	// Constructor
	RPC3();

	// Destructor
	virtual ~RPC3();

	/// Sets the network ID manager to use for object lookup
	/// Required to call C++ object member functions via SetRecipientObject()
	/// \param[in] idMan Pointer to the network ID manager to use
	void SetNetworkIDManager(NetworkIDManager *idMan);

	/// Register a function pointer as callable using RPC()
	/// \param[in] uniqueIdentifier String identifying the function. Recommended that this is the name of the function
	/// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION
	/// \return True on success, false on uniqueIdentifier already used
	template<typename Function>
	bool RegisterFunction(const char *uniqueIdentifier, Function functionPtr)
	{
		if (IsFunctionRegistered(uniqueIdentifier)) return false;
		_RPC3::FunctionPointer fp;
		fp= _RPC3::GetBoundPointer(functionPtr);
		localFunctions.Push(uniqueIdentifier,RakNet::OP_NEW_1<LocalRPCFunction>( _FILE_AND_LINE_, fp ),_FILE_AND_LINE_);
		return true;
	}

	/// \internal
	// Callable object, along with priority to call relative to other objects
	struct LocalSlotObject
	{
		LocalSlotObject() {}
		LocalSlotObject(NetworkID _associatedObject,unsigned int _registrationCount,int _callPriority,_RPC3::FunctionPointer _functionPointer)
		{associatedObject=_associatedObject;registrationCount=_registrationCount;callPriority=_callPriority;functionPointer=_functionPointer;}
		~LocalSlotObject() {}

		// Used so slots are called in the order they are registered
		NetworkID associatedObject;
		unsigned int registrationCount;
		int callPriority;
		_RPC3::FunctionPointer functionPointer;
	};
	/// \internal
	/// Identifies an RPC function, by string identifier and if it is a C or C++ function
	typedef RakString RPCIdentifier;
	static int LocalSlotObjectComp( const LocalSlotObject &key, const LocalSlotObject &data );
	/// \internal
	struct LocalSlot
	{
//		RPCIdentifier identifier;
		DataStructures::OrderedList<LocalSlotObject,LocalSlotObject,LocalSlotObjectComp> slotObjects;
	};
	/// Register a slot, which is a function pointer to one or more instances of a class that supports this function signature
	/// When a signal occurs, all slots with the same identifier are called.
	/// \param[in] sharedIdentifier A string to identify the slot. Recommended to be the same as the name of the function.
	/// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION
	/// \param[in] objectInstance If 0, then this slot is just a regular C function. Otherwise, this is a member of the given class instance.
	/// \param[in] callPriority Slots are called by order of the highest callPriority first. For slots with the same priority, they are called in the order they are registered
	template<typename Function>
	void RegisterSlot(const char *sharedIdentifier, Function functionPtr, NetworkID objectInstanceId, int callPriority)
	{
		_RPC3::FunctionPointer fp;
		fp= _RPC3::GetBoundPointer(functionPtr);
		LocalSlotObject lso(objectInstanceId, nextSlotRegistrationCount++, callPriority, _RPC3::GetBoundPointer(functionPtr));
		DataStructures::HashIndex idx = GetLocalSlotIndex(sharedIdentifier);
		LocalSlot *localSlot;
		if (idx.IsInvalid())
		{
			localSlot = RakNet::OP_NEW<LocalSlot>(_FILE_AND_LINE_);
			localSlots.Push(sharedIdentifier, localSlot,_FILE_AND_LINE_);
		}
		else
		{
			localSlot=localSlots.ItemAtIndex(idx);
		}
		localSlot->slotObjects.Insert(lso,lso,true,_FILE_AND_LINE_);
	}

	/// Unregisters a function pointer to be callable given an identifier for the pointer
	/// \param[in] uniqueIdentifier String identifying the function.
	/// \return True on success, false on function was not previously or is not currently registered.
	bool UnregisterFunction(const char *uniqueIdentifier);

	/// Returns if a function identifier was previously registered on this system with RegisterFunction(), and not unregistered with UnregisterFunction()
	/// \param[in] uniqueIdentifier String identifying the function.
	/// \return True if the function was registered, false otherwise
	bool IsFunctionRegistered(const char *uniqueIdentifier);

	/// Send or stop sending a timestamp with all following calls to Call()
	/// Use GetLastSenderTimestamp() to read the timestamp.
	/// \param[in] timeStamp Non-zero to pass this timestamp using the ID_TIMESTAMP system. 0 to clear passing a timestamp.
	void SetTimestamp(RakNet::Time timeStamp);

	/// Set parameters to pass to RakPeer::Send() for all following calls to Call()
	/// Deafults to HIGH_PRIORITY, RELIABLE_ORDERED, ordering channel 0
	/// \param[in] priority See RakPeer::Send()
	/// \param[in] reliability See RakPeer::Send()
	/// \param[in] orderingChannel See RakPeer::Send()
	void SetSendParams(PacketPriority priority, PacketReliability reliability, char orderingChannel);

	/// Set system to send to for all following calls to Call()
	/// Defaults to RakNet::UNASSIGNED_SYSTEM_ADDRESS, broadcast=true
	/// \param[in] systemAddress See RakPeer::Send()
	/// \param[in] broadcast See RakPeer::Send()
	void SetRecipientAddress(const SystemAddress &systemAddress, bool broadcast);

	/// Set the NetworkID to pass for all following calls to Call()
	/// Defaults to UNASSIGNED_NETWORK_ID (none)
	/// If set, the remote function will be considered a C++ function, e.g. an object member function
	/// If set to UNASSIGNED_NETWORK_ID (none), the remote function will be considered a C function
	/// If this is set incorrectly, you will get back either RPC_ERROR_CALLING_C_AS_CPP or RPC_ERROR_CALLING_CPP_AS_C
	/// \sa NetworkIDManager
	/// \param[in] networkID Returned from NetworkIDObject::GetNetworkID()
	void SetRecipientObject(NetworkID networkID);

	/// If the last received function call has a timestamp included, it is stored and can be retrieved with this function.
	/// \return 0 if the last call did not have a timestamp, else non-zero
	RakNet::Time GetLastSenderTimestamp(void) const;

	/// Returns the system address of the last system to send us a received function call
	/// Equivalent to the old system RPCParameters::sender
	/// \return Last system to send an RPC call using this system
	SystemAddress GetLastSenderAddress(void) const;

	/// If called while processing a slot, no further slots for the currently executing signal will be executed
	void InterruptSignal(void);

	/// Returns the instance of RakPeer this plugin was attached to
	RakPeerInterface *GetRakPeer(void) const;

	/// Returns the currently running RPC call identifier, set from RegisterFunction::uniqueIdentifier
	/// Returns an empty string "" if none
	/// \return which RPC call is currently running
	const char *GetCurrentExecution(void) const;

	/// Calls a remote function, using as send parameters whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
	/// If you call a C++ class member function, don't forget to first call SetRecipientObject(). You can use CallExplicit() instead of Call() to force yourself not to forget.
	///
	/// Parameters passed to Call are processed as follows:
	/// 1. If the parameter is not a pointer
	/// 2. - And you overloaded RakNet::BitStream& operator<<(RakNet::BitStream& out, MyClass& in) then that will be used to do the serialization
	/// 3. - Otherwise, it will use bitStream.Write(myClass); BitStream already defines specializations for NetworkIDObject, SystemAddress, other BitStreams
	/// 4. If the parameter is a pointer
	/// 5. - And the pointer can be converted to NetworkIDObject, then it will write bitStream.Write(myClass->GetNetworkID()); To make it also dereference the pointer, use RakNet::_RPC3::Deref(myClass)
	/// 6. - And the pointer can not be converted to NetworkID, but it is a pointer to RakNet::RPC3, then it is skipped
	/// 7. Otherwise, the pointer is dereferenced and written as in step 2 and 3.
	///
	/// \note If you need endian swapping (Mac talking to PC for example), you pretty much need to define operator << and operator >> for all classes you want to serialize. Otherwise the member variables will not be endian swapped.
	/// \note If the call fails on the remote system, you will get back ID_RPC_REMOTE_ERROR. packet->data[1] will contain one of the values of RPCErrorCodes. packet->data[2] and on will contain the name of the function.
	///
	/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
	bool Call(const char *uniqueIdentifier){
		RakNet::BitStream bitStream;
		return SendCallOrSignal(uniqueIdentifier, 0, &bitStream, true);
	}
	template <class P1>
	bool Call(const char *uniqueIdentifier, P1 &p1)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		return SendCallOrSignal(uniqueIdentifier, 1, &bitStream, true);
	}
	template <class P1, class P2>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		return SendCallOrSignal(uniqueIdentifier, 2, &bitStream, true);
	}
	template <class P1, class P2, class P3>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		return SendCallOrSignal(uniqueIdentifier, 3, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		return SendCallOrSignal(uniqueIdentifier, 4, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		return SendCallOrSignal(uniqueIdentifier, 5, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		return SendCallOrSignal(uniqueIdentifier, 6, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		return SendCallOrSignal(uniqueIdentifier, 7, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		return SendCallOrSignal(uniqueIdentifier, 8, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		_RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9);
		// bitStream.PrintBits();
		return SendCallOrSignal(uniqueIdentifier, 9, &bitStream, true);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10>
	bool Call(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		_RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9);
		_RPC3::SerializeCallParameterBranch<P10>::type::apply(bitStream, p10);
		// bitStream.PrintBits();
		return SendCallOrSignal(uniqueIdentifier, 10, &bitStream, true);
	}

	struct CallExplicitParameters
	{
		CallExplicitParameters(
			NetworkID _networkID=UNASSIGNED_NETWORK_ID, SystemAddress _systemAddress=RakNet::UNASSIGNED_SYSTEM_ADDRESS,
			bool _broadcast=true, RakNet::Time _timeStamp=0, PacketPriority _priority=HIGH_PRIORITY,
			PacketReliability _reliability=RELIABLE_ORDERED, char _orderingChannel=0
			) : networkID(_networkID), systemAddress(_systemAddress), broadcast(_broadcast), timeStamp(_timeStamp), priority(_priority), reliability(_reliability), orderingChannel(_orderingChannel)
		{}
		NetworkID networkID;
		SystemAddress systemAddress;
		bool broadcast;
		RakNet::Time timeStamp;
		PacketPriority priority;
		PacketReliability reliability;
		char orderingChannel;
	};

	/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
	/// Passed parameter(s), if any, are serialized using operator << with RakNet::BitStream. If you provide an overload it will be used, otherwise the seriailzation is equivalent to memcpy except for native RakNet types (NetworkIDObject, SystemAddress, etc.)
	/// If the type is a pointer to a type deriving from NetworkIDObject, then only the NetworkID is sent, and the object looked up on the remote system. Otherwise, the pointer is dereferenced and the contents serialized as usual.
	/// \note The this pointer, for this instance of RPC3, is pushed as the last parameter on the stack. See RPC3Sample.cpp for an example of this
	/// \note If the call fails on the remote system, you will get back ID_RPC_REMOTE_ERROR. packet->data[1] will contain one of the values of RPCErrorCodes. packet->data[2] and on will contain the name of the function.
	/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
	/// \param[in] timeStamp See SetTimestamp()
	/// \param[in] priority See SetSendParams()
	/// \param[in] reliability See SetSendParams()
	/// \param[in] orderingChannel See SetSendParams()
	/// \param[in] systemAddress See SetRecipientAddress()
	/// \param[in] broadcast See SetRecipientAddress()
	/// \param[in] networkID See SetRecipientObject()
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters){
		SetTimestamp(callExplicitParameters->timeStamp);
		SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
		SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
		SetRecipientObject(callExplicitParameters->networkID);
		return Call(uniqueIdentifier);
	}
	template <class P1 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1);
	}
	template <class P1, class P2 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2);
	}
	template <class P1, class P2, class P3 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3);
	}
	template <class P1, class P2, class P3, class P4 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4);
	}
	template <class P1, class P2, class P3, class P4, class P5 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10 >
	bool CallExplicit(const char *uniqueIdentifier, const CallExplicitParameters * const callExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10
		)	{
			SetTimestamp(callExplicitParameters->timeStamp);
			SetSendParams(callExplicitParameters->priority, callExplicitParameters->reliability, callExplicitParameters->orderingChannel);
			SetRecipientAddress(callExplicitParameters->systemAddress, callExplicitParameters->broadcast);
			SetRecipientObject(callExplicitParameters->networkID);
			return Call(uniqueIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
	}

	bool CallC(const char *uniqueIdentifier) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier);}

	template <class P1>
	bool CallC(const char *uniqueIdentifier, P1 &p1) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1);}

	template <class P1, class P2>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2);}

	template <class P1, class P2, class P3>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3);}

	template <class P1, class P2, class P3, class P4>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4);}

	template <class P1, class P2, class P3, class P4, class P5>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5);}

	template <class P1, class P2, class P3, class P4, class P5, class P6>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6);}

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7);}

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8);}

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9);}

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10>
	bool CallC(const char *uniqueIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10) {SetRecipientObject(UNASSIGNED_NETWORK_ID); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10);}

	bool CallCPP(const char *uniqueIdentifier, NetworkID nid) { SetRecipientObject(nid); return Call(uniqueIdentifier); }

	template <class P1>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1); }

	template <class P1, class P2>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2); }

	template <class P1, class P2, class P3>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3); }

	template <class P1, class P2, class P3, class P4>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4); }

	template <class P1, class P2, class P3, class P4, class P5>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5); }

	template <class P1, class P2, class P3, class P4, class P5, class P6>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6); }

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7); }

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8); }

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9) { SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9); }

	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10>
	bool CallCPP(const char *uniqueIdentifier, NetworkID nid, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10)	{ SetRecipientObject(nid); return Call(uniqueIdentifier,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10); }

	// ---------------------------- Signals and slots ----------------------------------

	/// Calls zero or more functions identified by sharedIdentifier.
	/// Uses as send parameters whatever was last passed to SetTimestamp(), SetSendParams(), and SetRecipientAddress()
	/// You can use CallExplicit() instead of Call() to force yourself not to forget to set parameters
	///
	/// See the Call() function for a description of parameters
	///
	/// \param[in] sharedIdentifier parameter of the same name passed to RegisterSlot() on the remote system
	bool Signal(const char *sharedIdentifier){
		RakNet::BitStream bitStream;
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 0, &bitStream, false);
	}
	template <class P1>
	bool Signal(const char *sharedIdentifier, P1 &p1)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 1, &bitStream, false);
	}
	template <class P1, class P2>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 2, &bitStream, false);
	}
	template <class P1, class P2, class P3>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 3, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 4, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 5, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 6, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 7, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 8, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		_RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 9, &bitStream, false);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10>
	bool Signal(const char *sharedIdentifier, P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10)	{
		RakNet::BitStream bitStream;
		_RPC3::SerializeCallParameterBranch<P1>::type::apply(bitStream, p1);
		_RPC3::SerializeCallParameterBranch<P2>::type::apply(bitStream, p2);
		_RPC3::SerializeCallParameterBranch<P3>::type::apply(bitStream, p3);
		_RPC3::SerializeCallParameterBranch<P4>::type::apply(bitStream, p4);
		_RPC3::SerializeCallParameterBranch<P5>::type::apply(bitStream, p5);
		_RPC3::SerializeCallParameterBranch<P6>::type::apply(bitStream, p6);
		_RPC3::SerializeCallParameterBranch<P7>::type::apply(bitStream, p7);
		_RPC3::SerializeCallParameterBranch<P8>::type::apply(bitStream, p8);
		_RPC3::SerializeCallParameterBranch<P9>::type::apply(bitStream, p9);
		_RPC3::SerializeCallParameterBranch<P10>::type::apply(bitStream, p10);
		InvokeSignal(GetLocalSlotIndex(sharedIdentifier), &bitStream, true);
		return SendCallOrSignal(sharedIdentifier, 10, &bitStream, false);
	}

	struct SignalExplicitParameters
	{
		SignalExplicitParameters(
			SystemAddress _systemAddress=RakNet::UNASSIGNED_SYSTEM_ADDRESS,
			bool _broadcast=true, RakNet::Time _timeStamp=0, PacketPriority _priority=HIGH_PRIORITY,
			PacketReliability _reliability=RELIABLE_ORDERED, char _orderingChannel=0
			) : systemAddress(_systemAddress), broadcast(_broadcast), timeStamp(_timeStamp), priority(_priority), reliability(_reliability), orderingChannel(_orderingChannel)
		{}
		SystemAddress systemAddress;
		bool broadcast;
		RakNet::Time timeStamp;
		PacketPriority priority;
		PacketReliability reliability;
		char orderingChannel;
	};

	/// Same as Signal(), but you are forced to specify the remote system parameters
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters){
		SetTimestamp(signalExplicitParameters->timeStamp);
		SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
		SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
		return Signal(sharedIdentifier);
	}
	template <class P1 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1);
	}
	template <class P1, class P2 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2);
	}
	template <class P1, class P2, class P3 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3);
	}
	template <class P1, class P2, class P3, class P4 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4);
	}
	template <class P1, class P2, class P3, class P4, class P5 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5, p6);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5, p6, p7);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5, p6, p7, p8);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9);
	}
	template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class P9, class P10 >
	bool SignalExplicit(const char *sharedIdentifier, const SignalExplicitParameters * const signalExplicitParameters,
		P1 &p1, P2 &p2, P3 &p3, P4 &p4, P5 &p5, P6 &p6, P7 &p7, P8 &p8, P9 &p9, P10 &p10
		)	{
			SetTimestamp(signalExplicitParameters->timeStamp);
			SetSendParams(signalExplicitParameters->priority, signalExplicitParameters->reliability, signalExplicitParameters->orderingChannel);
			SetRecipientAddress(signalExplicitParameters->systemAddress, signalExplicitParameters->broadcast);
			return Signal(sharedIdentifier, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
	}

	// ---------------------------- ALL INTERNAL AFTER HERE ----------------------------

	/// \internal
	/// The RPC identifier, and a pointer to the function
	struct LocalRPCFunction
	{
		LocalRPCFunction() {}
		LocalRPCFunction(_RPC3::FunctionPointer _functionPointer) {functionPointer=_functionPointer;};
//		LocalRPCFunction(RPCIdentifier _identifier, _RPC3::FunctionPointer _functionPointer) {identifier=_identifier; functionPointer=_functionPointer;};
//		RPCIdentifier identifier;
		_RPC3::FunctionPointer functionPointer;
	};

	/// \internal
	/// The RPC identifier, and the index of the function on a remote system
// 	struct RemoteRPCFunction
// 	{
// 		RPCIdentifier identifier;
// 		unsigned int functionIndex;
// 	};
//
// 	/// \internal
// 	static int RemoteRPCFunctionComp( const RPCIdentifier &key, const RemoteRPCFunction &data );

	/// \internal
	/// Sends the RPC call, with a given serialized function
	bool SendCallOrSignal(RakString uniqueIdentifier, char parameterCount, RakNet::BitStream *serializedParameters, bool isCall);

	/// Call a given signal with a bitstream representing the parameter list
	void InvokeSignal(DataStructures::HashIndex functionIndex, RakNet::BitStream *serializedParameters, bool temporarilySetUSA);

	protected:

	// --------------------------------------------------------------------------------------------
	// Packet handling functions
	// --------------------------------------------------------------------------------------------
	void OnAttach(void);
	virtual PluginReceiveResult OnReceive(Packet *packet);
	virtual void OnRPC3Call(const SystemAddress &systemAddress, unsigned char *data, unsigned int lengthInBytes);
//	virtual void OnRPCRemoteIndex(const SystemAddress &systemAddress, unsigned char *data, unsigned int lengthInBytes);
	virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason );
	virtual void OnShutdown(void);

	void Clear(void);

	void SendError(SystemAddress target, unsigned char errorCode, const char *functionName);
	DataStructures::HashIndex GetLocalFunctionIndex(RPCIdentifier identifier);
	DataStructures::HashIndex GetLocalSlotIndex(const char *sharedIdentifier);
//	bool GetRemoteFunctionIndex(const SystemAddress &systemAddress, RPCIdentifier identifier, unsigned int *outerIndex, unsigned int *innerIndex, bool isCall);

	DataStructures::Hash<RakNet::RakString, LocalSlot*,256, RakNet::RakString::ToInteger> localSlots;
	DataStructures::Hash<RakNet::RakString, LocalRPCFunction*,256, RakNet::RakString::ToInteger> localFunctions;

// 	DataStructures::List<LocalSlot*> localSlots;
// 	DataStructures::List<LocalRPCFunction> localFunctions;

//	DataStructures::Map<SystemAddress, DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, RPC3::RemoteRPCFunctionComp> *> remoteFunctions, remoteSlots;
	RakNet::Time outgoingTimestamp;
	PacketPriority outgoingPriority;
	PacketReliability outgoingReliability;
	char outgoingOrderingChannel;
	SystemAddress outgoingSystemAddress;
	bool outgoingBroadcast;
	NetworkID outgoingNetworkID;
	RakNet::BitStream outgoingExtraData;

	RakNet::Time incomingTimeStamp;
	SystemAddress incomingSystemAddress;
	RakNet::BitStream incomingExtraData;

	NetworkIDManager *networkIdManager;
	char currentExecution[512];

	/// Used so slots are called in the order they are registered
	unsigned int nextSlotRegistrationCount;

	bool interruptSignal;

};

} // End namespace

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#endif


text:
    Dependency-free notification library.

    Documentation »

## Hi

**NOTY** is a notification library that makes it easy to create **alert** - **success** - **error** - **warning** - **information** - **confirmation** messages as an alternative the standard alert dialog.

The notifications can be positioned at the;
**top** - **topLeft** - **topCenter** - **topRight** - **center** - **centerLeft** - **centerRight** - **bottom** - **bottomLeft** - **bottomCenter** - **bottomRight**

There are lots of other options in the API to customise the text, animation, buttons and much more.

It also has various callbacks for the buttons, opening closing the notifications and queue control.

***
### Features
- [x] Dependency-free
- [x] Web Push Notifications with Service Worker support
- [x] UMD
- [x] Named queue system
- [x] Has 11 layouts, 5 notification styles, 5+ themes
- [x] Custom container (inline notifications)
- [x] Confirm notifications
- [x] TTL
- [x] Progress bar indicator for timed notifications
- [x] Supports css animations, [animate.css](https://github.com/daneden/animate.css), [mojs](https://github.com/legomushroom/mojs), [bounce.js](https://github.com/tictail/bounce.js), [velocity](https://github.com/julianshapiro/velocity) and other animation libraries
- [x] 2 close options: click, button
- [x] API & Callbacks
- [x] Custom templating
- [x] Document visibility control (blur, focus)

### Documentation
Documentation and examples are here: <http://ned.im/noty>

***

##### Basic Usage
```js
import Noty from 'noty';

new Noty({
    text: 'Notification text'
}).show();

// or

const Noty = require('noty');

new Noty({
    text: 'Notification text'
}).show();

```

##### Development
```console
$ npm run dev
$ npm test
$ npm run build
$ npm run browserstack
$ npm run serve-docs
```

##### Development environment
- [x] Standard
- [x] Prettier
- [x] ES6 & Babel & Webpack
- [x] Sass
- [x] Autoprefixer
- [x] QUnit
- [x] BrowserStack
- [x] Pre-commit tests
- [x] Travis CI

[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

redpajama_set_name: RedPajamaGithub


text:
import { defineQuery } from '../utils/serverGraphqlUtil';
import Migrations from '../../lib/collections/migrations/collection';
import { availableMigrations } from './migrationUtils';
import * as _ from 'underscore';
import moment from 'moment';

defineQuery({
  name: "MigrationsDashboard",
  resultType: "MigrationsDashboardData",
  schema: `
    type MigrationsDashboardData {
      migrations: [MigrationStatus!]
    }
    type MigrationStatus {
      name: String!
      dateWritten: String
      runs: [MigrationRun!]
      lastRun: String
    }
    type MigrationRun {
      name: String!
      started: Date!
      finished: Date
      succeeded: Boolean
    }`,
  fn: async (root: void, args: void, context: ResolverContext) => {
    if (!context.currentUser || !context.currentUser.isAdmin)
      throw new Error("MigrationsDashboard graphQL API requires being logged in as an admin");

    const allMigrationRuns = await Migrations.find({}).fetch();
    const runsByMigration = _.groupBy(allMigrationRuns, m=>m.name);

    const migrationNamesByDateWrittenDesc =
      _.sortBy(
        _.pairs(availableMigrations),
        ([name, {dateWritten}]) => dateWritten
      )
      .reverse()
      .map(([name, migration]) => name);

    return {
      migrations: migrationNamesByDateWrittenDesc
        .map(name => makeMigrationStatus(name, runsByMigration))
    };
  },
});

const makeMigrationStatus = (name: string, runsByMigration) => {
  const runs = runsByMigration[name]?.map(run => ({
    name: run.name,
    started: new Date(run.started),
    finished: run.finished ? new Date(run.finished) : null,
    succeeded: run.succeeded,
  })) || []

  let lastRun = ''
  if (runs.length) {
    const startDates = runs.map(run => run.started)
    lastRun = moment.utc(_.max(startDates)).format('YYYY-MM-DD')
  }

  const result = {
    name,
    dateWritten: availableMigrations[name].dateWritten,
    runs,
    lastRun,
  }
  return result
}


text:
#include <sys/queue.h>
#include "unity.h"

#include "openflow.h"

#include "lagopus_apis.h"
#include "lagopus/dpmgr.h"
#include "lagopus/port.h"
#include "lagopus/vector.h"
#include "lagopus/ofp_dp_apis.h"

void
setUp(void) {
}

void
tearDown(void) {
}

void
test_ports_alloc(void) {
  struct vector *ports;

  ports = ports_alloc();
  TEST_ASSERT_NOT_NULL_MESSAGE(ports, "ports_alloc error");
}

void
test_port_add(void) {
  struct vector *ports;
  struct port port;
  lagopus_result_t rv;

  ports = ports_alloc();
  TEST_ASSERT_NOT_NULL_MESSAGE(ports, "ports_alloc error");

  port.ofp_port.port_no = 1;
  port.ifindex = 120;
  rv = port_add(ports, &port);

  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "port_add error");
}

void
test_port_delete(void) {
  struct vector *ports;
  struct port port;
  lagopus_result_t rv;

  ports = ports_alloc();
  TEST_ASSERT_NOT_NULL_MESSAGE(ports, "ports_alloc error");

  port.ofp_port.port_no = 1;
  port.ifindex = 120;
  rv = port_add(ports, &port);

  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "port_add error");

  rv = port_delete(ports, 5);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_NOT_FOUND, "not found error");
  rv = port_delete(ports, 120);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "port_delete error");
}

void
test_lagopus_get_port_statistics(void) {
  struct vector *ports;
  struct port port;
  struct ofp_port_stats_request req;
  struct port_stats_list list;
  struct ofp_error error;
  lagopus_result_t rv;

  ports = ports_alloc();
  TEST_ASSERT_NOT_NULL_MESSAGE(ports, "ports_alloc error");

  req.port_no = 1;
  TAILQ_INIT(&list);
  rv = lagopus_get_port_statistics(ports, &req, &list, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OFP_ERROR, "result error");

  req.port_no = OFPP_ANY;
  TAILQ_INIT(&list);
  rv = lagopus_get_port_statistics(ports, &req, &list, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "result error");
  TEST_ASSERT_NULL_MESSAGE(TAILQ_FIRST(&list), "empty list error");

  port.ofp_port.port_no = 1;
  port.ifindex = 120;
  rv = port_add(ports, &port);

  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "port_add error");

  req.port_no = OFPP_ANY;
  TAILQ_INIT(&list);
  rv = lagopus_get_port_statistics(ports, &req, &list, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "result error");
  TEST_ASSERT_NOT_NULL_MESSAGE(TAILQ_FIRST(&list), "list error");

  req.port_no = 1;
  TAILQ_INIT(&list);
  rv = lagopus_get_port_statistics(ports, &req, &list, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK, "result error");

  req.port_no = 5;
  TAILQ_INIT(&list);
  rv = lagopus_get_port_statistics(ports, &req, &list, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OFP_ERROR, "result error");
}

void
test_port_config(void) {
  struct port port;
  struct ofp_port_mod port_mod;
  struct ofp_error error;
  struct dpmgr *dpmgr;
  struct bridge *bridge;
  lagopus_result_t rv;

  dpmgr = dpmgr_alloc();
  TEST_ASSERT_NOT_NULL_MESSAGE(dpmgr, "dpmgr alloc error.");
  rv = dpmgr_bridge_add(dpmgr, "br0", 0);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK,
                            "bridge add error");
  memset(&port, 0, sizeof(port));
  port.ofp_port.port_no = 1;
  port.ifindex = 120;
  port.ofp_port.hw_addr[0] = 0xe0;
  port.ofp_port.hw_addr[1] = 0x4d;
  port.ofp_port.hw_addr[2] = 0xff;
  port.ofp_port.hw_addr[3] = 0x00;
  port.ofp_port.hw_addr[4] = 0x10;
  port.ofp_port.hw_addr[5] = 0x04;
  dpmgr_port_add(dpmgr, &port);
  dpmgr_bridge_port_add(dpmgr, "br0", 120, 1);

  bridge = dpmgr_bridge_lookup(dpmgr, "br0");
  port_mod.port_no = 1;
  port_mod.hw_addr[0] = 0xe0;
  port_mod.hw_addr[1] = 0x4d;
  port_mod.hw_addr[2] = 0xff;
  port_mod.hw_addr[3] = 0x00;
  port_mod.hw_addr[4] = 0x10;
  port_mod.hw_addr[5] = 0x04;
  port_mod.config = 0;
  port_mod.mask = 0;
  rv = port_config(bridge, &port_mod, &error);
  TEST_ASSERT_EQUAL_MESSAGE(rv, LAGOPUS_RESULT_OK,
                            "port_config error");
}


text:
class BoundingBox : public BoundingShape {
public:
    BoundingBox(Model*);
    void transform(Eigen::Matrix4f*, float);
    void transformVector(Eigen::Matrix4f*, Eigen::Vector3f*);
    bool intersect(BoundingSphere*);
    float distToPlane(Eigen::Vector3f, Eigen::Vector3f, Eigen::Vector3f, Eigen::Vector3f);
    void addSelf(kdtree*);
    void update(Geometry*);
    void dump();
    void bounce(Eigen::Vector3f*, Eigen::Vector3f*, float);
    Eigen::Vector3f uln,lln,urn,lrn,ulf,llf,urf,lrf;
};

class PlaneCollision {
public:
    Eigen::Vector3f P, A, B, C;
    float d;
    float distToPlane(Eigen::Vector3f p, Eigen::Vector3f A, Eigen::Vector3f B, Eigen::Vector3f C){
        Eigen::Vector3f v = (B - A).cross(C - A);
        v.normalize();
        return -v.dot(p - A);
    };
    Eigen::Vector3f normal(){
        return (B - A).cross(C - A).normalized();
    }
    PlaneCollision(){};
    PlaneCollision(Eigen::Vector3f p, Eigen::Vector3f a, Eigen::Vector3f b, Eigen::Vector3f c){
        P = p;
        A = a;
        B = b;
        C = c;
        d = distToPlane(P, A, B, C);
    };
};

#endif


text:
import os
import re
import subprocess
import platform as platform_module
import tempfile

from xml.etree import ElementTree
from distutils.version import LooseVersion

def launched_by_mistika():
    if os.getppid() == 1:
        return True
    else:
        return False
    process_names = ['mistika', 'mistika.bin']
    parent = subprocess.Popen(['ps', '-o', 'cmd=', str(os.getppid())], stdout=subprocess.PIPE).communicate()[0].strip()
    print 'Parent:', parent
    if parent in process_names:
        return True
    else:
        return False

def get_mistika_bin_pids(parent_pid):
    cmd = ['pstree', '-p', str(parent_pid)]
    pstree = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
    try:
        return [int(pid) for pid in re.findall('mistika.bin\((\d+)\)', pstree)]
    except AttributeError:
        return []

def get_rnd_path(rnd_name):
    for root, dirs, files in os.walk(os.path.join(projects_folder, project, 'DATA/RENDER')):
        for basename in files:
            if basename.startswith(rnd_name) and basename.endswith('.rnd'):
                return os.path.join(root, basename)

def get_mistikarc_path(env_folder, multiple=False):
    mistikarc_paths = [
        env_folder + '/mistikarc.cfg',
        env_folder + '/mistikarc.cfg',
        env_folder + '/.mistikarc',
        env_folder + '/.mambarc',
        env_folder + '/../MAMBA-ENV.config/.mambarc',
    ]
    for path in mistikarc_paths[:]:
        if not os.path.exists(path):
            mistikarc_paths.remove(path)
    if len(mistikarc_paths) == 0:
        print 'Error: mistikarc config not found in %s' % env_folder
        return False
    if multiple:
        return mistikarc_paths
    else:
        return mistikarc_paths[0]

def get_mistika_projects_folder(env_folder, shared_folder, config_name):
    config_path = os.path.join(shared_folder, 'presets', '.mistikarc.'+config_name)
    product_work = '%s_WORK' % product.upper()
    for line in open(config_path):
        if line.startswith(product_work):
            return line.strip().split(' ', 1)[1].strip()
    #legacy
    for line in open(os.path.join(env_folder, product_work)):
        if line.startswith(product_work):
             return line.strip().split(' ', 1)[1].strip()

def reload():
    global env_folder, tools_path, shared_folder, version, project, user, settings, product, projects_folder
    global afterscripts_path
    global fonts_config_path
    global scripts_folder
    global glsl_folder
    global lut_folder
    global fonts
    global fonts_folder
    global platform
    global executable
    product = False
    env_folder = None
    envFolderCandidates = [
        os.path.realpath(os.path.expanduser("~/SGO AppData/Mistika")),
        os.path.realpath(os.path.expanduser("~/MISTIKA-ENV")),
        os.path.realpath(os.path.expanduser("~/MAMBA-ENV")),
    ]
    for envFolderCandidate in envFolderCandidates:
        if os.path.exists(envFolderCandidate):
            env_folder = envFolderCandidate
            product = 'Mistika'
            executable = subprocess.Popen(["which", 'mistika'], stdout=subprocess.PIPE).communicate()[0].splitlines()[0]
            break
    app_folder = env_folder
    appFolderCandidates = [
        os.path.realpath(os.path.expanduser("~/SGO Apps/Mistika Ultima")),
    ]
    for appFolderCandidate in appFolderCandidates:
        if os.path.exists(appFolderCandidate):
            app_folder = appFolderCandidate
    if 'linux' in platform_module.system().lower():
        platform = 'linux'
        fonts_folder = '/usr/share/fonts/mistika/'
    elif 'darwin' in platform_module.system().lower():
        platform = 'mac'
        fonts_folder = os.path.expanduser('~/Library/Fonts/')
    elif 'windows' in platform_module.system().lower():
        platform = 'windows'
        fonts_folder = 'C:/Windows/Fonts/'
    sharedFolderCandidates = [
        os.path.realpath(os.path.expanduser("~/MISTIKA-SHARED")),
    ]
    if env_folder:
      sharedFolderCandidates.append(os.path.join(env_folder, 'shared'))
      shared_folder = os.path.join(env_folder, 'shared')
    for sharedFolderCandidate in sharedFolderCandidates:
        if os.path.exists(sharedFolderCandidate):
            shared_folder = sharedFolderCandidate
    version = None
    try:
        cmd = [executable, '-V']
        versionLines = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
        versionStrings = re.findall(r'Version(?:.*?)((?:\d|\.)+)', versionLines)
        if len(versionStrings):
            version = LooseVersion(versionStrings[0])
    except OSError as e:
        print e
        pass
    print executable, 'version', version
    try:
        version.vstring
    except AttributeError:
        version = LooseVersion('0')
    if version < LooseVersion('8.6'):
        project = open(os.path.join(env_folder, '%s_PRJ' % product.upper())).readline().splitlines()[0]
        user = False
    else:
        try:
            user = ElementTree.parse(os.path.join(shared_folder, "users/login.xml")).getroot().find('autoLogin/lastUser').text
        except:
            user = 'MistikaUser'
        try:
            project = ElementTree.parse(os.path.join(shared_folder, "users/%s/UIvalues.xml" % user)).getroot().find('project/current').text
        except:
            project = 'None'
    mistikarc_path = get_mistikarc_path(env_folder)
    settings = {}
    for line in open(mistikarc_path):
        try:
            key, value = line.strip().split(' ', 1)
        except ValueError:
            continue
        value = value.strip()
        if value.lower() == 'true':
            value = True
        elif value.lower() == 'false':
            value = False
        settings[key] = value
    projects_folder = get_mistika_projects_folder(env_folder, shared_folder, settings['STANDARD'])
    tools_path = os.path.join(shared_folder, 'config/LinuxMistikaTools')
    afterscripts_path = None
    afterscripts_path_candidates = [
        os.path.join(env_folder, 'config/RenderEndScript.cfg'),
        os.path.join(env_folder, 'etc/setup/RenderEndScript.cfg'),
    ]
    for afterscripts_path_candidate in afterscripts_path_candidates:
        if os.path.exists(afterscripts_path_candidate):
            afterscripts_path = afterscripts_path_candidate
        break
    if not afterscripts_path:
        afterscripts_path = afterscripts_path_candidates[0]
    if not os.path.isfile(afterscripts_path):
        try:
            open(afterscripts_path, 'a').write('None')
        except IOError:
            print 'Afterscripts config not available: %s' % afterscripts_path
    scripts_folder = os.path.join(app_folder, 'bin/scripts/')
    if not os.path.exists(scripts_folder):
        bin_folder_mac = '/Applications/SGOMambaFX.app/Contents/MacOS/'
        scripts_folder_mac = '/Applications/SGOMambaFX.app/Contents/MacOS/scripts/'
        if os.path.exists(bin_folder_mac):
            scripts_folder = scripts_folder_mac
    glsl_folder = os.path.join(env_folder, 'etc/GLSL')
    lut_folder = os.path.join(env_folder, 'etc/LUT')
    fonts_config_path = os.path.join(env_folder, 'extern/.fontParseOut')
    fonts = {}
    try:
        for line in open(fonts_config_path):
            font_path, font_name = line.strip().strip('"').split('"   "')
            fonts[font_name] = font_path
    except IOError:
        pass
        #print 'Could not read fonts config: %s' % fonts_config_path

reload()

def set_settings(new_settings):
    print repr(new_settings)
    global settings
    for mistika_settings_file in get_mistikarc_path(env_folder, multiple=True):
        with tempfile.NamedTemporaryFile(delete=False) as temp_handle:
            for line in open(mistika_settings_file):
                key = line.split()[0]
                if key in new_settings:
                    line = key.ljust(31)+str(new_settings[key])+'\n'
                    del new_settings[key]
                temp_handle.write(line)
                # print line,
            for key in new_settings:
                line = key.ljust(31)+str(new_settings[key])+'\n'
                temp_handle.write(line)
            temp_handle.flush()
        os.rename(mistika_settings_file, mistika_settings_file+'.bak')
        os.rename(temp_handle.name, mistika_settings_file)
        settings.update(new_settings)


text:
package users.system.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import users.system.entity.Country;
import users.system.entity.Town;

@Repository
public interface TownRepo extends JpaRepository<Town, Long> {
}


text:
title: "Chris Eppstein & Alan Hogan"
---

Come hang out with us for The Mixin, our 2nd San Francisco [Sass][]
& front-end meet up.

[sass]: http://sass-lang.com

We'll have a couple talks by 2 rad speakers, plus some food and drinks.
Tweeting about this event? Use hashtag: [#themixin][hashtag]

[hashtag]: https://twitter.com/search?q=#themixin

## Presentations
This time, we're excited to have the following talks:

* "**[What's coming in Sass 3.3 + Q&A][presentationA]**"
  by [Chris Eppstein](http://chriseppstein.github.io/), Sass core team member,
  Compass creator
* "**[How Sass can simplify responsive web design][presentationB]**"
  by [Alan Hogan](http://alanhogan.com/), UX researcher/designer/prototyper

[presentationA]: http://sass-3-3-presentation.herokuapp.com
[presentationB]: http://alanhogan.com/how-sass-can-simplify-responsive-web-design

## Event Team
* [Jina](http://jina.me/) & [Hampton Catlin](http://www.hamptoncatlin.com/)
  --- Emcees
* [Moovweb](http://moovweb.com/) --- Host & Sponsor
* Do.com --- Additional Staffing


text:
require File.expand_path("../trackers", __FILE__)
require File.expand_path("../ranks/alexa_us", __FILE__)
require File.expand_path("../ranks/alexa_global", __FILE__)
require File.expand_path("../ranks/alexa_country", __FILE__)
require File.expand_path("../ranks/google", __FILE__)
require File.expand_path('../ranks/moz_rank', __FILE__)
require File.expand_path('../ranks/domain_authority', __FILE__)
require File.expand_path('../ranks/page_authority', __FILE__)

module PageRankr
  class Ranks
    include Trackers

    alias_method :rank_trackers, :site_trackers
  end
end


text:
enum Foo {}
type FooAlias = Foo;

fn main() {
    let u = FooAlias { value: 0 };
    //~^ ERROR expected struct, variant or union type, found enum `Foo` [E0071]
}


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

  angular
    .module('app')
    .config(routeConfig);

  /* @ngInject */
  function routeConfig($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('common', {
        abstract: true,
        url: '',
        templateUrl: 'app/layouts/layout.html'
      })
      .state('common.main', {
        url: '/',
        views: {
          'header@common': {
            templateUrl: 'app/layouts/header/header.tmpl.html',
            controller: 'HeaderController'
          },
          // 'toolbar@common': {
          //   templateUrl: 'app/layouts/toolbar/toolbar.tmpl.html',
          //   controller: 'ToolbarController'
          // },
          'content@common': {
            templateUrl: 'app/common/main/main.tmpl.html',
            controller: 'MainController'
          },
          'footer@common': {
            templateUrl: 'app/layouts/footer/footer.tmpl.html',
            controller: 'FooterController'
          }
        }
      })

      .state('404', {
        url: '/404',
        templateUrl: '404.tmpl.html',
        controllerAs: 'vm',
        controller: function ($state) {
          var vm = this;

        }
      })
      .state('500', {
        url: '/500',
        templateUrl: '500.tmpl.html',
        controllerAs: 'vm',
        controller: function ($state) {
          var vm = this;

        }
      });

    $urlRouterProvider.otherwise('/');
  }

})();


text:
import { Component, Input, ViewEncapsulation } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';
import { Properties } from './../shared/flo.properties';

@Component({
  selector: 'df-property',
  templateUrl: './df.property.component.html',
  encapsulation: ViewEncapsulation.None
})
export class DynamicFormPropertyComponent {

  @Input()
  model : Properties.ControlModel<any>;

  @Input() form: FormGroup;

  constructor() {}

  get types() {
    return Properties.InputType;
  }

  get control() : AbstractControl {
    return this.form.controls[this.model.id];
  }

  get errorData() {
    return (this.model.validation && this.model.validation.errorData ? this.model.validation.errorData : []).map(e => this.control.errors[e.message]);
  }

}


text:
void test01()
{
  // Check for required typedefs
  typedef std::has_trivial_copy_constructor<int>     test_type;
  typedef test_type::value_type               value_type;
  typedef test_type::type                     type;
  typedef test_type::type::value_type         type_value_type;
  typedef test_type::type::type               type_type;
}


text:
#ifndef Page_h
#define Page_h

#include "core/dom/ViewportArguments.h"
#include "core/page/LayoutMilestones.h"
#include "core/page/PageVisibilityState.h"
#include "core/page/UseCounter.h"
#include "core/platform/PlatformScreen.h"
#include "core/platform/Supplementable.h"
#include "core/platform/graphics/LayoutRect.h"
#include "core/platform/graphics/Region.h"
#include "core/rendering/Pagination.h"
#include <wtf/Forward.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/Noncopyable.h>
#include <wtf/text/WTFString.h>

#if OS(SOLARIS)
#include <sys/time.h> // For time_t structure.
#endif

namespace WebCore {

class AutoscrollController;
class BackForwardClient;
class BackForwardController;
class Chrome;
class ChromeClient;
class ClientRectList;
class ContextMenuClient;
class ContextMenuController;
class Document;
class DragCaretController;
class DragClient;
class DragController;
class EditorClient;
class FocusController;
class Frame;
class FrameSelection;
class HaltablePlugin;
class HistoryItem;
class InspectorClient;
class InspectorController;
class Node;
class PageConsole;
class PageGroup;
class PlatformMouseEvent;
class PluginData;
class PointerLockController;
class ProgressTracker;
class Range;
class RenderBox;
class RenderObject;
class RenderTheme;
class VisibleSelection;
class ScrollableArea;
class ScrollingCoordinator;
class Settings;
class StorageNamespace;
class ValidationMessageClient;

typedef uint64_t LinkHash;

float deviceScaleFactor(Frame*);

struct ArenaSize {
    ArenaSize(size_t treeSize, size_t allocated)
        : treeSize(treeSize)
        , allocated(allocated)
    {
    }
    size_t treeSize;
    size_t allocated;
};

class Page : public Supplementable<Page> {
    WTF_MAKE_NONCOPYABLE(Page);
    friend class Settings;
public:
    static void scheduleForcedStyleRecalcForAllPages();

    // It is up to the platform to ensure that non-null clients are provided where required.
    struct PageClients {
        WTF_MAKE_NONCOPYABLE(PageClients); WTF_MAKE_FAST_ALLOCATED;
    public:
        PageClients();
        ~PageClients();

        ChromeClient* chromeClient;
        ContextMenuClient* contextMenuClient;
        EditorClient* editorClient;
        DragClient* dragClient;
        InspectorClient* inspectorClient;
        BackForwardClient* backForwardClient;
    };

    explicit Page(PageClients&);
    ~Page();

    ArenaSize renderTreeSize() const;

    void setNeedsRecalcStyleInAllFrames();

    RenderTheme* theme() const { return m_theme.get(); }

    ViewportArguments viewportArguments() const;

    static void refreshPlugins(bool reload);
    PluginData* pluginData() const;

    EditorClient* editorClient() const { return m_editorClient; }

    void setMainFrame(PassRefPtr<Frame>);
    Frame* mainFrame() const { return m_mainFrame.get(); }

    bool openedByDOM() const;
    void setOpenedByDOM();

    // DEPRECATED. Use backForward() instead of the following 5 functions.
    bool goBack();
    bool goForward();
    void goBackOrForward(int distance);
    int getHistoryLength();

    void goToItem(HistoryItem*);

    // FIXME: InspectorPageGroup is only needed to support single process debugger layout tests, it should be removed when DumpRenderTree is gone.
    enum PageGroupType { InspectorPageGroup, PrivatePageGroup, SharedPageGroup };
    void setGroupType(PageGroupType);
    void clearPageGroup();
    PageGroup& group()
    {
        if (!m_group)
            setGroupType(PrivatePageGroup);
        return *m_group;
    }

    void incrementSubframeCount() { ++m_subframeCount; }
    void decrementSubframeCount() { ASSERT(m_subframeCount); --m_subframeCount; }
    int subframeCount() const { checkSubframeCountConsistency(); return m_subframeCount; }

    Chrome& chrome() const { return *m_chrome; }
    DragCaretController* dragCaretController() const { return m_dragCaretController.get(); }
    DragController* dragController() const { return m_dragController.get(); }
    FocusController* focusController() const { return m_focusController.get(); }
    ContextMenuController* contextMenuController() const { return m_contextMenuController.get(); }
    InspectorController* inspectorController() const { return m_inspectorController.get(); }
    PointerLockController* pointerLockController() const { return m_pointerLockController.get(); }
    ValidationMessageClient* validationMessageClient() const { return m_validationMessageClient; }
    void setValidationMessageClient(ValidationMessageClient* client) { m_validationMessageClient = client; }

    bool autoscrollInProgress() const;
    bool autoscrollInProgress(const RenderBox*) const;
    bool panScrollInProgress() const;
    void startAutoscrollForSelection(RenderObject*);
    void stopAutoscrollIfNeeded(RenderObject*);
    void stopAutoscrollTimer();
    void updateAutoscrollRenderer();
    void updateDragAndDrop(Node* targetNode, const IntPoint& eventPosition, double eventTime);
#if ENABLE(PAN_SCROLLING)
    void handleMouseReleaseForPanScrolling(Frame*, const PlatformMouseEvent&);
    void startPanScrolling(RenderBox*, const IntPoint&);
#endif

    ScrollingCoordinator* scrollingCoordinator();

    String mainThreadScrollingReasonsAsText();
    PassRefPtr<ClientRectList> nonFastScrollableRects(const Frame*);

    Settings* settings() const { return m_settings.get(); }
    ProgressTracker* progress() const { return m_progress.get(); }
    BackForwardController* backForward() const { return m_backForwardController.get(); }

    UseCounter* useCounter() { return &m_UseCounter; }

    void setTabKeyCyclesThroughElements(bool b) { m_tabKeyCyclesThroughElements = b; }
    bool tabKeyCyclesThroughElements() const { return m_tabKeyCyclesThroughElements; }

    void unmarkAllTextMatches();

    void setDefersLoading(bool);
    bool defersLoading() const { return m_defersLoading; }

    void setPageScaleFactor(float scale, const IntPoint& origin);
    float pageScaleFactor() const { return m_pageScaleFactor; }

    float deviceScaleFactor() const { return m_deviceScaleFactor; }
    void setDeviceScaleFactor(float);

    // Page and FrameView both store a Pagination value. Page::pagination() is set only by API,
    // and FrameView::pagination() is set only by CSS. Page::pagination() will affect all
    // FrameViews in the page cache, but FrameView::pagination() only affects the current
    // FrameView.
    const Pagination& pagination() const { return m_pagination; }
    void setPagination(const Pagination&);

    // Notification that this Page was moved into or out of a native window.
    void setIsInWindow(bool);
    bool isInWindow() const { return m_isInWindow; }

    void userStyleSheetLocationChanged();
    const String& userStyleSheet() const;

    void dnsPrefetchingStateChanged();

    static void allVisitedStateChanged(PageGroup*);
    static void visitedStateChanged(PageGroup*, LinkHash visitedHash);

    StorageNamespace* sessionStorage(bool optionalCreate = true);
    void setSessionStorage(PassRefPtr<StorageNamespace>);

    // Don't allow more than a certain number of frames in a page.
    // This seems like a reasonable upper bound, and otherwise mutually
    // recursive frameset pages can quickly bring the program to its knees
    // with exponential growth in the number of frames.
    static const int maxNumberOfFrames = 1000;

    PageVisibilityState visibilityState() const;
    void setVisibilityState(PageVisibilityState, bool);

    bool isCursorVisible() const { return m_isCursorVisible; }
    void setIsCursorVisible(bool isVisible) { m_isCursorVisible = isVisible; }

    void addLayoutMilestones(LayoutMilestones);
    LayoutMilestones layoutMilestones() const { return m_layoutMilestones; }

    bool isCountingRelevantRepaintedObjects() const;
    void startCountingRelevantRepaintedObjects();
    void resetRelevantPaintedObjectCounter();
    void addRelevantRepaintedObject(RenderObject*, const LayoutRect& objectPaintRect);
    void addRelevantUnpaintedObject(RenderObject*, const LayoutRect& objectPaintRect);

#ifndef NDEBUG
    void setIsPainting(bool painting) { m_isPainting = painting; }
    bool isPainting() const { return m_isPainting; }
#endif

    PageConsole* console() { return m_console.get(); }

    void reportMemoryUsage(MemoryObjectInfo*) const;

    double timerAlignmentInterval() const;

    class MultisamplingChangedObserver {
    public:
        virtual void multisamplingChanged(bool) = 0;
    };

    void addMultisamplingChangedObserver(MultisamplingChangedObserver*);
    void removeMultisamplingChangedObserver(MultisamplingChangedObserver*);
    void multisamplingChanged();

private:
    void initGroup();

#if ASSERT_DISABLED
    void checkSubframeCountConsistency() const { }
#else
    void checkSubframeCountConsistency() const;
#endif

    void setTimerAlignmentInterval(double);

    OwnPtr<AutoscrollController> m_autoscrollController;
    OwnPtr<Chrome> m_chrome;
    OwnPtr<DragCaretController> m_dragCaretController;

    OwnPtr<DragController> m_dragController;
    OwnPtr<FocusController> m_focusController;
    OwnPtr<ContextMenuController> m_contextMenuController;
    OwnPtr<InspectorController> m_inspectorController;
    OwnPtr<PointerLockController> m_pointerLockController;
    RefPtr<ScrollingCoordinator> m_scrollingCoordinator;

    OwnPtr<Settings> m_settings;
    OwnPtr<ProgressTracker> m_progress;

    OwnPtr<BackForwardController> m_backForwardController;
    RefPtr<Frame> m_mainFrame;

    mutable RefPtr<PluginData> m_pluginData;

    RefPtr<RenderTheme> m_theme;

    EditorClient* m_editorClient;
    ValidationMessageClient* m_validationMessageClient;

    UseCounter m_UseCounter;

    int m_subframeCount;
    bool m_openedByDOM;

    bool m_tabKeyCyclesThroughElements;
    bool m_defersLoading;
    unsigned m_defersLoadingCallCount;

    float m_pageScaleFactor;
    float m_deviceScaleFactor;

    Pagination m_pagination;

    mutable String m_userStyleSheet;
    mutable bool m_didLoadUserStyleSheet;
    mutable time_t m_userStyleSheetModificationTime;

    RefPtr<PageGroup> m_group;

    RefPtr<StorageNamespace> m_sessionStorage;

    double m_timerAlignmentInterval;

    bool m_isInWindow;

    PageVisibilityState m_visibilityState;

    bool m_isCursorVisible;

    LayoutMilestones m_layoutMilestones;

    HashSet<RenderObject*> m_relevantUnpaintedRenderObjects;
    Region m_topRelevantPaintedRegion;
    Region m_bottomRelevantPaintedRegion;
    Region m_relevantUnpaintedRegion;
    bool m_isCountingRelevantRepaintedObjects;
#ifndef NDEBUG
    bool m_isPainting;
#endif

    const OwnPtr<PageConsole> m_console;

    HashSet<MultisamplingChangedObserver*> m_multisamplingChangedObservers;
};

} // namespace WebCore

#endif // Page_h


text:
package org.apache.juddi.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author Jeff Faath
 * @author Kurt T Stam
 */
@Entity
@Table(name = "j3_transfer_token_keys")
public class TransferTokenKey implements java.io.Serializable {

	private static final long serialVersionUID = 8163650692808546199L;
	private Long id;
	private TransferToken transferToken;
	private String entityKey;

	public TransferTokenKey() {
	}

	public TransferTokenKey(TransferToken transferToken, String entityKey) {
		this.transferToken = transferToken;
		this.entityKey = entityKey;
	}

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Long getId() {
		return this.id;
	}
	public void setId(Long id) {
		this.id = id;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "transfer_token", nullable = false)
	public TransferToken getTransferToken() {
		return this.transferToken;
	}
	public void setTransferToken(TransferToken transferToken) {
		this.transferToken = transferToken;
	}

	@Column(name = "entity_key", length = 255)
	public String getEntityKey() {
		return this.entityKey;
	}
	public void setEntityKey(String entityKey) {
		this.entityKey = entityKey;
	}

}


text:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
var path = require('path');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

var ieCSSPlugin =  new ExtractTextPlugin('assets/css/ie.css', {
            publicPath: 'assets/css/',
            allChunks: true,
            sourceMap: true
        });
var mainCSSPlugin = new ExtractTextPlugin('assets/css/main.css', {
            publicPath: 'assets/css/',
            allChunks: true,
            sourceMap: true
        });

const sassLoaders = [
  'css-loader',
  'sass-loader?indentedSyntax=sass&sourceMap&includePaths[]=' + path.resolve(__dirname, './src')
];

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },

    resolve: {
        extensions: ['', '.js', '.ts']
    },

    module: {
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.html$/,
                loader: 'html'
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file',
                query: {
                    name: 'assets/fonts/[name].[ext]',
                    context: 'src/'
                }
            },
            {
                test: /\ie.scss$/,
                loader: ieCSSPlugin.extract('style-loader', sassLoaders.join('!'))
            },
            {
                test: /\.scss$/, exclude: /\ie.scss$/,
                loader: mainCSSPlugin.extract('style-loader', sassLoaders.join('!'))
            }
        ]
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'src/index.html'
        }),

        new OptimizeCssAssetsPlugin({
          assetNameRegExp: /\.optimize\.css$/g,
          cssProcessor: require('cssnano'),
          cssProcessorOptions: { discardComments: {removeAll: true } },
          canPrint: true
        }),
        ieCSSPlugin,
        mainCSSPlugin
        /*,
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            output: {
            comments: false
            }
        }),
        new UnminifiedWebpackPlugin()*/
    ]
};


text:
package org.springframework.cloud.contract.verifier.builder;

import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;

class WebTestClientResponseWhen implements When, WebTestClientAcceptor {

	private final BlockBuilder blockBuilder;

	private final GeneratedClassMetaData generatedClassMetaData;

	WebTestClientResponseWhen(BlockBuilder blockBuilder, GeneratedClassMetaData metaData) {
		this.blockBuilder = blockBuilder;
		this.generatedClassMetaData = metaData;
	}

	@Override
	public MethodVisitor<When> apply(SingleContractMetadata metadata) {
		this.blockBuilder.addIndented("WebTestClientResponse response = given().spec(request)");
		return this;
	}

	@Override
	public boolean accept(SingleContractMetadata metadata) {
		return acceptType(this.generatedClassMetaData);
	}

}


text:
.. _mixedtutorial:

Mixing seminorms tutorial
~~~~~~~~~~~~~~~~~~~~~~~~~

This tutorial illustrates how to use RegReg to solve problems that have seminorms in both the objective and the contraint. We illustrate with an example:

.. math::

       \frac{1}{2}||y - \beta||^{2}_{2} + \lambda \|\beta\|_1 \text{ subject to} \  ||D\beta||_{1} \leq \delta

with

.. math::

       D = \left(\begin{array}{rrrrrr} -1 & 1 & 0 & 0 & \cdots & 0 \\ 0 & -1 & 1 & 0 & \cdots & 0 \\ &&&&\cdots &\\ 0 &0&0&\cdots & -1 & 1 \end{array}\right)

To solve this problem using RegReg we begin by loading the necessary numerical libraries

.. ipython::

   import numpy as np
   from scipy import sparse
   import regreg.api as rr

Next, let's generate an example signal, and solve the Lagrange form of the problem

.. ipython::

   Y = np.random.standard_normal(500); Y[100:150] += 7; Y[250:300] += 14
   loss = rr.quadratic.shift(-Y, coef=0.5)

   sparsity = rr.l1norm(len(Y), lagrange=1.4)
   # TODO should make a module to compute typical Ds
   D = sparse.csr_matrix((np.identity(500) + np.diag([-1]*499,k=1))[:-1])
   fused = rr.l1norm.linear(D, lagrange=25.5)
   problem = rr.container(loss, sparsity, fused)

   solver = rr.FISTA(problem)
   solver.fit(max_its=100, tol=1e-10)
   solution = solver.composite.coefs

We will now solve this problem in constraint form, using the
achieved  value :math:`\delta = \|D\widehat{\beta}\|_1`.
By default, the container class will try to solve this problem with the two-loop strategy.

.. ipython::

   delta = np.fabs(D * solution).sum()
   sparsity = rr.l1norm(len(Y), lagrange=1.4)
   fused_constraint = rr.l1norm.linear(D, bound=delta)
   constrained_problem = rr.container(loss, fused_constraint, sparsity)
   constrained_solver = rr.FISTA(constrained_problem)
   constrained_solver.composite.lipschitz = 1.01
   vals = constrained_solver.fit(max_its=10, tol=1e-06, backtrack=False, monotonicity_restart=False)
   constrained_solution = constrained_solver.composite.coefs

We can now check that the obtained value matches the constraint,

.. ipython::

   constrained_delta = np.fabs(D * constrained_solution).sum()
   print delta, constrained_delta
   print np.linalg.norm(solution - constrained_solution) / np.linalg.norm(solution)

.. plot:: ./examples/mixedtutorial.py


text:
using System;
using App.Common.Abstarct;
using App.Common.Extensions;

namespace App.CoreV2.Elements
{
    /// <summary>
    /// Класс для описания списка заявлений по оплате по типам служб.
    /// </summary>
    /// <remarks>Соответствует версии 2 для файла с данными об использовании.</remarks>
    public class Declaration : IDeclaration
    {
        /// <summary>
        /// Расчетный период.
        /// </summary>
        /// <remarks>Период потребления ресурса, за который выставляется счет.</remarks>
        public string SettlementPeriod { get; set; }

        /// <summary>
        /// Категория средства измерения.
        /// </summary>
        /// <remarks>Служба верхнего уровня, которая использовалась в течение расчетного периода.</remarks>
        public string Name { get; set; }

        /// <summary>
        /// Подкатегория средства измерения.
        /// </summary>
        /// <remarks>В этом столбце может быть указан тип службы, от которого зависит стоимость ее использования.</remarks>
        public string Type { get; set; }

        /// <summary>
        /// Имя средства измерения.
        /// </summary>
        /// <remarks>Определяет единицу измерения для использованного ресурса.</remarks>
        public string Resource { get; set; }

        /// <summary>
        /// Регион средства измерения.
        /// </summary>
        /// <remarks>В этом столбце указывается расположение центра обработки данных для определенных служб. От этого расположения может зависеть стоимость некоторых услуг.</remarks>
        public string Region { get; set; }

        /// <summary>
        /// SKU.
        /// </summary>
        /// <remarks>В этом столбце указан уникальный системный идентификатор для каждого ресурса Azure.</remarks>
        public string SKU { get; set; }

        /// <summary>
        /// Единица.
        /// </summary>
        /// <remarks>Здесь указываются единицы, в которых измеряется объем использования служб, Например, гигабайты, часы, десятки тысяч.</remarks>
        public string Unit { get; set; }

        /// <summary>
        /// Потребленный объем.
        /// </summary>
        /// <remarks>Здесь указан объем потребленного за расчетный период ресурса.</remarks>
        public string Spent { get; set; }

        /// <summary>
        /// Включенный объем.
        /// </summary>
        /// <remarks>В этом столбце указывается объем ресурса, предоставляемый бесплатно в рамках текущего расчетного периода.</remarks>
        public string Include { get; set; }

        /// <summary>
        /// Избыточный объем.
        /// </summary>
        /// <remarks>Если объем потребленного ресурса превышает включенный объем, в этом столбце отображается разница, которая подлежит оплате. В предложениях, предполагающих оплату по мере использования, здесь будет отображаться потребленный объем, так как в таких тарифных планах включенный объем не предусмотрен.</remarks>
        public string Payable { get; set; }

        /// <summary>
        /// В рамках обязательства.
        /// </summary>
        /// <remarks>В этом столбце отображается стоимость ресурсов, которая вычитается из стоимости вашего плана на 6 или 12 месяцев. Обратите внимание, что стоимость ваших ресурсов вычитается из стоимости вашего плана в хронологическом порядке.</remarks>
        public string AsPartOfACommitment { get; set; }

        /// <summary>
        /// Валюта.
        /// </summary>
        /// <remarks>В этой графе указывается валюта, используемая для текущего расчетного периода.</remarks>
        public string Currency { get; set; }

        /// <summary>
        /// Превышение.
        /// </summary>
        /// <remarks>В этом столбце отображается сумма, на которую стоимость использованных ресурсов превышает стоимость вашего плана на 6 или 12 месяцев.</remarks>
        public string Excess { get; set; }

        /// <summary>
        /// Тариф по обязательствам.
        /// </summary>
        /// <remarks>В этой графе указывается объем обязательств на основе общей стоимости вашего плана на 6 или 12 месяцев.</remarks>
        public string TariffCommitments { get; set; }

        /// <summary>
        /// Тариф.
        /// </summary>
        /// <remarks>В этом столбце отображается стоимость каждой оплачиваемой единицы.</remarks>
        public string Tariff { get; set; }

        /// <summary>
        /// Значение.
        /// </summary>
        /// <remarks>Здесь отображается результат умножения значения в столбце «Подлежит оплате» на значение в столбце «Тариф». Если число в столбце «Потреблено» меньше числа в столбце «Включено», в данном столбце ничего не указывается.</remarks>
        public string Value { get; set; }

        /// <summary>
        /// Инициализация "пустого" объекта.
        /// </summary>
        public Declaration()
        { }

        /// <summary>
        /// Инициализация объекта с данными полученными из разбора строки CSV файла.
        /// </summary>
        /// <param name="data">Массив строк из файла.</param>
        public Declaration(string[] data)
        {
            SettlementPeriod = data[0];
            Name = data[1];
            Type = data[2];
            Resource = data[3];
            Region = data[4];
            SKU = data[5];
            Unit = data[6];
            Spent = data[7];
            Include = data[8];
            Payable = data[9];
            AsPartOfACommitment = data[10];
            Currency = data[11];
            Excess = data[12];
            TariffCommitments = data[13];
            Tariff = data[14];
            Value = data[15];
        }

        public override string ToString()
        {
            return String.Format("Декларация за {0} отчетный период по службе {1}.", SettlementPeriod, Name);
        }

        /// <summary>
        /// Расчет потраченной суммы по декларации.
        /// </summary>
        /// <returns>Возвращает значение суммы, реально потраченной на услугу.</returns>
        public double CalculateSpentValue()
        {
            return Convert.ToDouble(Spent.CorrectDouble())*Convert.ToDouble(Tariff.CorrectDouble());
        }
    }
}


text:
layout: tag-template
title: "Mohmanyang book-review tag"
tag: book-review
---


text:
import os

from ..compat import urlsplit
from ..exceptions import NotSupportedSite
from ..settings import comics_settings, SUPPORTED_SITES

class Downloader(object):
    """
    Downloader is used to detect the specific class to use to download the comic.
    """
    def __init__(self, url):
        self.url = url

    def create_default_folder(self):
        if not os.path.exists(comics_settings.path):
            os.mkdir(comics_settings.path)

    def load_class(self):
        """
        From the domain return the specific class to use to download
        the comics.
        """
        # for example we have http://example.com
        # the netloc part is `example.com`
        domain = urlsplit(self.url).netloc

        if 'www' in domain:
            domain = domain[4:]

        if domain not in SUPPORTED_SITES:
            msg = '{} is not supported yet.'.format(domain)
            raise NotSupportedSite(msg)

        return getattr(comics_settings, domain)

    def run(self):
        klass = self.load_class()
        self.create_default_folder()
        klass(self.url).make_pdf()