text:
// This is a part of the Active Template Library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.

#ifndef __ATLSNAP_H__
#define __ATLSNAP_H__

#pragma once

#ifndef _ATL_NO_PRAGMA_WARNINGS
#pragma warning (push)
#pragma warning(disable: 4702) // unreachable code
#pragma warning(disable: 4127) // conditional expression constant
#endif //!_ATL_NO_PRAGMA_WARNINGS

#include <mmc.h>
#include <commctrl.h>
#include <atlwin.h>

#ifndef _ATL_NO_DEFAULT_LIBS
#pragma comment(lib, "mmc.lib")
#pragma comment(lib, "comctl32.lib")
#endif  // !_ATL_NO_DEFAULT_LIBS

#pragma pack(push,_ATL_PACKING)
namespace ATL
{

template <class T, bool bAutoDelete = true>
class ATL_NO_VTABLE CSnapInPropertyPageImpl :
	public CDialogImplBase
{
public:
	PROPSHEETPAGE m_psp;

	operator PROPSHEETPAGE*()
	{
		return &m_psp;
	}

// Construction
	CSnapInPropertyPageImpl(_In_opt_z_ LPCTSTR lpszTitle = NULL)
	{
		// initialize PROPSHEETPAGE struct
		memset(&m_psp, 0, sizeof(PROPSHEETPAGE));
		m_psp.dwSize = sizeof(PROPSHEETPAGE);
		m_psp.dwFlags = PSP_USECALLBACK;
		m_psp.hInstance = _AtlBaseModule.GetResourceInstance();
		m_psp.pszTemplate = MAKEINTRESOURCE(T::IDD);
		m_psp.pfnDlgProc = (DLGPROC)T::StartDialogProc;
		m_psp.pfnCallback = T::PropPageCallback;
		m_psp.lParam = (LPARAM)this;

		if(lpszTitle != NULL)
		{
			m_psp.pszTitle = lpszTitle;
			m_psp.dwFlags |= PSP_USETITLE;
		}
	}

	static UINT CALLBACK PropPageCallback(
		_In_ HWND hWnd,
		_In_ UINT uMsg,
		_In_ LPPROPSHEETPAGE ppsp)
	{
		UNREFERENCED_PARAMETER(hWnd);
		ATLASSERT(hWnd == NULL);
		if(uMsg == PSPCB_CREATE)
		{
			CDialogImplBase* pPage = (CDialogImplBase*)ppsp->lParam;
			_AtlWinModule.AddCreateWndData(&pPage->m_thunk.cd, pPage);
		}
		if (bAutoDelete && uMsg == PSPCB_RELEASE)
		{
			T* pPage = (T*)ppsp->lParam;
			delete pPage;
		}

		return 1;
	}

	HPROPSHEETPAGE Create()
	{
		ATLASSUME(m_psp.lParam == (LPARAM)this);
		return ::CreatePropertySheetPage(&m_psp);
	}

	BOOL EndDialog(int)
	{
		// do nothing here, calling ::EndDialog will close the whole sheet
		ATLASSERT(FALSE);
		return FALSE;
	}

// Operations
	void CancelToClose()
	{
		ATLASSERT(::IsWindow(m_hWnd));
		ATLASSERT(GetParent() != NULL);

		::SendMessage(GetParent(), PSM_CANCELTOCLOSE, 0, 0L);
	}
	void SetModified(_In_ BOOL bChanged = TRUE)
	{
		ATLASSERT(::IsWindow(m_hWnd));
		ATLASSERT(GetParent() != NULL);

		if(bChanged)
			::SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0L);
		else
			::SendMessage(GetParent(), PSM_UNCHANGED, (WPARAM)m_hWnd, 0L);
	}
	LRESULT QuerySiblings(
		_In_ WPARAM wParam,
		_In_ LPARAM lParam)
	{
		ATLASSERT(::IsWindow(m_hWnd));
		ATLASSERT(GetParent() != NULL);

		return ::SendMessage(GetParent(), PSM_QUERYSIBLINGS, wParam, lParam);
	}

	typedef CSnapInPropertyPageImpl< T, bAutoDelete > thisClass;
	BEGIN_MSG_MAP(thisClass)
		MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
	END_MSG_MAP()

// Message handler
	LRESULT OnNotify(
		_In_ UINT /*uMsg*/,
		_In_ WPARAM /*wParam*/,
		_In_ LPARAM lParam,
		_Inout_ BOOL& bHandled)
	{
		ATLASSERT(::IsWindow(m_hWnd));
		NMHDR* pNMHDR = (NMHDR*)lParam;

		// don't handle messages not from the page/sheet itself
		if(pNMHDR->hwndFrom != m_hWnd && pNMHDR->hwndFrom != ::GetParent(m_hWnd))
		{
			bHandled = FALSE;
			return 1;
		}

		T* pT = (T*)this;
		LRESULT lResult = 0;
		// handle default
		switch(pNMHDR->code)
		{
		case PSN_SETACTIVE:
			lResult = pT->OnSetActive() ? 0 : -1;
			break;
		case PSN_KILLACTIVE:
			lResult = !pT->OnKillActive();
			break;
		case PSN_APPLY:
			lResult = pT->OnApply() ? PSNRET_NOERROR : PSNRET_INVALID_NOCHANGEPAGE;
			break;
		case PSN_RESET:
			pT->OnReset();
			break;
		case PSN_QUERYCANCEL:
			lResult = !pT->OnQueryCancel();
			break;
		case PSN_WIZNEXT:
			lResult = !pT->OnWizardNext();
			break;
		case PSN_WIZBACK:
			lResult = !pT->OnWizardBack();
			break;
		case PSN_WIZFINISH:
			lResult = !pT->OnWizardFinish();
			break;
		case PSN_HELP:
			lResult = pT->OnHelp();
			break;
		default:
			bHandled = FALSE;	// not handled
		}

		return lResult;
	}

// Overridables
	BOOL OnSetActive()
	{
		return TRUE;
	}
	BOOL OnKillActive()
	{
		return TRUE;
	}
	BOOL OnApply()
	{
		return TRUE;
	}
	void OnReset()
	{
	}
	BOOL OnQueryCancel()
	{
		return TRUE;    // ok to cancel
	}
	BOOL OnWizardBack()
	{
		return TRUE;
	}
	BOOL OnWizardNext()
	{
		return TRUE;
	}
	BOOL OnWizardFinish()
	{
		return TRUE;
	}
	BOOL OnHelp()
	{
		return TRUE;
	}
};

class CSnapInItem;
class CSnapInObjectRootBase;

class CObjectData
{
public:
	CSnapInItem* m_pItem;
	DATA_OBJECT_TYPES m_type;
};

class ATL_NO_VTABLE CSnapInItem
{
public:
	virtual ~CSnapInItem()
	{
	}
	STDMETHOD(Notify)(
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param,
		_Inout_opt_ IComponentData* pComponentData,
		_Inout_opt_ IComponent* pComponent,
		_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(GetScopePaneInfo)(_Out_ SCOPEDATAITEM *pScopeDataItem) = 0;

	STDMETHOD(GetResultViewType)(
		_Deref_out_z_ LPOLESTR *ppViewType,
		_Out_ long *pViewOptions) = 0;

	STDMETHOD(GetResultPaneInfo)(_Out_ RESULTDATAITEM *pResultDataItem) = 0;

	STDMETHOD(AddMenuItems)(
		_In_ LPCONTEXTMENUCALLBACK piCallback,
		_Inout_ long  *pInsertionAllowed,
		_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(Command)(
		_In_ long lCommandID,
		_Inout_ CSnapInObjectRootBase* pObj,
		_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(CreatePropertyPages)(
		_In_ LPPROPERTYSHEETCALLBACK lpProvider,
		_In_ LONG_PTR handle,
		_Inout_ IUnknown* pUnk,
		_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(QueryPagesFor)(_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(SetControlbar)(
		_Inout_ IControlbar  *pControlbar,
		_Inout_opt_ IExtendControlbar  *pExtendControlbar,
		_Inout_ CSimpleMap<UINT, IUnknown*>* pToolbarMap) = 0;

	STDMETHOD(ControlbarNotify)(
		_Inout_ IControlbar *pControlbar,
		_Inout_opt_ IExtendControlbar *pExtendControlbar,
		_Inout_ CSimpleMap<UINT, IUnknown*>* pToolbarMap,
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param,
		_Inout_ CSnapInObjectRootBase* pObj,
		_In_ DATA_OBJECT_TYPES type) = 0;

	STDMETHOD(GetScopeData)(_Deref_out_ SCOPEDATAITEM  **pScopeDataItem) = 0;

	STDMETHOD(GetResultData)(_Deref_out_ RESULTDATAITEM  **pResultDataItem) = 0;

	STDMETHOD(FillData)(
		_In_ CLIPFORMAT cf,
		_Inout_ LPSTREAM pStream) = 0;

	virtual void InitDataClass(
		_Inout_opt_ IDataObject* /*pDataObject*/,
		_Inout_opt_ CSnapInItem* /*pDefault*/)
	{
		ATLASSERT(0 && "Override this function in derived class");
	}

	static HRESULT GetDataClass(
		_Inout_ IDataObject* pDataObj,
		_Deref_out_opt_ _Deref_post_opt_bytecount_x_(sizeof(CSnapInItem)) CSnapInItem** ppItem,
		_Out_ DATA_OBJECT_TYPES* pType)
	{
		if (ppItem == NULL)
			return E_POINTER;
		if (pType == NULL)
			return E_POINTER;

		if (IS_SPECIAL_DATAOBJECT(pDataObj))
		{
			ATLTRACENOTIMPL(_T("CSnapInItem::GetDataClass"));
		}

		*ppItem = NULL;
		*pType = CCT_UNINITIALIZED;

		STGMEDIUM stgmedium = { TYMED_HGLOBAL, NULL };
		FORMATETC formatetc = { m_CCF_SNAPIN_GETOBJECTDATA,
			NULL,
			DVASPECT_CONTENT,
			-1,
			TYMED_HGLOBAL
		};

		stgmedium.hGlobal = GlobalAlloc(0, sizeof(CObjectData));
		if (stgmedium.hGlobal == NULL)
			return E_OUTOFMEMORY;

		HRESULT hr = pDataObj->GetDataHere(&formatetc, &stgmedium);
		if (SUCCEEDED(hr))
		{
			CObjectData* pData = (CObjectData*)stgmedium.hGlobal;
			 *ppItem = pData->m_pItem;
			 *pType = pData->m_type;
		}

		GlobalFree(stgmedium.hGlobal);

		return hr;
	}

	virtual HRESULT STDMETHODCALLTYPE GetDataObject(
		_Deref_out_ IDataObject** pDataObj,
		_In_ DATA_OBJECT_TYPES type) = 0;

	static void Init()
	{
		m_CCF_NODETYPE			= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_NODETYPE"));
		m_CCF_SZNODETYPE		= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_SZNODETYPE"));
		m_CCF_DISPLAY_NAME		= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_DISPLAY_NAME"));
		m_CCF_SNAPIN_CLASSID	= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_SNAPIN_CLASSID"));
		m_CCF_SNAPIN_GETOBJECTDATA	= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_GETOBJECTDATA"));
		m_CCF_MMC_MULTISELECT_DATAOBJECT	= (CLIPFORMAT) RegisterClipboardFormat(_T("CCF_MMC_MULTISELECT_DATAOBJECT"));
	}
public:
	static CLIPFORMAT m_CCF_NODETYPE;
	static CLIPFORMAT m_CCF_SZNODETYPE;
	static CLIPFORMAT m_CCF_DISPLAY_NAME;
	static CLIPFORMAT m_CCF_SNAPIN_CLASSID;
	static CLIPFORMAT m_CCF_SNAPIN_GETOBJECTDATA;
	static CLIPFORMAT m_CCF_MMC_MULTISELECT_DATAOBJECT;
};

class CSnapInObjectRootBase
{
public:
	CComPtr <IControlbar> m_spControlbar;
	CSimpleMap <UINT, IUnknown*> m_toolbarMap;
	const int m_nType;

	CSnapInObjectRootBase(_In_ int n = 0) : m_nType(n)
	{
	}
ATLPREFAST_SUPPRESS(6387)
	HRESULT GetDataClass(
		_In_ IDataObject* pDataObject,
		_Deref_out_ CSnapInItem** ppItem,
		_Out_ DATA_OBJECT_TYPES* pType)
	{
		return CSnapInItem::GetDataClass(pDataObject, ppItem, pType);
	}
ATLPREFAST_UNSUPPRESS()
};

template <int n, class ComponentData>
class CSnapInObjectRoot :
	public CSnapInObjectRootBase
{
public :
	CSnapInObjectRoot() : CSnapInObjectRootBase(n)
	{
		m_pComponentData = NULL;
	}
	ComponentData* m_pComponentData;
};

#define EXTENSION_SNAPIN_DATACLASS(dataClass) dataClass m_##dataClass;

#define BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP(classname) \
	HRESULT GetDataClass( \
		_In_ IDataObject* pDataObject, \
		_Deref_out_ ATL::CSnapInItem** ppItem, \
		_Out_ DATA_OBJECT_TYPES* pType) \
	{ \
		if (ppItem == NULL) \
			return E_POINTER; \
		if (pType == NULL) \
			return E_POINTER; \
\
		*ppItem = NULL; \
\
		*pType = CCT_UNINITIALIZED; \
\
		STGMEDIUM stgmedium = { TYMED_HGLOBAL, NULL }; \
		FORMATETC formatetc = { ATL::CSnapInItem::m_CCF_NODETYPE, \
			NULL, \
			DVASPECT_CONTENT, \
			-1, \
			TYMED_HGLOBAL \
		}; \
\
		stgmedium.hGlobal = GlobalAlloc(0, sizeof(GUID)); \
		if (stgmedium.hGlobal == NULL) \
			return E_OUTOFMEMORY; \
\
		HRESULT hr = pDataObject->GetDataHere(&formatetc, &stgmedium); \
		if (FAILED(hr)) \
		{ \
			GlobalFree(stgmedium.hGlobal); \
			return hr; \
		} \
\
		GUID guid; \
		Checked::memcpy_s(&guid, sizeof(GUID), stgmedium.hGlobal, sizeof(GUID)); \
\
		GlobalFree(stgmedium.hGlobal); \
		hr = S_OK;

#define EXTENSION_SNAPIN_NODEINFO_ENTRY(dataClass) \
		if (IsEqualGUID(guid, *(GUID*)m_##dataClass.GetNodeType())) \
		{ \
			*ppItem = m_##dataClass.GetExtNodeObject(pDataObject, &m_##dataClass); \
			ATLASSERT(*ppItem != NULL); \
			(*ppItem)->InitDataClass(pDataObject, &m_##dataClass); \
			return hr; \
		}

#define END_EXTENSION_SNAPIN_NODEINFO_MAP() \
			return ATL::CSnapInItem::GetDataClass(pDataObject, ppItem, pType); \
	};

class ATL_NO_VTABLE CSnapInDataObjectImpl :
	public IDataObject,
	public CComObjectRoot
{
public:
	virtual ~CSnapInDataObjectImpl()
	{
	}
	BEGIN_COM_MAP(CSnapInDataObjectImpl)
		COM_INTERFACE_ENTRY(IDataObject)
	END_COM_MAP()
	STDMETHOD(GetData)(
		_In_opt_ FORMATETC * /*pformatetcIn*/,
		_In_opt_ STGMEDIUM * /*pmedium*/)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::GetData\n"));
	}

	STDMETHOD(GetDataHere)(
		_In_ FORMATETC* pformatetc,
		_In_ STGMEDIUM* pmedium)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("SnapInDataObjectImpl::GetDataHere\n"));
		if (pmedium == NULL)
			return E_POINTER;

		HRESULT hr = DV_E_TYMED;
		// Make sure the type medium is HGLOBAL
		if (pmedium->tymed == TYMED_HGLOBAL)
		{
			// Create the stream on the hGlobal passed in
			CComPtr<IStream> spStream;
			hr = CreateStreamOnHGlobal(pmedium->hGlobal, FALSE, &spStream);
			if (SUCCEEDED(hr))
				if (pformatetc->cfFormat == CSnapInItem::m_CCF_SNAPIN_GETOBJECTDATA)
				{
					hr = DV_E_CLIPFORMAT;
					ULONG uWritten;
					hr = spStream->Write(&m_objectData, sizeof(CObjectData), &uWritten);
				}
				else
					hr = m_objectData.m_pItem->FillData(pformatetc->cfFormat, spStream);
		}
		return hr;
	}

	STDMETHOD(QueryGetData)(_In_opt_ FORMATETC* /* pformatetc */)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::QueryGetData\n"));
	}
	STDMETHOD(GetCanonicalFormatEtc)(
		_In_opt_ FORMATETC* /* pformatectIn */,
		_In_opt_ FORMATETC* /* pformatetcOut */)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::GetCanonicalFormatEtc\n"));
	}
	STDMETHOD(SetData)(
		_In_opt_ FORMATETC* /* pformatetc */,
		_In_opt_ STGMEDIUM* /* pmedium */,
		_In_ BOOL /* fRelease */)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::SetData\n"));
	}
	STDMETHOD(EnumFormatEtc)(
		_In_ DWORD /* dwDirection */,
		_In_ IEnumFORMATETC** /* ppenumFormatEtc */)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::EnumFormatEtc\n"));
	}
	STDMETHOD(DAdvise)(
		_In_opt_ FORMATETC * /*pformatetc*/,
		_In_ DWORD /*advf*/,
		_Inout_opt_ IAdviseSink * /*pAdvSink*/,
		_Out_opt_ DWORD* /*pdwConnection*/)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::SetData\n"));
	}
	STDMETHOD(DUnadvise)(_In_ DWORD /*dwConnection*/)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::SetDatan\n"));
	}
	STDMETHOD(EnumDAdvise)(_In_ IEnumSTATDATA ** /*ppenumAdvise*/)
	{
		ATLTRACENOTIMPL(_T("SnapInDataObjectImpl::SetData\n"));
	}

	CObjectData m_objectData;
};

template <class T, class Component>
class ATL_NO_VTABLE IComponentDataImpl :
	public IComponentData
{
public :
	IComponentDataImpl()
	{
		m_pNode = NULL;
	}

	STDMETHOD(Initialize)(_Inout_ LPUNKNOWN pUnknown)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::Initialize\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pUnknown != NULL);
		if (pUnknown == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::Initialize called with pUnknown == NULL\n"));
		else
		{
			hr = pUnknown->QueryInterface(&m_spConsole);
			if (FAILED(hr))
				ATLTRACE(atlTraceSnapin, 0, _T("QI for IConsole failed\n"));
		}

		return hr;
	}

	STDMETHOD(CreateComponent)(_Deref_out_ LPCOMPONENT *ppComponent)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::CreateComponent\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(ppComponent != NULL);
		if (ppComponent == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::CreateComponent called with ppComponent == NULL\n"));
		else
		{
			*ppComponent = NULL;

			CComObject< Component >* pComponent;
			hr = CComObject< Component >::CreateInstance(&pComponent);
			ATLASSUME(SUCCEEDED(hr));
			if (FAILED(hr))
				ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::CreateComponent : Could not create IComponent object\n"));
			else
			{
				pComponent->m_pComponentData = static_cast<T*>(this);
				hr = pComponent->QueryInterface(__uuidof(IComponent), (void**)ppComponent);
			}
		}
		return hr;
	}

	STDMETHOD(Notify)(
		_Inout_ LPDATAOBJECT lpDataObject,
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::Notify\n"));
		ATLASSERT(lpDataObject != NULL && _T("Override Notify in derived class handle notifications for which lpDataObject == NULL"));
		HRESULT hr = E_POINTER;

		ATLASSERT(lpDataObject != NULL);
		if (lpDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::Notify called with lpDataObject == NULL\n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			hr = pT->m_pComponentData->GetDataClass(lpDataObject, &pItem, &type);
			ATLASSERT(SUCCEEDED(hr));
			if (SUCCEEDED(hr))
			{
				hr = pItem->Notify(event, arg, param, pT, NULL, type);
			}
		}
		return hr;
	}

	STDMETHOD(Destroy)(void)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::Destroy\n"));

		T* pT = static_cast<T*>(this);
		if (pT->m_spControlbar != NULL)
		{
			int n = pT->m_toolbarMap.GetSize();
			for (int i = 0; i < n; i++)
			{
				IToolbar* pToolbar = (IToolbar*)pT->m_toolbarMap.GetValueAt(i);
				 if (pToolbar != NULL)
				 {
					pT->m_spControlbar->Detach(pToolbar);
					pToolbar->Release();
				 }
			}
		}
		pT->m_toolbarMap.RemoveAll();

		m_spConsole.Release();
		return S_OK;
	}

	STDMETHOD(QueryDataObject)(
		_In_ LONG_PTR cookie,
		_In_ DATA_OBJECT_TYPES type,
		_Deref_out_ LPDATAOBJECT *ppDataObject)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::QueryDataObject\n"));
		HRESULT hr = E_POINTER;

		ATLASSERT(ppDataObject != NULL);
		if (ppDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::QueryDataObject called with ppDataObject == NULL\n"));
		else
		{
			*ppDataObject = NULL;

			CSnapInItem* pItem = (CSnapInItem*) cookie;
			if (cookie == NULL)
				pItem = m_pNode;

			hr = pItem->GetDataObject(ppDataObject, type);
		}
		return hr;
	}

	STDMETHOD(GetDisplayInfo)(_Inout_ SCOPEDATAITEM *pScopeDataItem)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentDataImpl::GetDisplayInfo\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pScopeDataItem != NULL);
		if (pScopeDataItem == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponentData::GetDisplayInfo called with pScopeDataItem == NULL\n"));
		else
		{
			CSnapInItem* pItem= (CSnapInItem*) pScopeDataItem->lParam;
			if (pItem == NULL)
				pItem = m_pNode;

			hr = E_UNEXPECTED;
			if (pItem != NULL)
				hr = pItem->GetScopePaneInfo(pScopeDataItem);
		}
		return hr;
	}

	STDMETHOD(CompareObjects)(
		_In_opt_ LPDATAOBJECT /*lpDataObjectA*/,
		_In_opt_ LPDATAOBJECT /*lpDataObjectB*/)
	{
		ATLTRACENOTIMPL(_T("IComponentDataImpl::CompareObjects\n"));
	}

	CComPtr<IConsole> m_spConsole;
	CSnapInItem* m_pNode;
};

template <class T>
class ATL_NO_VTABLE IComponentImpl :
	public IComponent
{
public:
	STDMETHOD(Initialize)(_Inout_ LPCONSOLE lpConsole)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::Initialize\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(lpConsole != NULL);
		if (lpConsole == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("lpConsole is NULL\n"));
		else
		{
			m_spConsole = lpConsole;

			CComPtr<IHeaderCtrl> spHeaderCtrl;
			hr = m_spConsole.QueryInterface(&spHeaderCtrl);
			if (FAILED(hr))
				ATLTRACE(atlTraceSnapin, 0, _T("QI for IHeaderCtrl failed\n"));
			else
			{
				hr = m_spConsole->SetHeader(spHeaderCtrl);
				if (FAILED(hr))
					ATLTRACE(atlTraceSnapin, 0, _T("IConsole::SetHeader failed (HRESULT = %x)\n"), hr);
			}
		}
		return hr;
	}

	STDMETHOD(Notify)(
		_Inout_ LPDATAOBJECT lpDataObject,
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::Notify\n"));
		ATLASSERT(lpDataObject != NULL && _T("Override Notify in derived class handle notifications for which lpDataObject == NULL"));
		HRESULT hr = E_POINTER;

		if (lpDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IComponent::Notify called with lpDataObject==NULL \n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			// Make sure that the object is derived from CSnapInObjectRoot
			hr = pT->m_pComponentData->GetDataClass(lpDataObject, &pItem, &type);
			if (SUCCEEDED(hr))
			{
				hr = pItem->Notify(event, arg, param, NULL, pT, type);
			}
		}
		return hr;
	}

	STDMETHOD(Destroy)(_In_ LONG_PTR /*cookie*/)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::Destroy\n"));

		T* pT = static_cast<T*>(this);

		if (pT->m_spControlbar != NULL)
		{
			int n = pT->m_toolbarMap.GetSize();
			for (int i = 0; i < n; i++)
			{
				IToolbar* pToolbar = (IToolbar*)pT->m_toolbarMap.GetValueAt(i);
				 if (pToolbar != NULL)
				 {
					pT->m_spControlbar->Detach(pToolbar);
					pToolbar->Release();
				 }
			}
		}
		pT->m_toolbarMap.RemoveAll();

		m_spConsole->SetHeader(NULL);
		m_spConsole.Release();
		return S_OK;
	}

	STDMETHOD(QueryDataObject)(
		_In_ LONG_PTR cookie,
		_In_ DATA_OBJECT_TYPES type,
		_Deref_out_ LPDATAOBJECT *ppDataObject)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::QueryDataObject\n"));

		ATLASSERT(ppDataObject != NULL);
		if (ppDataObject == NULL)
		{
			ATLTRACE(atlTraceSnapin, 0, _T("IComponent::QueryDataObject called with ppDataObject==NULL \n"));
			return E_POINTER;
		}

		if (cookie == NULL)
		{
			ATLTRACE(atlTraceSnapin, 0, _T("IComponent::QueryDataObject called with cookie==NULL \n"));
			return E_UNEXPECTED;
		}

		*ppDataObject = NULL;
		if (cookie == MMC_MULTI_SELECT_COOKIE)
		{
			ATLTRACE(atlTraceSnapin, 0, _T("Override QueryDataObject to handle multiselect\n"));
			return E_UNEXPECTED;
		}

		CSnapInItem* pItem = (CSnapInItem*) cookie;
		return pItem->GetDataObject(ppDataObject, type);
	}

	STDMETHOD(GetResultViewType)(
		_In_ LONG_PTR cookie,
		_Deref_out_z_ LPOLESTR *ppViewType,
		_Out_ long *pViewOptions)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::GetResultViewType\n"));

		HRESULT hr = E_FAIL;
		if (cookie == NULL)
		{
			T* pT = static_cast<T*> (this);
			ATLENSURE_RETURN( pT->m_pComponentData != NULL );
			ATLENSURE_RETURN( pT->m_pComponentData->m_pNode != NULL );
			hr = pT->m_pComponentData->m_pNode->GetResultViewType(ppViewType, pViewOptions);
		}
		else
		{
			CSnapInItem* pItem = (CSnapInItem*)cookie;
			hr = pItem->GetResultViewType(ppViewType, pViewOptions);
		}
		return hr;
	}

	STDMETHOD(GetDisplayInfo)(_Inout_ RESULTDATAITEM *pResultDataItem)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IComponentImpl::GetDisplayInfo\n"));

		ATLASSERT(pResultDataItem != NULL);
		if (pResultDataItem == NULL)
		{
			ATLTRACE(atlTraceSnapin, 0, _T("IComponent::GetDisplayInfo called with pResultDataItem==NULL\n"));
			return E_POINTER;
		}

		CSnapInItem* pItem = (CSnapInItem*) pResultDataItem->lParam;

		if (pItem == NULL)
		{
			ATLTRACE(atlTraceSnapin, 0, _T("Invalid Item\n"));
			return E_UNEXPECTED;
		}
		return pItem->GetResultPaneInfo(pResultDataItem);
	}

	STDMETHOD(CompareObjects)(
		_In_opt_ LPDATAOBJECT /*lpDataObjectA*/,
		_In_opt_ LPDATAOBJECT /*lpDataObjectB*/)
	{
		ATLTRACENOTIMPL(_T("IComponentImpl::CompareObjects\n"));
	}

	CComPtr<IConsole> m_spConsole;
};

template <class T, class D>
class ATL_NO_VTABLE IResultDataCompareImpl :
	public IResultDataCompare
{
public:
	STDMETHOD(Compare)(long /*lUserParam*/,
		_In_ long /*cookieA*/,
		_In_ long /*cookieB*/,
		_In_opt_ int* /*pnResult*/)
	{
		ATLTRACENOTIMPL(_T("IResultDataCompareImpl::Compare"));
	}
};

template <class T>
class ATL_NO_VTABLE IExtendContextMenuImpl :
	public IExtendContextMenu
{
public:
	STDMETHOD(AddMenuItems)(
		_Inout_ LPDATAOBJECT pDataObject,
		_In_ LPCONTEXTMENUCALLBACK piCallback,
		_Inout_ long *pInsertionAllowed)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendContextMenuImpl::AddMenuItems\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pDataObject != NULL);
		if (pDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IExtendContextMenu::AddMenuItems called with pDataObject==NULL\n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			hr = pT->m_pComponentData->GetDataClass(pDataObject, &pItem, &type);

			if (SUCCEEDED(hr))
			{
				hr = pItem->AddMenuItems(piCallback, pInsertionAllowed, type);
			}
		}
		return hr;
	}

	STDMETHOD(Command)(
		_In_ long lCommandID,
		_Inout_ LPDATAOBJECT pDataObject)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendContextMenuImpl::Command\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pDataObject != NULL);
		if (pDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IExtendContextMenu::Command called with pDataObject==NULL\n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			hr = pT->m_pComponentData->GetDataClass(pDataObject, &pItem, &type);

			if (SUCCEEDED(hr))
			{
				hr = pItem->Command(lCommandID, (CSnapInObjectRootBase*)pT, type);
			}
		}
		return hr;
	}
};

template<class T>
class ATL_NO_VTABLE IExtendPropertySheetImpl :
	public IExtendPropertySheet
{
public:
	STDMETHOD(CreatePropertyPages)(
		_In_ LPPROPERTYSHEETCALLBACK lpProvider,
		_In_ LONG_PTR handle,
		_Inout_ LPDATAOBJECT pDataObject)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendPropertySheetImpl::CreatePropertyPages\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pDataObject != NULL);
		if (pDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IExtendPropertySheetImpl::CreatePropertyPages called with pDataObject==NULL\n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			hr = pT->m_pComponentData->GetDataClass(pDataObject, &pItem, &type);

			if (SUCCEEDED(hr))
			{
				hr = pItem->CreatePropertyPages(lpProvider, handle, this, type);
			}
		}

		return hr;
	}

	STDMETHOD(QueryPagesFor)(_Inout_ LPDATAOBJECT pDataObject)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendPropertySheetImpl::QueryPagesFor\n"));

		HRESULT hr = E_POINTER;

		ATLASSERT(pDataObject != NULL);
		if (pDataObject == NULL)
			ATLTRACE(atlTraceSnapin, 0, _T("IExtendPropertySheetImpl::QueryPagesFor called with pDataObject==NULL\n"));
		else
		{
			T* pT = static_cast<T*>(this);
			CSnapInItem* pItem;
			DATA_OBJECT_TYPES type;
			hr = pT->m_pComponentData->GetDataClass(pDataObject, &pItem, &type);

			if (SUCCEEDED(hr))
			{
				hr = pItem->QueryPagesFor(type);
			}
		}
		return hr;
	}
};

template <class T>
class ATL_NO_VTABLE IExtendControlbarImpl :
	public IExtendControlbar
{
public:
	STDMETHOD(SetControlbar)(_In_opt_ LPCONTROLBAR pControlbar)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendControlbarImpl::SetControlbar\n"));
		T* pT = static_cast<T*>(this);

		if (pT->m_spControlbar != NULL)
		{
			int n = pT->m_toolbarMap.GetSize();
			for (int i = 0; i < n; i++)
			{
				IToolbar* pToolbar = (IToolbar*)pT->m_toolbarMap.GetValueAt(i);
				 if (pToolbar != NULL)
				 {
					pT->m_spControlbar->Detach(pToolbar);
					pToolbar->Release();
				 }
			}
		}
		pT->m_toolbarMap.RemoveAll();

		pT->m_spControlbar = pControlbar;
		return S_OK;
	}

	STDMETHOD(ControlbarNotify)(
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("IExtendControlbarImpl::ControlbarNotify\n"));

		CSnapInItem* pItem = NULL;
		DATA_OBJECT_TYPES type = CCT_UNINITIALIZED;
		HRESULT hr = S_FALSE;
		T* pT = static_cast<T*>(this);

		if (event == MMCN_BTN_CLICK)
			hr = pT->m_pComponentData->GetDataClass((IDataObject*) arg, &pItem, &type);
		else if (event == MMCN_SELECT)
		{
			hr = pT->m_pComponentData->GetDataClass((IDataObject*) param, &pItem, &type);
			const BOOL bSelect = (BOOL) HIWORD (arg);
			if (bSelect)
			{
				int n = pT->m_toolbarMap.GetSize();
				for (int i = 0; i < n; i++)
				{
					IToolbar* pToolbar = (IToolbar*)pT->m_toolbarMap.GetValueAt(i);
					 if (pToolbar != NULL)
						pT->m_spControlbar->Detach(pToolbar);
				}
			}
		}

		if (SUCCEEDED(hr) && pItem != NULL)
			hr = pItem->ControlbarNotify(pT->m_spControlbar, this, &(pT->m_toolbarMap), event, arg, param, (CSnapInObjectRootBase*) pT, type);

		return hr;
	}
};

#define SNAPINMENUID(id) \
public: \
	static const UINT GetMenuID() \
	{ \
		static const UINT IDMENU = id; \
		return id; \
	}

#define EXT_SNAPINMENUID(id) \
public: \
	static const UINT GetMenuID() \
	{ \
		static const UINT IDMENU = id; \
		return id; \
	}

#define BEGIN_SNAPINCOMMAND_MAP(theClass, bIsExtension) \
	HRESULT ProcessCommand(UINT nID, \
		_Out_ bool& bHandled, \
		_In_opt_ ATL::CSnapInObjectRootBase* pObj, \
		_In_ DATA_OBJECT_TYPES type) \
	{ \
			bHandled = true; \
			HRESULT hr = S_OK;

#define SNAPINCOMMAND_ENTRY(id, func) \
		if (id == nID) \
		{ \
			hr = func(bHandled, pObj); \
			if (bHandled) \
				return hr; \
		}

#define SNAPINCOMMAND_RANGE_ENTRY(id1, id2, func) \
		if (nID >= id1 && nID <= id2) \
		{ \
			hr = func(nID, bHandled, pObj); \
			if (bHandled) \
				return hr; \
		}

#define CHAIN_SNAPINCOMMAND_MAP(theChainClass) \
	{ \
		hr = theChainClass::ProcessCommand(nID, bHandled, pObj, type); \
		if (bHandled) \
			return hr; \
	}

#define END_SNAPINCOMMAND_MAP() \
			return hr; \
	}

struct CSnapInToolBarData
{
	WORD wVersion;
	WORD wWidth;
	WORD wHeight;
	WORD wItemCount;
	//WORD aItems[wItemCount]

	WORD* items()
	{
		return (WORD*)(this+1);
	}
};

#define RT_TOOLBAR  MAKEINTRESOURCE(241)

class CSnapInToolbarInfo
{
public:
	void __stdcall CleanUp(_In_ DWORD_PTR /*dw*/)
	{
		if (m_pStrToolTip)
		{
			for (UINT i = 0; i < m_nButtonCount; i++)
			{
				delete m_pStrToolTip[i];
				m_pStrToolTip[i] = NULL;
			}
			delete [] m_pStrToolTip;
			m_pStrToolTip = NULL;
		}

		if (m_pStrButtonText)
		{
			for (UINT i = 0; i < m_nButtonCount; i++)
			{
				delete m_pStrButtonText[i];
				m_pStrButtonText[i] = NULL;
			}

			delete [] m_pStrButtonText;
			m_pStrButtonText = NULL;
		}
		if (m_pnButtonID)
		{
			delete m_pnButtonID;
			m_pnButtonID = NULL;
		}

		m_nButtonCount = 0;
	}

	OLECHAR** m_pStrToolTip;
	OLECHAR** m_pStrButtonText;
	UINT* m_pnButtonID;
	UINT m_idToolbar;
	UINT m_nButtonCount;
};

#define BEGIN_SNAPINTOOLBARID_MAP(theClass) \
public: \
	static ATL::CSnapInToolbarInfo* GetToolbarInfo() \
	{ \
		static ATL::CSnapInToolbarInfo m_toolbarInfo[] = \
		{

#define SNAPINTOOLBARID_ENTRY(id) \
			{ NULL, NULL, NULL, id, 0},

#define END_SNAPINTOOLBARID_MAP() \
			{ NULL, NULL, NULL, 0, 0} \
		}; \
		return m_toolbarInfo; \
	}

template <class T, BOOL bIsExtension = FALSE>
class ATL_NO_VTABLE CSnapInItemImpl :
	public CSnapInItem
{
public:
	CSnapInItemImpl()
	{
	}

	virtual ~CSnapInItemImpl()
	{
	}

public:

	STDMETHOD(Notify)(
		_In_ MMC_NOTIFY_TYPE /*event*/,
		_In_ LONG_PTR /*arg*/,
		_In_ LONG_PTR /*param*/,
		_Inout_opt_ IComponentData* /*pComponentData*/,
		_Inout_opt_ IComponent* /*pComponent*/,
		_In_ DATA_OBJECT_TYPES /*type*/)
	{
		ATLASSERT("Override Function in Derived Class");
		ATLTRACENOTIMPL(_T("CSnapInItemImpl::Notify"));
	}

	STDMETHOD(GetScopePaneInfo)(_In_ SCOPEDATAITEM * /*pScopeDataItem*/)
	{
		ATLTRACENOTIMPL(_T("CSnapInItemImpl::GetScopePaneInfo"));
	}

	STDMETHOD(GetResultViewType)(
		_Deref_out_opt_z_ LPOLESTR *ppViewType,
		_Out_ long *pViewOptions)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("CSnapInItemImpl::GetResultViewType\n"));
		*ppViewType = NULL;
		*pViewOptions = MMC_VIEW_OPTIONS_NONE;
		return S_FALSE;
	}

	STDMETHOD(GetResultPaneInfo)(_In_opt_ RESULTDATAITEM * /*pResultDataItem*/)
	{
		ATLTRACENOTIMPL(_T("CSnapInItemImpl::GetResultPaneInfo"));
	}

	STDMETHOD(AddMenuItems)(
		_In_ LPCONTEXTMENUCALLBACK piCallback,
		_Inout_ long *pInsertionAllowed,
		_In_ DATA_OBJECT_TYPES /*type*/)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("CSnapInItemImpl::AddMenuItems\n"));
		T* pT = static_cast<T*>(this);

		if (!bIsExtension)
			pT->SetMenuInsertionFlags(true, pInsertionAllowed);

		UINT menuID = pT->GetMenuID();
		if (menuID == 0)
			return S_OK;

		HMENU hMenu = LoadMenu(_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(menuID));
		long insertionID;
		if (hMenu)
		{
			USES_CONVERSION_EX;

			for (int i = 0; 1; i++)
			{
				HMENU hSubMenu = GetSubMenu(hMenu, i);
				if (hSubMenu == NULL)
					break;

				MENUITEMINFO menuItemInfo;
				memset(&menuItemInfo, 0, sizeof(menuItemInfo));
				menuItemInfo.cbSize = sizeof(menuItemInfo);

				switch (i)
				{
				case 0:
					if (! (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) )
						continue;
					insertionID = CCM_INSERTIONPOINTID_PRIMARY_TOP;
					break;

				case 1:
					if (! (*pInsertionAllowed & CCM_INSERTIONALLOWED_NEW) )
						continue;
					if (bIsExtension)
						insertionID = CCM_INSERTIONPOINTID_3RDPARTY_NEW;
					else
						insertionID = CCM_INSERTIONPOINTID_PRIMARY_NEW;
					break;

				case 2:;
					if (! (*pInsertionAllowed & CCM_INSERTIONALLOWED_TASK) )
						continue;
					if (bIsExtension)
						insertionID = CCM_INSERTIONPOINTID_3RDPARTY_TASK;
					else
						insertionID = CCM_INSERTIONPOINTID_PRIMARY_TASK;
					break;
				case 3:;
					if (! (*pInsertionAllowed & CCM_INSERTIONALLOWED_VIEW) )
						continue;
					insertionID = CCM_INSERTIONPOINTID_PRIMARY_VIEW;
					break;
				default:
					{
						insertionID = 0;
						continue;
					}
					break;
				}

				menuItemInfo.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID;
				menuItemInfo.fType = MFT_STRING;
				TCHAR szMenuText[128];

				for (int j = 0; 1; j++)
				{
					menuItemInfo.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID;
					menuItemInfo.fType = MFT_STRING;
					menuItemInfo.cch = 128;
					menuItemInfo.dwTypeData = szMenuText;
					TCHAR szStatusBar[256];

					if (!GetMenuItemInfo(hSubMenu, j, TRUE, &menuItemInfo))
						break;
					if (menuItemInfo.fType != MFT_STRING)
						continue;

					/* force termination -- should be unnecessary because we check return from GetMenuItemInfo */
					szMenuText[_countof(szMenuText)-1]=_T('\0');

					pT->UpdateMenuState(menuItemInfo.wID, szMenuText, &menuItemInfo.fState);
					LoadString(_AtlBaseModule.GetResourceInstance(), menuItemInfo.wID, szStatusBar, 256);

					OLECHAR wszStatusBar[256];
					OLECHAR wszMenuText[128];
					if(!ocscpy_s(wszMenuText, _countof(wszMenuText), CT2COLE(szMenuText)) ||
						!ocscpy_s(wszStatusBar, _countof(wszStatusBar), CT2COLE (szStatusBar)))
					{
						return E_FAIL;
					}

					CONTEXTMENUITEM contextMenuItem;
					contextMenuItem.strName = wszMenuText;
					contextMenuItem.strStatusBarText = wszStatusBar;
					contextMenuItem.lCommandID = menuItemInfo.wID;
					contextMenuItem.lInsertionPointID = insertionID;
					contextMenuItem.fFlags = menuItemInfo.fState;
					contextMenuItem.fSpecialFlags = 0;

					HRESULT hr = piCallback->AddItem(&contextMenuItem);
					DBG_UNREFERENCED_LOCAL_VARIABLE(hr);
					ATLASSERT(SUCCEEDED(hr));
				}
			}
			DestroyMenu(hMenu);
		}

		if (!bIsExtension)
			pT->SetMenuInsertionFlags(true, pInsertionAllowed);

		return S_OK;
	}

	STDMETHOD(Command)(
		_In_ long lCommandID,
		_Inout_opt_ CSnapInObjectRootBase* pObj,
		_In_ DATA_OBJECT_TYPES type)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("CSnapInItemImpl::Command\n"));
		bool bHandled = false;
		T* pT = static_cast<T*>(this);
		return pT->ProcessCommand(lCommandID, bHandled, pObj, type);
	}

	STDMETHOD(CreatePropertyPages)(
		_In_ LPPROPERTYSHEETCALLBACK /*lpProvider*/,
		_In_ LONG_PTR /*handle*/,
		_Inout_opt_ IUnknown* /*pUnk*/,
		_In_ DATA_OBJECT_TYPES /*type*/)
	{
		ATLASSERT("Override Function in Derived Class");
		ATLTRACENOTIMPL(_T("CSnapInItemImpl::CreatePropertyPages"));
	}

	STDMETHOD(QueryPagesFor)(_In_ DATA_OBJECT_TYPES /*type*/)
	{
		ATLASSERT("Override Function in Derived Class");
		ATLTRACENOTIMPL(_T("CSnapInItemImpl::QueryPagesFor"));
	}

	STDMETHOD(SetControlbar)(
		_Inout_ IControlbar *pControlbar,
		_Inout_opt_ IExtendControlbar* pExtendControlBar,
		_Inout_ CSimpleMap<UINT, IUnknown*>* pToolbarMap)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("CSnapInItemImpl::SetControlbar\n"));
		static bool m_bAddTermFunc = false;
		if (!m_bAddTermFunc)
		{
			m_bAddTermFunc = true;
			_pAtlModule->AddTermFunc(CleanUpToolbarInfo, 0);
		}

		T* pT = static_cast<T*>(this);

		CSnapInToolbarInfo* pInfo = pT->GetToolbarInfo();
		if (pInfo == NULL)
			return S_OK;

		USES_CONVERSION_EX;
		for( ; pInfo->m_idToolbar; pInfo++)
		{
			IToolbar* p = (IToolbar*) pToolbarMap->Lookup(pInfo->m_idToolbar);
			if (p != NULL)
				continue;

			HBITMAP hBitmap = LoadBitmap(_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(pInfo->m_idToolbar));
			if (hBitmap == NULL)
				return E_FAIL;

			HRSRC hRsrc = ::FindResource(_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(pInfo->m_idToolbar), RT_TOOLBAR);
			if (hRsrc == NULL)
				return E_FAIL;

			HGLOBAL hGlobal = LoadResource(_AtlBaseModule.GetResourceInstance(), hRsrc);
			if (hGlobal == NULL)
				return E_FAIL;

			CSnapInToolBarData* pData = (CSnapInToolBarData*)LockResource(hGlobal);
			if (pData == NULL)
				return E_FAIL;
			ATLASSERT(pData->wVersion == 1);
			ATLASSERT(pData->wWidth == 16);
			ATLASSERT(pData->wHeight == 16);

			int nButtonCount = pData->wItemCount;
			if (pInfo->m_pnButtonID == NULL)
				ATLTRY(pInfo->m_pnButtonID = new UINT[nButtonCount]);
			pInfo->m_nButtonCount=nButtonCount;

			if (pInfo->m_pnButtonID == NULL)
				continue;

			CAutoVectorPtr<MMCBUTTON> pButtons;
			if (!pButtons.Allocate(pData->wItemCount))
			{
				delete []pInfo->m_pnButtonID;
				pInfo->m_pnButtonID=NULL;
				continue;
			}

			if (pInfo->m_pStrToolTip == NULL)
			{
				ATLTRY(pInfo->m_pStrToolTip = new OLECHAR* [pData->wItemCount]);
				if (pInfo->m_pStrToolTip)
					memset(pInfo->m_pStrToolTip, 0, sizeof(OLECHAR*) * pData->wItemCount);
			}

			if (pInfo->m_pStrToolTip == NULL)
			{
				delete []pInfo->m_pnButtonID;
				pInfo->m_pnButtonID=NULL;
				continue;
			}

			for (int i = 0, j = 0; i < pData->wItemCount; i++)
			{
				pInfo->m_pnButtonID[i] = pButtons[i].idCommand = pData->items()[i];
				if (pButtons[i].idCommand)
				{
					pButtons[i].nBitmap = j++;
					// get the statusbar string and allow modification of the button state
					TCHAR szStatusBar[512];
					LoadString(_AtlBaseModule.GetResourceInstance(), pButtons[i].idCommand, szStatusBar, 512);

					if (pInfo->m_pStrToolTip[i] == NULL)
					{
						ATLTRY(pInfo->m_pStrToolTip[i] = new OLECHAR[lstrlen(szStatusBar) + 1]);
					}
					if (pInfo->m_pStrToolTip[i] == NULL)
						continue;
					if(!ocscpy_s(pInfo->m_pStrToolTip[i], (lstrlen(szStatusBar) + 1), CT2COLE(szStatusBar)))
					{
						return E_FAIL;
					}
					pButtons[i].lpTooltipText = pInfo->m_pStrToolTip[i];
					pButtons[i].lpButtonText = OLESTR("");
					pButtons[i].fsState = TBSTATE_ENABLED;
					pButtons[i].fsType = TBSTYLE_BUTTON;
					pT->SetToolbarButtonInfo(pButtons[i].idCommand, &pButtons[i].fsState, &pButtons[i].fsType);
				}
				else
				{
					pButtons[i].lpTooltipText = OLESTR("");
					pButtons[i].lpButtonText = OLESTR("");
					pButtons[i].fsType = TBSTYLE_SEP;
					pButtons[i].fsState = 0;
				}
			}

			CComPtr<IToolbar> pToolbar;
			HRESULT hr = pControlbar->Create(TOOLBAR, pExtendControlBar, reinterpret_cast<LPUNKNOWN*>(&pToolbar));
			if (SUCCEEDED(hr))
			{
				hr = pToolbar->AddBitmap(pData->wItemCount, hBitmap, pData->wWidth, pData->wHeight, RGB(192, 192, 192));
				if (SUCCEEDED(hr))
				{
					hr = pToolbar->AddButtons(pData->wItemCount, pButtons);
					if (SUCCEEDED(hr))
					{
						pToolbarMap->Add(pInfo->m_idToolbar, pToolbar);
					}
				}
			}
		}
		return S_OK;
	}

	STDMETHOD(ControlbarNotify)(
		_Inout_ IControlbar *pControlbar,
		_Inout_opt_ IExtendControlbar *pExtendControlbar,
		_Inout_ CSimpleMap<UINT, IUnknown*>* pToolbarMap,
		_In_ MMC_NOTIFY_TYPE event,
		_In_ LONG_PTR arg,
		_In_ LONG_PTR param,
		_Inout_opt_ CSnapInObjectRootBase* pObj,
		_In_ DATA_OBJECT_TYPES type)
	{
		ATLTRACE(atlTraceSnapin, 2, _T("CSnapInItemImpl::ControlbarNotify\n"));
		T* pT = static_cast<T*>(this);

		SetControlbar(pControlbar, pExtendControlbar, pToolbarMap);

		if(event == MMCN_SELECT)
		{
			if (pControlbar == NULL)
				return S_OK;

			BOOL bSelect = (BOOL) HIWORD (arg);

			CSnapInToolbarInfo* pInfo = pT->GetToolbarInfo();
			if (pInfo == NULL)
				return S_OK;

			for(; pInfo->m_idToolbar; pInfo++)
			{
				IToolbar* pToolbar = (IToolbar*)pToolbarMap->Lookup(pInfo->m_idToolbar);
				if (pToolbar == NULL)
					continue;
				if (bSelect)
					pControlbar->Attach(TOOLBAR, pToolbar);
				for (UINT i = 0; i < pInfo->m_nButtonCount; i++)
				{
					if (pInfo->m_pnButtonID[i])
					{
						BOOL bEnable;
						if (bSelect)
							bEnable = pT->UpdateToolbarButton(pInfo->m_pnButtonID[i],
								ENABLED);
						else
							bEnable = FALSE;

						pToolbar->SetButtonState(pInfo->m_pnButtonID[i],
							ENABLED, bEnable
							);
						pToolbar->SetButtonState(pInfo->m_pnButtonID[i],
							CHECKED,
							pT->UpdateToolbarButton(pInfo->m_pnButtonID[i],
								CHECKED));
						pToolbar->SetButtonState(pInfo->m_pnButtonID[i],
							HIDDEN,
							pT->UpdateToolbarButton(pInfo->m_pnButtonID[i],
								HIDDEN));
						pToolbar->SetButtonState(pInfo->m_pnButtonID[i],
							INDETERMINATE,
							pT->UpdateToolbarButton(pInfo->m_pnButtonID[i],
								INDETERMINATE));
						pToolbar->SetButtonState(pInfo->m_pnButtonID[i],
							BUTTONPRESSED,
							pT->UpdateToolbarButton(pInfo->m_pnButtonID[i],
								BUTTONPRESSED));
					}
				}
			}
			return S_OK;
		}
		else if (event == MMCN_BTN_CLICK)
		{
			bool bHandled;
			return pT->ProcessCommand((UINT) param, bHandled, pObj, type);
		}

		return E_UNEXPECTED;
	}

	STDMETHOD(GetScopeData)(_Deref_out_ SCOPEDATAITEM **pScopeDataItem)
	{
		if (pScopeDataItem == NULL)
			return E_FAIL;

		*pScopeDataItem = &m_scopeDataItem;
		return S_OK;
	}

	STDMETHOD(GetResultData)(_Deref_out_ RESULTDATAITEM **pResultDataItem)
	{
		if (pResultDataItem == NULL)
			return E_FAIL;

		*pResultDataItem = &m_resultDataItem;
		return S_OK;
	}

ATLPREFAST_SUPPRESS(6387)
	STDMETHOD(GetDataObject)(
		_Deref_out_ IDataObject** pDataObj,
		_In_ DATA_OBJECT_TYPES type)
	{
		ATLASSERT(pDataObj != NULL);
		if (pDataObj == NULL)
			return E_POINTER;
		*pDataObj = NULL;

		CComObject<CSnapInDataObjectImpl>* pData;
		HRESULT hr = CComObject<CSnapInDataObjectImpl>::CreateInstance(&pData);
		if (FAILED(hr))
			return hr;

		T* pT = static_cast<T*> (this);
		pData->m_objectData.m_pItem = pT;
		pData->m_objectData.m_type = type;

		hr = pData->QueryInterface(__uuidof(IDataObject), (void**)(pDataObj));
		return hr;
	}
ATLPREFAST_UNSUPPRESS()

	void UpdateMenuState(
		_In_ UINT /*id*/,
		_In_opt_z_ LPTSTR /*pBuf*/,
		_In_opt_ UINT * /*flags*/)
	{
		return;
	}

	void SetToolbarButtonInfo(
		_In_ UINT /*id*/,
		_Out_ BYTE *pfsState,
		_Out_ BYTE *pfsType)
	{
		*pfsState = TBSTATE_ENABLED;
		*pfsType = TBSTYLE_BUTTON;
	}

	BOOL UpdateToolbarButton(
		_In_ UINT /*id*/,
		_In_ BYTE fsState)
	{
		if (fsState == ENABLED)
			return TRUE;
		return FALSE;
	}

	HRESULT ProcessCommand(
		_In_ UINT nID,
		_In_ bool& /*bHandled*/,
		_In_opt_ CSnapInObjectRootBase* /*pObj*/,
		_In_ DATA_OBJECT_TYPES /*type*/)
	{
		UNREFERENCED_PARAMETER(nID);
		ATLTRACE(atlTraceSnapin, 2, _T("No handler for item with ID %d\n"), nID);
		return S_OK;
	}

	STDMETHOD (FillData)(
		_In_ CLIPFORMAT cf,
		_Inout_ LPSTREAM pStream)
	{
		HRESULT hr = DV_E_CLIPFORMAT;
		ULONG uWritten;

		T* pT = static_cast<T*> (this);

		if (cf == m_CCF_NODETYPE)
		{
			hr = pStream->Write(pT->GetNodeType(), sizeof(GUID), &uWritten);
			return hr;
		}

		if (cf == m_CCF_SZNODETYPE)
		{
			hr = pStream->Write(pT->GetSZNodeType(), (ocslen((OLECHAR*)pT->GetSZNodeType()) + 1 )* sizeof(OLECHAR), &uWritten);
			return hr;
		}

		if (cf == m_CCF_DISPLAY_NAME)
		{
			hr = pStream->Write(pT->GetDisplayName(), (ocslen((OLECHAR*)pT->GetDisplayName()) + 1) * sizeof(OLECHAR), &uWritten);
			return hr;
		}

		if (cf == m_CCF_SNAPIN_CLASSID)
		{
			hr = pStream->Write(pT->GetSnapInCLSID(), sizeof(GUID), &uWritten);
			return hr;
		}

		return hr;
	}

	static CSnapInToolbarInfo* GetToolbarInfo()
	{
		return NULL;
	}

	static void _stdcall CleanUpToolbarInfo(_In_ DWORD_PTR dw)
	{
		for (CSnapInToolbarInfo* pInfo = T::GetToolbarInfo(); pInfo->m_idToolbar != 0; pInfo++)
		{
			pInfo->CleanUp(dw);
		}
	}

	static const UINT GetMenuID()
	{
		return 0;
	}

	void SetMenuInsertionFlags(
		_In_ bool /*bBeforeInsertion*/,
		_In_opt_ long* /*pInsertionAllowed*/)
	{
	}

	void* GetNodeType()
	{
		return (void*)T::m_NODETYPE;
	}
	void* GetSZNodeType()
	{
		return (void*)T::m_SZNODETYPE;
	}

	void* GetDisplayName()
	{
		return (void*)T::m_SZDISPLAY_NAME;
	}

	void* GetSnapInCLSID()
	{
		return (void*)T::m_SNAPIN_CLASSID;
	}

	CComBSTR m_bstrDisplayName;
	SCOPEDATAITEM m_scopeDataItem;
	RESULTDATAITEM m_resultDataItem;
};

_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_NODETYPE = 0;
_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_SZNODETYPE = 0;
_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_DISPLAY_NAME = 0;
_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_SNAPIN_CLASSID = 0;
_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_SNAPIN_GETOBJECTDATA = 0;
_declspec( selectany ) CLIPFORMAT CSnapInItem::m_CCF_MMC_MULTISELECT_DATAOBJECT = 0;

}; //namespace ATL

#pragma pack(pop)
#ifndef _ATL_NO_PRAGMA_WARNINGS
#pragma warning (pop)
#endif //!_ATL_NO_PRAGMA_WARNINGS

#endif //__ATLSNAP_H__


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

  <title>Container</title>

  <script type="text/javascript" src="../../../../../../dojo-1.3.1/dojo/dojo.js" djConfig="isDebug: true, parseOnLoad: true"></script>
  <script type="text/javascript">
    dojo.require("doh.runner");
    dojo.require("dojo.parser");

    dojo.addOnLoad(function(){
      doh.register("alwayssucceed",
        [
          function assertTrueTest() {
        	   doh.assertTrue(true);
          }
        ]
      );
      doh.run();
    });
  </script>
</head>
<body class="tundra">
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
void register_vector_less__osgViewer_scope_Scene_ptr___greater__class();

#endif//vector_less__osgViewer_scope_Scene_ptr___greater__hpp__pyplusplus_wrapper


text:
package org.hawkular.feedcomm.ws.server;

import java.util.HashMap;
import java.util.Map;

import org.hawkular.feedcomm.ws.command.Command;

/**
 * Contains commands that are valid for a particular endpoint to execute.
 * This is here mainly to have a "put" method that returns this object so a valid commands map
 * can be created by chaining "put" calls.
 */
public class ValidCommandsMap {
    private Map<String, Class<? extends Command<?, ?>>> validCommands = new HashMap<>();

    public ValidCommandsMap() {
    }

    public ValidCommandsMap put(String commandName, Class<? extends Command<?, ?>> command) {
        validCommands.put(commandName, command);
        return this;
    }

    public Class<? extends Command<?, ?>> get(String commandName) {
        return validCommands.get(commandName);
    }
}


text:
"""
The template processor class interface.
"""

__version__='$Revision: 11 $'[11:-2]
__author__ = "Duan Guoqiang (mattgduan@gmail.com)"

# template imports
from TemplateException import TemplateException

##############################################
#          CLASS: TemplateProcessor
##############################################

class TemplateProcessor:
    """ Fill the template with data and process it.

        This class is the abstract class of all template processor classes.
    """

    def __init__(self):
        """ Constructor.
        """
        pass

    def set(self, var, value):
        """ Associate a value with top-level template variable or loop.
        """
        raise TemplateException, "TemplateProcessor.set() method must be " + \
                                 "overwrited by subclass for model specific" + \
                                 "data structures!"

    def setdict(self, dict):
        """ Associate dictionary values with top-level template variables.
        """
        raise TemplateException, "TemplateProcessor.setdict() method must be " + \
                                 "overwrited by subclass for model specific" + \
                                 "data structures!"

    def reset(self, keep_data=0):
        """ Reset the template data.
        """
        raise TemplateException, "TemplateProcessor.reset() method must be " + \
                                 "overwrited by subclass for model specific" + \
                                 "data structures!"

    def process(self, template, part=None):
        """ Process a compiled template. Return the result as string.
        """
        raise TemplateException, "TemplateProcessor.process() method must be " + \
                                 "overwrited by subclass for model specific" + \
                                 "template object!"


text:
<?php

/**
 * PHP version 7.0
 *
 * Class WC_Retailcrm_Order_Payment - Build payments for CRM order.
 *
 * @category Integration
 * @author   RetailCRM <integration@retailcrm.ru>
 * @license  http://retailcrm.ru Proprietary
 * @link     http://retailcrm.ru
 * @see      http://help.retailcrm.ru
 */
class WC_Retailcrm_Order_Payment extends WC_Retailcrm_Abstracts_Data
{
    /** @var array  */
    protected $data = [
        'type'       => '',
        'order'      => [],
        'externalId' => '',
    ];

    /** @var bool */
    public $isNew = true;

    /**
     * @var array
     */
    protected $settings = [];

    /**
     * WC_Retailcrm_Order_Item constructor.
     *
     * @param array $settings
     */
    public function __construct($settings)
    {
        $this->settings = $settings;
    }

    /**
     * @param WC_Order $order
     * @param mixed $externalId
     *
     * @return self
     */
    public function build($order, $externalId = false)
    {
        $this->resetData();

        $paymentData = [];

        if (!$this->isNew) {
            $paymentData['externalId'] = $externalId;
        } else {
            $paymentData['externalId'] = uniqid($order->get_id() . '-');
        }

        $paymentData['order'] = [
            'externalId' => $order->get_id()
        ];

        if ($order->is_paid()) {
            if ($order->get_status() != 'completed' && $order->get_payment_method() == 'cod') {
                writeBaseLogs(
                    implode(
                        ' ',
                        [
                            'Payment for order: ' . $order->get_id(),
                            'Payment status cannot be changed as it is cash (or other payment method) on delivery.',
                            'The status will be changed when the order is in status completed.',
                        ]
                    )
                );
            } else {
                $paymentData['status'] = 'paid';

                if (isset($this->settings[$order->get_payment_method()])) {
                    $paymentData['type'] = $this->settings[$order->get_payment_method()];
                }

                $paidAt = $order->get_date_paid();

                if (!empty($paidAt)) {
                    $paymentData['paidAt'] = $paidAt->date('Y-m-d H:i:s');
                }
            }
        }

        if ($this->isNew) {
            if (isset($this->settings[$order->get_payment_method()])) {
                $paymentData['type'] = $this->settings[$order->get_payment_method()];
            } else {
                $paymentData = [];
            }
        }

        $paymentData = apply_filters(
            'retailcrm_process_payment',
            WC_Retailcrm_Plugin::clearArray($paymentData),
            $order
        );

        $this->setDataFields($paymentData);

        return $this;
    }

    /**
     * Returns false if payment doesn't have method
     *
     * @return array
     */
    public function getData()
    {
        $data = parent::getData();

        if (empty($data['type'])) {
            return [];
        }

        // Need to clear the array from empty values
        return array_filter($data);
    }

    public function resetData()
    {
        $this->data = [
            'externalId' => '',
            'type' => '',
            'status' => '',
            'paidAt' => '',
            'order' => []
        ];
    }
}


text:
var gridOptions = {
    columnDefs: [
        { field: 'country', rowGroup: true },
        { field: 'year', rowGroup: true },
        { field: 'sport' },
        { field: 'athlete' },
        { field: 'total' }
    ],
    defaultColDef: {
        flex: 1,
        minWidth: 100,
        filter: true,
        sortable: true,
        resizable: true,
    },
    autoGroupColumnDef: {
        minWidth: 200,
    },
    enableRangeSelection: true,
    animateRows: true,
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
        .then(function(data) {
            gridOptions.api.setRowData(data);
        });
});


text:
package net.bhardy.braintree.scala

import net.bhardy.braintree.scala.util.NodeWrapper

class Customer(node: NodeWrapper) {
  val id = node.findString("id")
  val firstName = node.findString("first-name")
  val lastName = node.findString("last-name")
  val company = node.findString("company")
  val email = node.findString("email")
  val fax = node.findString("fax")
  val phone = node.findString("phone")
  val website = node.findString("website")
  val createdAt = node.findDateTime("created-at")
  val updatedAt = node.findDateTime("updated-at")
  val customFields = node.findMap("custom-fields/*")
  val creditCards = node.findAll("credit-cards/credit-card").map {
    creditCardResponse => new CreditCard(creditCardResponse)
  }

  val addresses = node.findAll("addresses/address").map {
    addressResponse => new Address(addressResponse)
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/alin/StudioProjects/PracticalTest02Var01/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.1.1/res/values-w500dp-v13/values.xml -->
    <eat-comment/>
    <integer name="abc_max_action_buttons">4</integer>
</resources>


text:
        This example demonstrates inter mojit communication on a page.
        The mojit on the left side contains a list of image links.
        The mojit on the right side will display the image whenever a link
        in the left mojit is clicked on.

                {{{sender}}}

                {{{receiver}}}


text:
#include "config.h"
#include "WebURLError.h"

#include "KURL.h"
#include "ResourceError.h"
#include <wtf/text/CString.h>

using namespace WebCore;

namespace WebKit {

WebURLError::WebURLError(const ResourceError& error)
{
    *this = error;
}

WebURLError& WebURLError::operator=(const ResourceError& error)
{
    if (error.isNull())
        *this = WebURLError();
    else {
        domain = error.domain();
        reason = error.errorCode();
        unreachableURL = KURL(ParsedURLString, error.failingURL());
    }
    return *this;
}

WebURLError::operator ResourceError() const
{
    if (!reason)
        return ResourceError();
    CString spec = unreachableURL.spec();
    return ResourceError(domain, reason,
                         String::fromUTF8(spec.data(), spec.length()),
                         String());
}

} // namespace WebKit


text:
define([
  'aeris/util',
  'aeris/maps/map',
  'aeris/maps/markercollections/markercollection',
  'aeris/maps/markers/marker',
  'tests/spec/integration/helpers/mapcanvas',
  'tests/spec/integration/helpers/triggermouseevent',
  'tests/spec/integration/helpers/getmarkers',
  'jquery',
  'tests/lib/flag'
], function(_, Map, MarkerCollection, Marker, MapCanvas, triggerMouseEvent, getMarkers, $, Flag) {
  var ASYNC_DELAY = 100;

  describe('A MarkerCollection (Leaflet)', function() {
    var markerCollection, map, mapCanvas, layersReadyFlag;
    var clusterStyles;

    var NW = [45, -120], NE = [45, -80], SW = [30, -120], SE = [30, -80];
    var CLUSTER_CLASS = 'aeris-cluster';
    var MARKER_URL = 'http://cdn.aerisjs.com/assets/lightning_blue.png';
    var CLUSTER_URL = 'http://cdn.aerisjs.com/assets/poi.png';

    var getMarkers_orig = getMarkers;
    getMarkers = function(count, opt_position, opt_options) {
      var options = _.defaults(opt_options || {}, {
        url: MARKER_URL
      });

      return getMarkers_orig.call(this, count, opt_position, options);
    };

    beforeEach(function() {
      mapCanvas = new MapCanvas();
      // To make sure we have room for markers;
      mapCanvas.style.height = '800px';

      map = new Map(mapCanvas.id);
      map.jasmineToString = _.constant('Map');
    });
    afterEach(function() {
      mapCanvas.remove();
    });

    // toHaveMarkerCount
    beforeEach(function() {
      this.addMatchers({
        toHaveMarkerCount: function(count) {
          var map = this.actual;
          var actualMarkerCount = findMarkers(map).length;

          this.message = this.isNot ?
            _.constant('Expect map not to have ' + count + ' markers.') :
            _.constant('Expect map to have ' + count + ' markers, but it has ' + actualMarkerCount);

          return actualMarkerCount === count;
        },
        toHaveClusterCount: function(count) {
          var map = this.actual;
          var actualClusterCount = findClusters(map).length;

          this.message = this.isNot ?
            _.constant('Expect map not to have ' + count + ' clusters.') :
            _.constant('Expect map to have ' + count + ' clusters, but it has ' + actualClusterCount);

          return actualClusterCount === count;
        }
      });
    });

    beforeEach(function() {
      clusterStyles = {
        url: CLUSTER_URL,
        width: 25,
        height: 25,
        textColor: 'white',
        textSize: 13,
        anchorText: [-14, 15]
      };

      markerCollection = new MarkerCollection(null, {
        clusterStyles: {
          defaultStyles: [clusterStyles]
        }
      });
    });

    beforeEach(function() {
      // Set the layersReadyFlag when layers have been added to the map
      layersReadyFlag = new Flag();

      // 25 ms seems like enough time to load all layers.
      // This might be a little dangerous....
      //  - it will slow down our tests
      //  - there's some guesswork involved.
      // However, it's the only way I can think of to make sure that
      // markers are find-able on the map when are tests are run.
      map.getView().on('layeradd', _.debounce(layersReadyFlag.set, ASYNC_DELAY));
    });

    it('should not render anything if the collection is empty', function() {
      markerCollection.setMap(map);
      markerCollection.reset();

      layersReadyFlag.then(function() {
        expect(map).toHaveMarkerCount(0);
        expect(map).toHaveClusterCount(0);
      });
    });

    it('should render clusters for markers in the collection', function() {
      markerCollection = new MarkerCollection(getMarkers(10), {
        clusterStyles: {
          defaultStyles: [clusterStyles]
        }
      });
      markerCollection.setMap(map);

      layersReadyFlag.then(function() {
        expect(map).toHaveMarkerCount(0);
        expect(map).toHaveClusterCount(1);
      });
    });

    it('should render non-clustered markers in the collection', function() {
      var markers = getMarkers(1, NE).concat(getMarkers(1, SE));
      markerCollection = new MarkerCollection(markers, {
        clusterStyles: {
          defaultStyles: [clusterStyles]
        }
      });

      markerCollection.setMap(map);

      layersReadyFlag.then(function() {
        expect(map).toHaveMarkerCount(2);
        expect(map).toHaveClusterCount(0);
      });
    });

    describe('when many nearby markers are added to a collection', function() {
      var MARKER_COUNT;

      beforeEach(function() {
        MARKER_COUNT = 17;

        markerCollection.setMap(map);
        markerCollection.add(getMarkers(MARKER_COUNT));
      });

      it('should render a single cluster element', function() {
        layersReadyFlag.then(function() {
          expect(map).toHaveClusterCount(1);
        });
      });

      it('should not render individual markers', function() {
        layersReadyFlag.then(function() {
          expect(map).toHaveMarkerCount(0);
        });
      });

      it('should render the marker count in the cluster element', function() {
        layersReadyFlag.then(function() {
          expect(getClusterCount()).toMatch(MARKER_COUNT.toString());
        });
      });

    });

    describe('when markers groups are added in two different locations', function() {

      beforeEach(function() {
        markerCollection.add(getMarkers(5, NE));
        markerCollection.add(getMarkers(5, SW));

        markerCollection.setMap(map);
      });

      it('should render cluster elements for each marker group', function() {
        expect(map).toHaveClusterCount(2);
      });

      it('should not render individual markers', function() {
        expect(map).toHaveMarkerCount(0);
      });

    });

    describe('when markers are added in faraway locations', function() {

      beforeEach(function() {
        markerCollection.add(getMarkers(1, NE));
        markerCollection.add(getMarkers(1, NW));
        markerCollection.add(getMarkers(1, SE));
        markerCollection.add(getMarkers(1, SW));

        markerCollection.setMap(map);
      });

      it('should not create any cluster elements', function() {
        expect(map).toHaveClusterCount(0);
      });

      it('should render marker icons for each marker', function() {
        expect(map).toHaveMarkerCount(4);
      });

    });

    describe('when a single marker is added with a type', function() {
      var TYPE_STUB = 'TYPE_STUB';

      beforeEach(function() {
        markerCollection.setMap(map);
        markerCollection.add(getMarkers(1, SW, { type: TYPE_STUB }));
      });

      it('should render the marker', function() {
        layersReadyFlag.then(function() {
          expect(map).toHaveMarkerCount(1);
        });
      });

    });

    describe('when a group of markers are added with a type', function() {
      var TYPE_STUB = 'TYPE_STUB';

      beforeEach(function() {
        markerCollection.setMap(map);
        markerCollection.add(getMarkers(5, SW, { type: TYPE_STUB }));
      });

      it('should render a cluster element', function() {
        layersReadyFlag.then(function() {
          expect(map).toHaveClusterCount(1);
        });
      });

    });

    describe('when nearby groups of markers with different types are added', function() {
      var TYPE_A_STUB = 'TYPE_A_STUB', TYPE_B_STUB = 'TYPE_B_STUB';

      beforeEach(function() {
        markerCollection.setMap(map);
        markerCollection.add(getMarkers(5, SW, { type: TYPE_A_STUB }));
        markerCollection.add(getMarkers(5, SW, { type: TYPE_B_STUB }));
      });

      it('should render a cluster element for each marker type', function() {
        layersReadyFlag.then(function() {
          expect(map).toHaveClusterCount(2);
        });
      });

    });

    describe('when a marker is removed', function() {

      beforeEach(function() {
        markerCollection.setMap(map);
      });

      it('should reduce the cluster count when a marker is removed', function() {
        markerCollection.setMap(map);

        layersReadyFlag.then(function() {
          markerCollection.add(getMarkers(10));

          markerCollection.pop();
          expect(getClusterCount()).toMatch('9');

          markerCollection.pop();
          expect(getClusterCount()).toMatch('8');
        });
      });

      it('should replace the cluster with a marker, if all but one marker is removed', function() {
        markerCollection.setMap(map);

        layersReadyFlag.then(function() {
          markerCollection.add(getMarkers(2));

          markerCollection.pop();
          expect(map).toHaveClusterCount(0);
          expect(map).toHaveMarkerCount(1);
        });
      });

    });

    describe('when the collection is reset', function() {

      beforeEach(function() {
        markerCollection.setMap(map);
      });

      describe('when no new markers are added', function() {

        it('should remove all clusters and markers', function() {
          layersReadyFlag.then(function() {
            markerCollection.reset();

            expect(map).toHaveClusterCount(0);
          });
        });

      });

      describe('when a single new marker is added', function() {

        it('should render only a single marker', function() {
          layersReadyFlag.then(function() {
            markerCollection.reset(getMarkers(1));

            expect(map).toHaveClusterCount(0);
            expect(map).toHaveMarkerCount(1);
          });
        });

      });

      describe('when several new markers are added', function() {

        it('should render a cluster', function() {
          layersReadyFlag.then(function() {
            markerCollection.reset(getMarkers(5));

            expect(map).toHaveClusterCount(1);
            expect(map).toHaveMarkerCount(0);
          });
        });

      });

      describe('adding a collection to the map', function() {
        var delayFlag;

        beforeEach(function() {
          delayFlag = new Flag();

          markerCollection.add(getMarkers(5));

          _.delay(function() {
            markerCollection.setMap(map);
            delayFlag.set();
          }, ASYNC_DELAY);
        });

        it('should render clusters elements', function() {
          delayFlag.then(function() {
            expect(findClusters().length).toBeGreaterThan(0);
          });
        });

      });

    });

    describe('removing a collection from the map', function() {
      var delayFlag;

      beforeEach(function() {
        delayFlag = new Flag();

        _.delay(function() {
          markerCollection.setMap(map);
          markerCollection.setMap(null);
          delayFlag.set();
        }, ASYNC_DELAY);
      });

      it('should remove cluster elements', function() {
        delayFlag.then(function() {
          expect(map).toHaveClusterCount(0);
        });
      });

      it('should not render individual marker elements', function() {
        delayFlag.then(function() {
          expect(map).toHaveMarkerCount(0);
        });
      });

    });

    describe('MarkerCollection events', function() {

      beforeEach(function() {
        markerCollection.setMap(map);
        markerCollection.add(getMarkers(5, NW));
        markerCollection.add(getMarkers(1, SE));
      });

      describe('click', function() {
        var onClick;

        beforeEach(function() {
          onClick = jasmine.createSpy('onClick');
          markerCollection.on('click', onClick);
        });

        it('should fire when an individual marker is clicked', function() {
          layersReadyFlag.then(function() {
            triggerMarkerEvent('click');
            expect(onClick).toHaveBeenCalled();
          });
        });

        it('should only fire once for each clicked marker', function() {
          layersReadyFlag.then(function() {
            triggerMarkerEvent('click');
            expect(onClick.callCount).toEqual(1);
          });
        });

        it('should not fire when a cluster is clicked', function() {
          layersReadyFlag.then(function() {
            triggerClusterEvent('click');
            expect(onClick).not.toHaveBeenCalled();
          });
        });

      });

      describe('cluster:click', function() {
        var onClusterClick;

        beforeEach(function() {
          onClusterClick = jasmine.createSpy('onClusterClick');
          markerCollection.on('cluster:click', onClusterClick);
        });

        it('should fire when a cluster is clicked', function() {
          layersReadyFlag.then(function() {
            triggerClusterEvent('click');
            expect(onClusterClick).toHaveBeenCalled();
          });
        });

        it('should provide an aeris LatLon object', function() {
          onClusterClick.andCallFake(function(latLon) {
            expect(_.isArray(latLon)).toEqual(true);
            expect(_.isNumeric(latLon[0])).toEqual(true);
            expect(_.isNumeric(latLon[1])).toEqual(true);
          });

          layersReadyFlag.then(function() {
            triggerClusterEvent('click');
            expect(onClusterClick).toHaveBeenCalled();
          });
        });

        it('should not fire when an individual marker is clicked', function() {
          layersReadyFlag.then(function() {
            triggerMarkerEvent('click');
            expect(onClusterClick).not.toHaveBeenCalled();
          });
        });

      });

      describe('cluster:mouseover', function() {
        var onClusterMouseOver;

        beforeEach(function() {
          onClusterMouseOver = jasmine.createSpy('onClusterMouseOver');
          markerCollection.on('cluster:mouseover', onClusterMouseOver);
        });

        it('should fire when the mouse enters a cluster element', function() {
          layersReadyFlag.then(function() {
            triggerClusterEvent('mouseover');
            expect(onClusterMouseOver).toHaveBeenCalled();
          });
        });

        it('should not fire when the mouse enters an individual marker', function() {
          layersReadyFlag.then(function() {
            triggerMarkerEvent('mouseover');
            expect(onClusterMouseOver).not.toHaveBeenCalled();
          });
        });

      });

      describe('cluster:mouseout', function() {
        var onClusterMouseOut;

        beforeEach(function() {
          onClusterMouseOut = jasmine.createSpy('onClusterMouseOut');
          markerCollection.on('cluster:mouseout', onClusterMouseOut);
        });

        it('should fire when the mouse leaves a cluster element', function() {
          layersReadyFlag.then(function() {
            triggerClusterEvent('mouseout');
            expect(onClusterMouseOut).toHaveBeenCalled();
          });
        });

        it('should not fire when the mouse leaves an individual marker', function() {
          layersReadyFlag.then(function() {
            triggerMarkerEvent('mouseout');
            expect(onClusterMouseOut).not.toHaveBeenCalled();
          });
        });

      });

    });

    describe('toggling clustering behavior', function() {

      describe('using the `cluster: false` option', function() {

        it('should prevent markers from clustering (on init)', function() {
          var MARKER_COUNT = 10;
          var markersInSameArea = getMarkers(MARKER_COUNT, NE);
          var markerCollection = new MarkerCollection(markersInSameArea, {
            cluster: false
          });
          markerCollection.setMap(map);

          layersReadyFlag.then(function() {
            expect(map).toHaveClusterCount(0);
            expect(findMarkers().length).toEqual(MARKER_COUNT);
          });
        });

        it('should prevent markers from clustering (on init)', function() {
          var MARKER_COUNT = 10;
          var markersInSameArea = getMarkers(MARKER_COUNT, NE);
          var markerCollection = new MarkerCollection([], {
            cluster: false
          });
          markerCollection.setMap(map);

          markerCollection.add(markersInSameArea);

          layersReadyFlag.then(function() {
            expect(map).toHaveClusterCount(0);
            expect(findMarkers().length).toEqual(MARKER_COUNT);
          });
        });

      });

      describe('stopClustering', function() {
        var ctx, MARKER_COUNT_INIT = 10;

        beforeEach(function() {
          ctx = {};
        });

        describe('when using the `cluster: true` option', function() {

          beforeEach(function() {
            ctx.markerCollection = new MarkerCollection(getMarkers(MARKER_COUNT_INIT), {
              cluster: true
            });
            ctx.markerCollection.setMap(map);
          });

          itShouldStopClustering();

          describe('toggling with #startClustering', function() {

            beforeEach(function() {
              ctx.markerCollection.stopClustering();
              ctx.markerCollection.startClustering();
            });

            itShouldStopClustering();

          });

          function itShouldStopClustering() {

            it('should replace all rendered clusters with individual markers', function() {
              ctx.markerCollection.stopClustering();

              expect(map).toHaveClusterCount(0);
              expect(map).toHaveMarkerCount(MARKER_COUNT_INIT);
            });

            it('should render any new markers individually', function() {
              ctx.markerCollection.stopClustering();

              ctx.markerCollection.add(getMarkers(10, NE));
              ctx.markerCollection.add(getMarkers(10, SW));

              expect(map).toHaveClusterCount(0);
              expect(map).toHaveMarkerCount(MARKER_COUNT_INIT + 10 + 10);
            });

          }

        });

      });

      describe('startClustering', function() {
        var ctx, MARKER_COUNT_INIT = 10, CLUSTER_POSITION_INIT = NE;

        beforeEach(function() {
          ctx = {};
        });

        describe('when used with the `cluster: false` option', function() {

          beforeEach(function() {
            var markers = getMarkers(MARKER_COUNT_INIT, CLUSTER_POSITION_INIT);
            ctx.markerCollection = new MarkerCollection(markers, {
              cluster: false
            });
            ctx.markerCollection.setMap(map);
          });

          itShouldStartClustering();

          describe('toggling with #stopClustering', function() {

            beforeEach(function() {
              ctx.markerCollection.startClustering();
              ctx.markerCollection.stopClustering();
            });

            itShouldStartClustering();

          });

          function itShouldStartClustering() {

            it('should cluster groups of markers', function() {
              ctx.markerCollection.startClustering();

              expect(map).toHaveMarkerCount(0);
              expect(map).toHaveClusterCount(1);
            });

            it('should add new markers to clusters', function() {
              var somwhereElse = CLUSTER_POSITION_INIT.map(function(coord) {
                return coord - 10;
              });
              ctx.markerCollection.startClustering();

              // Add markers next to init markers
              ctx.markerCollection.add(getMarkers(10, CLUSTER_POSITION_INIT));
              expect(map).toHaveMarkerCount(0);
              expect(map).toHaveClusterCount(1);

              // Add markers somewhere else on the map
              ctx.markerCollection.add(getMarkers(10, somwhereElse));
              expect(map).toHaveMarkerCount(0);
              expect(map).toHaveClusterCount(2);
            });

          }

        });

      });

    });

    function getClusterCount() {
      return findClusters().text().
        match(/\b[0-9]+\b/g)[0];
    }

    function triggerClusterEvent(event) {
      var $clusters = findClusters();

      if (!$clusters.length) {
        throw new Error('Unable to trigger cluster event: no clusters are rendered');
      }

      triggerMouseEvent($clusters[0], event);
    }

    function triggerMarkerEvent(event) {
      var $markers = findMarkers();

      if (!$markers.length) {
        throw new Error('Unable to trigger marker event: no markers are rendered');
      }

      triggerMouseEvent($markers[0], event);
    }

    function findClusters(opt_map) {
      var scopeMap = opt_map || map;
      return $(scopeMap.getElement()).find('.' + CLUSTER_CLASS);
    }

    function findMarkers(opt_map) {
      var scopeMap = opt_map || map;
      var selector = 'img[src$="{markerUrl}"]'.
        replace('{markerUrl}', MARKER_URL);

      return $(scopeMap.getElement()).find(selector);
    }

    /**
     * Helper for getting a bunch of markers
     * around the same lat lon.
     *
     * @param count
     * @param {aeris.LatLon=} opt_position Lat lon location around which markers will be centered.
     * @param {Object=} opt_options
     * @param {String=} opt_options.type If specified, will be used to stub the marker's `getType` return value.
     *
     * @return {Array.aeris.markers.Marker}
     */
    function getMarkers(count, opt_position, opt_options) {
      var options = opt_options || {};
      var positions = [];
      var basePos = opt_position || NW;

      _.times(count, function(i) {
        var offsetX = Math.random() > 0.5 ? Math.random() : Math.random() * -1;
        var offsetY = Math.random() > 0.5 ? Math.random() : Math.random() * -1;

        positions.push([basePos[0] + offsetX, basePos[1] + offsetY]);
      });

      return positions.map(function(pos) {
        var marker = new Marker({
          position: pos,
          url: MARKER_URL
        });

        if (options.type) {
          marker.getType = _.constant(options.type);
        }

        return marker;
      });
    }

  });

});


text:
CREATE TABLE bookings (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(20) null,
email varchar(20) null,
passengers varchar(2) null,
departure date null
)ENGINE=innodb;


text:
namespace Epi.Data
{

    /// <summary>
    /// Common interface for connection string building graphical user interfaces (in both Windows and Web)
    /// </summary>
    public interface IConnectionStringGui
    {
        bool ShouldIgnoreNonExistance
        {
            set;
        }

        /// <summary>
        /// Gets the connection string
        /// </summary>
        System.Data.Common.DbConnectionStringBuilder DbConnectionStringBuilder
        {
            get;
        }
        /// <summary>
        /// Gets the preferred database name
        /// </summary>
        string PreferredDatabaseName
        {
            get;
        }
        /// <summary>
        /// Gets the connection string description
        /// </summary>
        string ConnectionStringDescription
        {
            get;
        }

        /// <summary>
        /// Gets whether or not the user entered a password
        /// </summary>
        bool UsesPassword
        {
            get;
        }

        /// <summary>
        /// Sets the database name for the dialog to use
        /// </summary>
        /// <param name="databaseName">The name of the database</param>
        void SetDatabaseName(string databaseName);

        /// <summary>
        /// Sets the server name for the dialog to use
        /// </summary>
        /// <param name="serverName">The name of the server</param>
        void SetServerName(string serverName);

        /// <summary>
        /// Sets the user name for the dialog to use
        /// </summary>
        /// <param name="serverName">The username</param>
        void SetUserName(string userName);

        /// <summary>
        /// Sets the password for the dialog to use
        /// </summary>
        /// <param name="password">The password</param>
        void SetPassword(string password);
    }
}


text:
import styled from 'styled-components'

const Wrapper = styled.main.attrs(props => ({
  role: !props.as ? 'main' : undefined,
  id: !props.as ? 'main-content' : undefined,
}))`
  position: relative;
  border-radius: 5px;
  max-width: 770px;
  word-wrap: break-word;
  background-color: var(--color-wrapperBackground);
  margin: 0px auto 30px auto;
  top: 30px;
  padding: 50px;
  box-shadow: 0 0 0 0, 0 6px 12px var(--color-wrapperShadow);

  @media (max-width: 780px) {
    width: 100%;
    border-radius: unset;
    padding: 25px;
  }
`

export default Wrapper


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

	$config = array(

		'persona_insert' =>
		array(
			array('field' => 'nombre','lebel' => 'nombre de persona', 'rules' => 'trim|required|max_length[50]'),
			array('field' => 'appaterno','lebel' => 'Apellido paterno', 'rules' => 'trim|required|max_length[50]'),
			array('field' => 'apmaterno','lebel' => 'Apellido Materno', 'rules' => 'trim|required|max_length[50]'),
			array('field' => 'email','lebel' => 'Email', 'rules' => 'trim|valid_email'),
			array('field' => 'dni','lebel' => 'DNI', 'rules' => 'trim|required|max_length[50]'),
			array('field' => 'register_date','lebel' => 'fecha', 'rules' => 'trim|required|max_length[50]')
		),

		'usuario_insert' =>
		array(
			array ('field' => 'nomusuario','lebel' => 'nombre de usuario','rules' => 'trim|required|max_length[50]'),
			array ('field' => 'clave','lebel' => 'nombre de usuario','rules' => 'trim|required|max_length[50]'),
			)

	);

?>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Jb. 34: 44 (1904)

#### Original name
Poria delicatula Henn., 1904

### Remarks
null


text:
copyright:
  years: 2015, 2016

---

# {{site.data.keyword.amashort}} mit einer lokalen Entwicklungsumgebung verwenden
{: #protecting-local}

*Letzte Aktualisierung: 15. April 2016*
{: .last-updated}

Sie können Ihre lokale Entwicklungsumgebung so konfigurieren, dass sie den {{site.data.keyword.amashort}}-Service verwendet, der in {{site.data.keyword.Bluemix}} ausgeführt wird. Insbesondere können Sie das {{site.data.keyword.amashort}}-Server-SDK verwenden, wenn Sie serverseitigen Code mit einem lokalen Entwicklungsserver wie Node.js entwickeln.

Das {{site.data.keyword.amashort}}-Server-SDK setzt voraus, dass zwei Umgebungsvariablen festgelegt werden. Wenn Sie serverseitigen Code in {{site.data.keyword.Bluemix_notm}} entwickeln, werden diese Variablen von der {{site.data.keyword.Bluemix_notm}}-Infrastruktur bereitgestellt.

* `VCAP_SERVICES`: Enthält Informationen zu Services, die an die mobile Back-End-Anwendung gebunden sind.
* `VCAP_APPLICATION`: Enthält Informationen zur mobilen Back-End-Anwendung.

Zur Verwendung von {{site.data.keyword.amashort}} mit einem lokalen Entwicklungsserver müssen Sie diese Umgebungsvariablen manuell hinzufügen.

1. Öffnen Sie das {{site.data.keyword.Bluemix_notm}}-Dashboard Ihres mobilen Back-Ends, das mit dem {{site.data.keyword.amashort}}-Service geschützt wird.

1. Klicken Sie auf **Mobile Systemerweiterungen** und kopieren Sie den Wert für **AppGUID**.

1. Legen Sie in Ihrer lokalen Entwicklungsumgebung die Umgebungsvariable *VCAP_APPLICATION* fest. Die Variable muss ein in eine Zeichenfolge konvertiertes JSON-Objekt mit einer einzelnen Eigenschaft enthalten.
```JavaScript
{
    application_id: "appGUID"
}
```
Ersetzen Sie die Variable *appGUID* durch den Wert aus dem entsprechenden Feld unter **Mobile Systemerweiterungen**.

1. Klicken Sie auf **Berechtigungsnachweise anzeigen** auf der Kachel für den {{site.data.keyword.amashort}}-Service in Ihrer mobilen Back-End-Anwendung im {{site.data.keyword.Bluemix_notm}}-Dashboard. Es wird ein JSON-Objekt mit Zugriffsberechtigungsnachweisen angezeigt, die {{site.data.keyword.amashort}} für Ihre mobile Back-End-Anwendung bereitstellt.

1. Legen Sie in Ihrer lokalen Entwicklungsumgebung die Umgebungsvariable `VCAP_SERVICES` fest. Der Wert dieser Variablen muss ein in eine Zeichenfolge konvertiertes JSON-Objekt sein, das die {{site.data.keyword.amashort}}-Berechtigungsnachweise enthält.  Weitere Informationen finden Sie im folgenden Beispiel.

## Beispielcode
{: #local-dev-sample}

Zur Verwendung des {{site.data.keyword.amashort}}-Service in einer lokalen Node.js-Entwicklungsumgebung fügen Sie den folgenden Code hinzu, bevor Sie das Modul `bms-mca-token-validation-strategy` benötigen.

```JavaScript
var vcapApplication = {
	application_id:"appGUID"
};

var vcapServices = {
	"AdvancedMobileAccess": [
		{
			"credentials": {
				"admin_url": "https://mobile.ng.bluemix.net/imfmobileplatformdashboard/?appGuid=appGUID",
				"clientId": "appGUID",
				"secret": "secret",
				"serverUrl": "https://imf-authserver.ng.bluemix.net/imf-authserver",
				"tenantId": "appGUID"
			}
		}
	]
};

process.env["VCAP_APPLICATION"] = JSON.stringify(vcapApplication);
process.env["VCAP_SERVICES"] = JSON.stringify(vcapServices);

var MCABackendStrategy =
	require('bms-mca-token-validation-strategy').MCABackendStrategy;

// Restlicher Code
```
Ersetzen Sie die Vorkommen des Werts *appGUID* im Code durch den Wert für *appGUID* aus Ihrem mobilen Back-End.

## Mobile Anwendungen zur Arbeit mit einem lokalen Entwicklungsserver konfigurieren
{: #configuring-local}

Initialisieren Sie die {{site.data.keyword.amashort}}-Client-SDKs mit der realen URL Ihrer {{site.data.keyword.Bluemix_notm}}-Anwendung und verwenden Sie den lokalen Host (localhost) oder die IP-Adresse in jeder Ihrer Anforderungen. Weitere Informationen finden Sie in den folgenden Beispielen.

Es ist möglich, dass Sie `localhost` in den folgenden Beispielen in die tatsächliche IP-Adresse Ihres Entwicklungsservers ändern müssen.

### Android

```Java
String baseRequestUrl = "http://localhost:3000";
String bluemixAppRoute = "http://myapp.mybluemix.net";
String bluemixAppGUID = "your-bluemix-app-guid";

BMSClient.getInstance().initialize(bluemixAppRoute, bluemixAppGUID);

Request request =
			new Request(baseRequestUrl + "/resource/path", Request.GET);

request.send(this, new ResponseListener() {
	@Override
	public void onSuccess (Response response) {
		Log.d("Myapp", "onSuccess :: " + response.getResponseText());
	}
	@Override
	public void onFailure (Response response, Throwable t, JSONObject extendedInfo) {
		if (null != t) {
			Log.d("Myapp", "onFailure :: " + t.getMessage());
		} else if (null != extendedInfo) {
			Log.d("Myapp", "onFailure :: " + extendedInfo.toString());
		} else {
			Log.d("Myapp", "onFailure :: " + response.getResponseText());
		}
	}
});
```
### Cordova

```JavaScript
var baseRequestUrl = "http://localhost:3000";
var bluemixAppRoute = "http://myapp.mybluemix.net";
var bluemixAppGUID = "your-bluemix-app-guid";

BMSClient.initialize(bluemixAppRoute, bluemixAppGUID);

var success = function(data){
   	console.log("success", data);
}

var failure = function(error){
	console.log("failure", error);
}

var request = new MFPRequest(baseRequestUrl +
							"/resource/path", MFPRequest.GET);

request.send(success, failure);
```

### iOS - Objective C

```Objective-C
NSString *baseRequestUrl = @"http://localhost:3000";
NSString *bluemixAppRoute = @"http://myapp.mybluemix.net";
NSString *bluemixAppGUID = @"your-bluemix-app-guid";

[[IMFClient sharedInstance]
			initializeWithBackendRoute:bluemixAppRoute
			backendGUID:bluemixAppGUID];

NSString *requestPath = [NSString stringWithFormat:@"%@/resource/path",
								baseRequestUrl];

IMFResourceRequest *request =  [IMFResourceRequest requestWithPath:requestPath
																method:@"GET"];

[request sendWithCompletionHandler:^(IMFResponse *response, NSError *error) {
	if (error){
		NSLog(@"Error :: %@", [error description]);
	} else {
		NSLog(@"Response :: %@", [response responseText]);
	}
}];
```

### iOS - Swift

```Swift
let baseRequestUrl = "http://localhost:3000";
let bluemixAppRoute = "http://myapp.mybluemix.net";
let bluemixAppGUID = "your-bluemix-app-guid";

IMFClient.sharedInstance().initializeWithBackendRoute(bluemixAppRoute,
	 							backendGUID: bluemixAppGuid)

let requestPath = baseRequestUrl + "/resource/path"

let request = IMFResourceRequest(path: requestPath, method: "GET");

request.sendWithCompletionHandler { (response, error) -> Void in
	if (nil != error){
		NSLog("Error :: %@", error.description)
	} else {
		NSLog("Response :: %@", response.responseText)
	}
};

```


text:
drop table if exists gh_ost_test;
create table gh_ost_test (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(512) DEFAULT NULL,
  v varchar(255) DEFAULT NULL COMMENT '添加普通列测试',
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=gbk;

insert into gh_ost_test values (null, 'gbk-test-initial', '添加普通列测试-添加普通列测试');
insert into gh_ost_test values (null, 'gbk-test-initial', '添加普通列测试-添加普通列测试');

drop event if exists gh_ost_test;
delimiter ;;
create event gh_ost_test
  on schedule every 1 second
  starts current_timestamp
  ends current_timestamp + interval 60 second
  on completion not preserve
  enable
  do
begin
  insert into gh_ost_test (name) values ('gbk-test-default');
  insert into gh_ost_test values (null, 'gbk-test', '添加普通列测试-添加普通列测试');
  update gh_ost_test set v='添加普通列测试' where v='添加普通列测试-添加普通列测试' order by id desc limit 1;
end ;;


text:
import { IQueryRequest } from "../query-request";
import { PipelineItem } from "../../pipeline-item";
import { IQueryResponse } from "../query-response";
import { IConcreteEntity } from "@poseidon/core-models";
import { IResponse } from "../../response";

export async function queryFromRepository<
  T extends object = object,
  TResponse extends IConcreteEntity = IConcreteEntity
>(
  request: IQueryRequest<T, TResponse>,
  next: PipelineItem<T, IQueryResponse<TResponse>>
): Promise<IResponse<IQueryResponse<TResponse>>> {
  const { repoFactory, entityType, query } = request;
  const repo = await repoFactory.createById(entityType._id);

  request.response = request.response || {};
  request.response.result = {
    total: 0,
    data: (await repo.findMany(query)) as TResponse[]
  };

  return next(request);
}


text:
use std::time::Duration;
use libusb::{Transfer, Result as UsbResult};
use utils::UsbWrapper;

pub trait ToControlPacket {
    fn to_control_packet(self) -> ControlPacket;
}

pub struct ControlPacket {
    buf: Vec<u8>,
    endpoint_direction: u8,
    request_type: u8,
    request: u8,
    value: u16,
    index: u16,
    timeout: Duration,
}

impl ControlPacket {
    pub fn new(buf: Vec<u8>, endpoint_direction: u8, request_type: u8, request: u8,
               value:u16, index: u16, timeout: Duration) -> ControlPacket {
        ControlPacket {
            endpoint_direction: endpoint_direction,
            buf: buf,
            request_type: request_type,
            request: request,
            value: value,
            index: index,
            timeout: timeout,
        }
    }
}

pub struct Handle {
    usb_wrapper: Option<UsbWrapper>,
}

impl Handle {
    pub fn new() -> UsbResult<Handle> {
        let usb_wrapper = try!(UsbWrapper::new());
        let mut handle = Handle {
            usb_wrapper: Some(usb_wrapper),
        };
        try!(handle.listen_iface1(Duration::from_secs(3600*24*365)));
        try!(handle.listen_iface2(Duration::from_secs(3600*24*365)));
        Ok(handle)
    }

    pub fn reconnect(&mut self) -> UsbResult<()> {
        // We must drop the old one before creating a new one, because all
        // handles and locks on that device must be released first.
        drop(::std::mem::replace(&mut self.usb_wrapper, None));
        self.usb_wrapper = Some(try!(UsbWrapper::new()));
        Ok(())
    }

    pub fn send_control(&mut self, packet: ControlPacket) ->  UsbResult<()> {
        let wrapper_ref = self.usb_wrapper.as_mut().unwrap();
        wrapper_ref.async_group.submit(Transfer::control(
                wrapper_ref.handle,
                packet.endpoint_direction,
                packet.buf,
                packet.request_type,
                packet.request,
                packet.value,
                packet.index,
                packet.timeout
        ))
    }

    pub fn send_interrupt(&mut self, endpoint_direction: u8, buf: Vec<u8>,
                          timeout: Duration) -> UsbResult<()> {
        let wrapper_ref = self.usb_wrapper.as_mut().unwrap();
        wrapper_ref.async_group.submit(Transfer::interrupt(
                wrapper_ref.handle,
                endpoint_direction,
                buf,
                timeout
        ))
    }

    pub fn recv(&mut self, timeout: Duration) -> Option<UsbResult<(u8, Vec<u8>)>> {
        let mut transfer = match self.usb_wrapper.as_mut().unwrap().async_group.try_wait_any(timeout) {
            Some(res) => match res {
                Ok(transfer) => transfer,
                Err(err) => return Some(Err(err))
            },
            None => return None
        };
        let buf = transfer.actual().iter().cloned().collect();
        let endpoint_direction = transfer.endpoint();
        // don't resubmit control packets
        if endpoint_direction != 0x80 {
            match self.usb_wrapper.as_mut().unwrap().async_group.submit(transfer) {
                Ok(_) => {},
                Err(err) => return Some(Err(err))
            }
        }
        Some(Ok((endpoint_direction, buf)))
    }

    pub fn listen_iface2(&mut self, timeout: Duration) -> UsbResult<()> {
        let mut vec = Vec::new();
        vec.resize(64, 0u8);
        self.send_interrupt(0x82, vec, timeout)
    }

    pub fn listen_iface1(&mut self, timeout: Duration) -> UsbResult<()> {
        let mut vec = Vec::new();
        vec.resize(8, 0u8);
        try!(self.send_interrupt(0x81, vec, timeout));
        Ok(())
    }
}


text:
"""
    admin.models.occupation

    :copyright: (c) 2013 by Openlabs Technologies & Consulting (P) Limited
    :license: see LICENSE for more details.
"""
from django.db import models
from django.contrib import admin
from django.core.urlresolvers import reverse

__all__ = ['Occupation']

class Occupation(models.Model):
    '''
        Occupation model
    '''
    class Meta:
        '''
            Meta properties for this model
        '''
        app_label = 'admin'

    name = models.CharField(
        max_length=50, default=None, unique=True, db_index=True,
    )
    tracks = models.ManyToManyField('Track', blank=True, null=True)
    slug = models.SlugField(unique=True)
    sub_sector = models.ForeignKey('SubSector', db_index=True)
    create_date = models.DateTimeField(auto_now_add=True)
    write_date = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        '''
            Returns object display name
        '''
        return "%s/%s" % (self.sub_sector, self.name)

    @property
    def sector(self):
        """
        Returns the sector for occupation
        """
        return self.sub_sector.sector

    @property
    def qps(self):
        """
        Returns a list of objects of the jobs in this occupation
        """
        from admin.models.qualification_pack import QualificationPack
        return QualificationPack.objects.filter(
            occupation=self, is_draft=False
        )

    @property
    def career_map(self):
        """
            return url for career map svg
        """
        return reverse(
            "career_map", args=[self.slug]
        )

    def get_absolute_url(self):
        """
            url to render occupation
        """
        return reverse(
            "render_occupation", args=[self.slug]
        )

class OccupationAdmin(admin.ModelAdmin):
    '''
        Occupation for admin
    '''
    list_display = ('name', 'sub_sector', 'slug')
    prepopulated_fields = {"slug": ("name",)}

admin.site.register(Occupation, OccupationAdmin)