text:
/////////////////////////////////////////////////////////////////////////////
// TabbedFrame.h - Base template class for supporting a frame
//   window with multiple views that you switch between using
//   a "CustomTabCtrl" (such as CDotNetTabCtrl)
//
// Written by Daniel Bowen (dbowen@es.com)
// Copyright (c) 2002-2005 Daniel Bowen.
//
// Depends on CustomTabCtrl.h originally by Bjarke Viksoe (bjarke@viksoe.dk)
//  with the modifications by Daniel Bowen
//
// CCustomTabOwnerImpl -
//   MI class that helps implement the parent of the actual custom tab control window.
//   The class doesn't have a message map itself, and is meant
//   to be inherited from along-side a CWindowImpl derived class.
//   This class handles creation of the tab window as well as
//   adding, removing, switching and renaming tabs based on an HWND.
// CTabbedFrameImpl -
//   Base template to derive your specialized frame window class from to get
//   a frame window with multiple "view" child windows that you
//   switch between using a custom tab control (such as CDotNetTabCtrl).
// CTabbedPopupFrame -
//   Simple class deriving from CTabbedFrameImpl that is suitable
//   for implementing a tabbed "popup frame" tool window, with one or more views.
// CTabbedChildWindow -
//   Simple class deriving from CTabbedFrameImpl that is suitable
//   for implementing a tabbed child window, with one or more views.
//
//
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever.
//
// If you find bugs, have suggestions for improvements, etc.,
// please contact the author.
//
// History (Date/Author/Description):
// ----------------------------------
//
// 2005/07/13: Daniel Bowen
// - Namespace qualify the use of more ATL and WTL classes.
//
// 2005/04/12: Daniel Bowen
// - CCustomTabOwnerImpl::CalcTabAreaHeight -
//   * CDC dc = TabCtrl.GetDC();
//       should be
//     CClientDC dc(TabCtrl);
//
// 2005/04/08: Daniel Bowen
// - Generalize support for having the tab control automatically hidden
//   if the number of tabs is below a certain count.
// - CCustomTabOwnerImpl -
//   * Change OnAddFirstTab and OnRemoveLastTab to be more
//     general purpose. Have OnAddTab and OnRemoveTab instead,
//     and have them called for every AddTab or RemoveTab.
//   * Add KeepTabsHidden (overrideable). Previously only in CMDITabOwnerImpl.
//   * Add ShowTabControl, HideTabControl (overrideable)
//   * Add SetMinTabCountForVisibleTabs (method)
// - CTabbedFrameImpl -
//   * Pass in T instead of CTabbedFrameImpl<T,...> to CCustomTabOwnerImpl inheritance
//     (so you can override CCustomTabOwnerImpl overrideables in
//     CTabbedFrameImpl derived classes)
//   * Add ModifyTabStyles (method)
//   * OnSettingChange - Call CalcTabAreaHeight through pT
//   * SetTabAreaHeight - Support for "KeepTabsHidden"
//
// 2005/03/14: Daniel Bowen
// - Fix warnings when compiling for 64-bit.
//
// 2004/11/29: Daniel Bowen
// - Update all WM_NOTIFY handlers to check that the notification is
//   from the tab control (and not from a sibling like a list view control)
// - Update CTabbedFrameImpl::OnRemoveLastTab to call this->Invalidate()
//
// 2004/06/28: Daniel Bowen
// - CCustomTabOwnerImpl -
//   * HighlightTab
// - Clean up warnings on level 4
//
// 2004/06/21: Peter Carlson
// - CCustomTabOwnerImpl -
//   * UpdateTabCanClose
//
// 2004/05/14: Daniel Bowen
// - CTabbedFrameImpl -
//   * Update OnClick handling so it only sets focus to the tab view
//     if the selected tab is being clicked. Without this update,
//     other code that tries to minimize flickering when switching
//     the active view doesn't get called.
//
// 2004/04/29: Daniel Bowen
// - Use LongToHandle with GetClassLong when getting HICON
// - CTabbedFrameImpl -
//   * Only forward focus to the active view if
//     the tab isn't currently capturing the mouse.
//   * Respond to NM_CLICK, CTCN_ACCEPTITEMDRAG and CTCN_CANCELITEMDRAG
//     from the tab control, and set focus to the tab item's view
//
// 2004/02/03: Daniel Bowen
// - CTabbedFrameImpl -
//   * Add new Set/GetForwardNotifications in case you want the parent of the tab
//     window to forward notifications on to its parent.  A good example where
//     you might want to use this would be with CTabbedChildWindow.
//
// 2004/01/19: Daniel Bowen
// - CTabbedFrameImpl -
//   * Have new "CHAIN_ACTIVETABVIEW_CHILD_COMMANDS" and "CHAIN_ACTIVETABVIEW_CHILD_COMMANDS2"
//     macro that is used to forward WM_COMMAND messages to the active view of a tab window
//     from outside the implementation of that tab window (such as in the Main Frame).
//
// 2003/06/27: Daniel Bowen
// - CCustomTabOwnerImpl -
//   * Remove WTL:: scope off of CImageList member.
// - CTabbedFrameImpl -
//   * Have new "CHAIN_ACTIVETABVIEW_COMMANDS" macro that is used to forward
//     WM_COMMAND messages to the active view.  This is done after
//     the CHAIN_MSG_MAP(baseClass), so be careful if the base
//     class also handles WM_COMMAND messages (the default
//     CFrameWindowImpl does not, and neither does CMDIChildWindowImpl
//     or CTabbedMDIChildWindowImpl).
//   * New "GetActiveView" that returns what CTabbedFrameImpl
//     thinks is the active view.
//   * Replace
//      DECLARE_FRAME_WND_CLASS(_T("TabbedFrame"), 0)
//     with
//      DECLARE_FRAME_WND_CLASS_EX(_T("TabbedFrame"), 0, 0, COLOR_APPWORKSPACE)
//     (gets rid of CS_DBLCLKS, CS_HREDRAW and CS_VREDRAW, sets background brush)
//   * Support "empty" tabbed frame (have window class brush,
//     let default handling of WM_ERASEBKGND happen if no active view,
//     and NULL out m_hWndActive in OnRemoveLastTab).
// - CTabbedPopupFrame -
//   * Replace
//      DECLARE_FRAME_WND_CLASS(_T("TabbedPopupFrame"), 0)
//     with
//      DECLARE_FRAME_WND_CLASS_EX(_T("TabbedPopupFrame"), 0, 0, COLOR_APPWORKSPACE)
//     (gets rid of CS_DBLCLKS, CS_HREDRAW and CS_VREDRAW, sets background brush)
// - CTabbedChildWindow -
//   * Replace
//      DECLARE_WND_CLASS(_T("TabbedChildWindow"))
//     with
//      DECLARE_FRAME_WND_CLASS_EX(_T("TabbedChildWindow"), 0, 0, COLOR_APPWORKSPACE)
//     (gets rid of CS_DBLCLKS, CS_HREDRAW and CS_VREDRAW, sets background brush)
//
// 2003/02/27: Daniel Bowen
// - Use _U_STRINGorID instead of WTL::_U_STRINGorID.
//   For VC7, this means you must #define _WTL_NO_UNION_CLASSES
//   before including the WTL header files, or you will
//   get compile errors (the ATL7 union classes are defined
//   in atlwin.h).
//
// 2002/11/27: Daniel Bowen
// - CTabbedFrameImpl::GetTabStyles needs to return DWORD, not bool
//
// 2002/09/25: Daniel Bowen
// - CTabbedFrameImpl -
//   * Expose "SetTabStyles" and "GetTabStyles" so that you can change
//     the tab related styles to something different than the default
// - CTabbedPopupFrame -
//   * Expose "SetCloseCommand" and "GetCloseCommand" so that
//     instead of destroying the window when the close button
//     on the popup frame is pushed, a command ID of your choice
//     is sent to the parent (such as a menu ID that corresponds
//     to toggling the visibility of the popup frame)
//
// 2002/06/26: Daniel Bowen
// - New "CTabbedChildWindow" that derives from CTabbedFrameImpl.
//   You can use this class when you want a child window to
//   use a tab control to switch between multiple views
// - Provide "PreTranslateMessage" function in CTabbedPopupFrame
//   (and the new CTabbedChildWindow)
// - CCustomTabOwnerImpl -
//   * Rename "GetTabs" method to "GetTabCtrl"
//   * Rename member "m_tabs" to "m_TabCtrl"
//   * Rename template argument "TTab" to "TTabCtrl"
//   * Rename "ShowTabs" and "HideTabs" overrideables to "OnAddFirstTab" and "OnRemoveLastTab",
//     and change the place that calls these to live up to those new names
//   * Remove GetCurSel (just call GetTabCtrl().GetCurSel() instead)
//   * DisplayTab -
//     + Add new parameter that says whether to use the window's icon.
//       If TRUE, the icon is requested first by sending the window WM_GETICON
//       looking for the "small" icon, then asking the window class for a small icon.
//       If no small icon is found, the same procedure is used to look for the
//       "big" icon.
//     + Call "SetCurSel" even if the tab to display has the same index
//       as the current selection
//     + Call "OnAddFirstTab" (which was "ShowTabs") only when the count
//       of tabs goes from 0 to 1.
//
// 2002/06/12: Daniel Bowen
// - Publish codeproject article.  For history prior
//   to the release of the article, please see the article
//   and the section "Note to previous users"

#ifndef __WTL_TABBED_FRAME_H__
#define __WTL_TABBED_FRAME_H__

#pragma once

#ifndef __cplusplus
	#error TabbedFrame.h requires C++ compilation
#endif

#ifndef __ATLAPP_H__
	#error TabbedFrame.h requires atlapp.h to be included first
#endif

#ifndef __ATLWIN_H__
	#error TabbedFrame.h requires atlwin.h to be included first
#endif

#ifndef __ATLFRAME_H__
	#error TabbedFrame.h requires atlframe.h to be included first
#endif

#ifndef __CUSTOMTABCTRL_H__
#include "CustomTabCtrl.h"
#endif

/////////////////////////////////////////////////////////////////////////////
//
// CCustomTabOwnerImpl
//  an MI template to help implement the owner window that uses CustomTabCtrl
//  to switch between windows / views
//
/////////////////////////////////////////////////////////////////////////////

template <class T, class TTabCtrl>
class CCustomTabOwnerImpl
{
// Member variables
protected:
	TTabCtrl m_TabCtrl;
	WTL::CImageList m_ImageList;
	int m_cxImage, m_cyImage;
	int m_nTabAreaHeight;
	size_t m_nMinTabCountForVisibleTabs;
	bool m_bKeepTabsHidden;

// Constructors
public:
	CCustomTabOwnerImpl() :
		m_cxImage(16),
		m_cyImage(16),
		m_nTabAreaHeight(24),
		m_nMinTabCountForVisibleTabs(1)
	{
		m_bKeepTabsHidden = (m_nMinTabCountForVisibleTabs > 0);
	}

// Overrideables
public:

	void OnAddTab(size_t nNewTabCount)
	{
		T* pT = static_cast<T*>(this);

		// NOTE: Derived classes should call this base class version as well
		if(nNewTabCount == m_nMinTabCountForVisibleTabs)
		{
			pT->ShowTabControl();
		}
	}

	void OnRemoveTab(size_t nNewTabCount)
	{
		T* pT = static_cast<T*>(this);

		// NOTE: Derived classes should call this base class version as well
		if((nNewTabCount+1) == m_nMinTabCountForVisibleTabs)
		{
			pT->HideTabControl();
		}
		else if(nNewTabCount == 0)
		{
			pT->Invalidate();
		}
	}

	void KeepTabsHidden(bool bKeepTabsHidden = true)
	{
		if(m_bKeepTabsHidden != bKeepTabsHidden)
		{
			m_bKeepTabsHidden = bKeepTabsHidden;

			// CalcTabAreaHeight will end up doing UpdateLayout and Invalidate
			T* pT = static_cast<T*>(this);
			pT->CalcTabAreaHeight();
		}
	}

	void ShowTabControl(void)
	{
		T* pT = static_cast<T*>(this);
		pT->KeepTabsHidden(false);
	}

	void HideTabControl(void)
	{
		T* pT = static_cast<T*>(this);
		pT->KeepTabsHidden(true);
	}

	void SetTabAreaHeight(int nNewTabAreaHeight)
	{
		if(m_nTabAreaHeight != nNewTabAreaHeight)
		{
			m_nTabAreaHeight = nForceTabAreaHeight;

			/*
			T* pT = static_cast<T*>(this);
			pT->UpdateLayout();
			Invalidate();
			*/
		}
	}

	// A derived class might not need to override this although they can.
	// (but they will probably need to specialize SetTabAreaHeight)
	void CalcTabAreaHeight(void)
	{
		// Dynamically figure out a reasonable tab area height
		// based on the tab's font metrics

		const int nNominalHeight = 24;
		const int nNominalFontLogicalUnits = 11;	// 8 point Tahoma with 96 DPI

		// Initialize nFontLogicalUnits to the typical case
		// appropriate for CDotNetTabCtrl
		LOGFONT lfIcon = { 0 };
		::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIcon), &lfIcon, 0);
		int nFontLogicalUnits = -lfIcon.lfHeight;

		// Use the actual font of the tab control
		TTabCtrl& TabCtrl = this->GetTabCtrl();
		if(TabCtrl.IsWindow())
		{
			HFONT hFont = TabCtrl.GetFont();
			if(hFont != NULL)
			{
				CClientDC dc(TabCtrl);
				CFontHandle hFontOld = dc.SelectFont(hFont);
				TEXTMETRIC tm = {0};
				dc.GetTextMetrics(&tm);
				nFontLogicalUnits = tm.tmAscent;
				dc.SelectFont(hFontOld);
			}
		}

		int nNewTabAreaHeight = nNominalHeight + ( ::MulDiv(nNominalHeight, nFontLogicalUnits, nNominalFontLogicalUnits) - nNominalHeight ) / 2;

		T* pT = static_cast<T*>(this);
		pT->SetTabAreaHeight(nNewTabAreaHeight);
	}

// Methods
public:
	TTabCtrl& GetTabCtrl(void)
	{
		return m_TabCtrl;
	}

	int GetTabAreaHeight(void) const
	{
		return m_nTabAreaHeight;
	}

	void SetMinTabCountForVisibleTabs(size_t nMinTabCountForVisibleTabs)
	{
		if(m_nMinTabCountForVisibleTabs != nMinTabCountForVisibleTabs)
		{
			T* pT = static_cast<T*>(this);
			m_nMinTabCountForVisibleTabs = nMinTabCountForVisibleTabs;
			size_t nCurrentTabCount = m_TabCtrl.GetItemCount();
			if(nCurrentTabCount < m_nMinTabCountForVisibleTabs)
			{
				pT->HideTabControl();
			}
			else
			{
				pT->ShowTabControl();
			}
		}
	}

	void CreateTabWindow(HWND hWndTabParent, RECT rcTab, DWORD dwOtherStyles = CTCS_TOOLTIPS)
	{
		if(m_TabCtrl.IsWindow())
		{
			m_TabCtrl.DestroyWindow();
		}

		BOOL bCreate = FALSE;
		bCreate = m_ImageList.Create(m_cxImage, m_cyImage, ILC_COLOR32 | ILC_MASK, 4, 4);
		if(bCreate)
		{
			m_TabCtrl.SetImageList(m_ImageList);
		}

		DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | dwOtherStyles;

		m_TabCtrl.Create(hWndTabParent, rcTab, NULL, dwStyle);

		T* pT = static_cast<T*>(this);
		pT->CalcTabAreaHeight();
	}

	BOOL DestroyTabWindow()
	{
		return m_ImageList.Destroy();
	}

	// AddBitmap (with a couple of overloaded versions)
	int AddBitmap(HBITMAP hBitmap, HBITMAP hBitmapMask = NULL)
	{
		return m_ImageList.Add(hBitmap, hBitmapMask);
	}

	int AddBitmap(HBITMAP hBitmap, COLORREF crMask)
	{
		return m_ImageList.Add(hBitmap, crMask);
	}

	int AddBitmap(_U_STRINGorID bitmap, COLORREF crMask, HMODULE hModule = _Module.GetResourceInstance())
	{
		HBITMAP hBitmap = (HBITMAP)::LoadImage(
			hModule,
			bitmap.m_lpstr,
			IMAGE_BITMAP, 0, 0, LR_SHARED);
		return hBitmap ? m_ImageList.Add(hBitmap, crMask) : -1;
	}

	int AddBitmap(_U_STRINGorID bitmap, HBITMAP hBitmapMask = NULL, HMODULE hModule = _Module.GetResourceInstance())
	{
		HBITMAP hBitmap = (HBITMAP)::LoadImage(
			hModule,
			bitmap.m_lpstr,
			IMAGE_BITMAP, 0, 0, LR_SHARED);
		return hBitmap ? m_ImageList.Add(hBitmap, hBitmapMask) : -1;
	}

	// AddIcon (with a couple of overloaded versions)
	int AddIcon(HICON hIcon)
	{
		return m_ImageList.AddIcon(hIcon);
	}

	int AddIcon(_U_STRINGorID icon, HMODULE hModule = _Module.GetResourceInstance())
	{
		HICON hIcon = (HICON)::LoadImage(
			hModule,
			icon.m_lpstr,
			IMAGE_ICON, m_cxImage, m_cyImage, LR_SHARED);
		return hIcon ? m_ImageList.AddIcon(hIcon) : -1;
	}

	// AddTabWithBitmap (with a couple of overloaded versions)
	int AddTabWithBitmap(HWND hWnd, LPCTSTR sTabText, HBITMAP hBitmap, HBITMAP hBitmapMask = NULL)
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddBitmap(hBitmap, hBitmapMask);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	int AddTabWithBitmap(HWND hWnd, LPCTSTR sTabText, HBITMAP hBitmap, COLORREF crMask)
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddBitmap(hBitmap, crMask);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	int AddTabWithBitmap(HWND hWnd, LPCTSTR sTabText, _U_STRINGorID bitmap, HBITMAP hBitmapMask = NULL, HMODULE hModule = _Module.GetResourceInstance())
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddBitmap(bitmap, hBitmapMask, hModule);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	int AddTabWithBitmap(HWND hWnd, LPCTSTR sTabText, _U_STRINGorID bitmap, COLORREF crMask, HMODULE hModule = _Module.GetResourceInstance())
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddBitmap(bitmap, crMask, hModule);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	// AddTabWithIcon (with a couple of overloaded versions)
	int AddTabWithIcon(HWND hWnd, LPCTSTR sTabText, HICON hIcon)
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddIcon(hIcon);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	int AddTabWithIcon(HWND hWnd, LPCTSTR sTabText, _U_STRINGorID icon, HMODULE hModule = _Module.GetResourceInstance())
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nImageIndex = this->AddIcon(icon, hModule);

		return this->AddTab(hWnd, sTabText, nImageIndex);
	}

	// AddTab - either referencing an image in the image list, or no image used
	int AddTab(HWND hWnd, LPCTSTR sTabText, int nImageIndex = -1)
	{
		if(hWnd == NULL)
		{
			return -1;
		}

		int nNewTabIndex = -1;

		TTabCtrl::TItem* pItem = m_TabCtrl.CreateNewItem();
		if(pItem)
		{
			pItem->SetText(sTabText);
			pItem->SetImageIndex(nImageIndex);
			// NOTE: You must use a tab item class derived off of CCustomTabCtrl
			//  that tracks a view HWND, such as CTabViewTabItem
			pItem->SetTabView(hWnd);

			size_t nOldCount = m_TabCtrl.GetItemCount();

			// The tab control takes ownership of the new item
			nNewTabIndex = m_TabCtrl.InsertItem(nOldCount, pItem);

			size_t nNewCount = m_TabCtrl.GetItemCount();

			if((nOldCount+1) == nNewCount)
			{
				T* pT = static_cast<T*>(this);
				pT->OnAddTab(nNewCount);
			}
		}

		return nNewTabIndex;
	}

	int DisplayTab(HWND hWnd, BOOL bAddIfNotFound = TRUE, BOOL bUseIcon = FALSE)
	{
		int nTab = -1;
		if(hWnd)
		{
			TTabCtrl::TItem tcItem;
			tcItem.SetTabView(hWnd);

			nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
			if((bAddIfNotFound == TRUE) && (nTab < 0))
			{
				// The corresponding tab doesn't exist yet. Create it.

				LPTSTR sWindowText = NULL;
				int cchWindowText = ::GetWindowTextLength(hWnd);
				if(cchWindowText > 0)
				{
					sWindowText = new TCHAR[cchWindowText + 1];
					if(sWindowText != NULL)
					{
						::GetWindowText(hWnd, sWindowText, cchWindowText+1);

						HICON hIcon = NULL;
						if(bUseIcon)
						{
							if(hIcon == NULL)
							{
								hIcon = (HICON) ::SendMessage(hWnd, WM_GETICON, ICON_SMALL, 0);
							}
							if(hIcon == NULL)
							{
// need conditional code because types don't match in winuser.h
#ifdef _WIN64
								hIcon = (HICON)::GetClassLongPtr(hWnd, GCLP_HICONSM);
#else
								hIcon = (HICON)LongToHandle(::GetClassLongPtr(hWnd, GCLP_HICONSM));
#endif
							}
							if(hIcon == NULL)
							{
								hIcon = (HICON) ::SendMessage(hWnd, WM_GETICON, ICON_BIG, 0);
							}
							if(hIcon == NULL)
							{
// need conditional code because types don't match in winuser.h
#ifdef _WIN64
								hIcon = (HICON)::GetClassLongPtr(hWnd, GCLP_HICON);
#else
								hIcon = (HICON)LongToHandle(::GetClassLongPtr(hWnd, GCLP_HICON));
#endif
							}
						}

						if(hIcon == NULL)
						{
							nTab = AddTab(hWnd, sWindowText);
						}
						else
						{
							nTab = AddTabWithIcon(hWnd, sWindowText, hIcon);
						}

						delete [] sWindowText;
					}
				}

				if(nTab < 0)
				{
					// We had trouble getting the window text
					// TODO: What should we put for the text and/or icon
					//  in this case?
					ATLASSERT(0 && "Adding a tab where no name was provided");
					nTab = AddTab(hWnd, _T("Untitled"));
				}
			}

			if(nTab >= 0)
			{
				m_TabCtrl.SetCurSel(nTab);
			}

		}

		return nTab;
	}

	BOOL RemoveTab(HWND hWnd)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			size_t nOldCount = m_TabCtrl.GetItemCount();

			bSuccess = m_TabCtrl.DeleteItem(nTab);

			size_t nNewCount = m_TabCtrl.GetItemCount();

			T* pT = static_cast<T*>(this);
			if((nOldCount-1) == nNewCount)
			{
				pT->OnRemoveTab(nNewCount);
			}
		}

		return bSuccess;
	}

	BOOL UpdateTabText(HWND hWnd, LPCTSTR sText = NULL)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(nTab);
			_CSTRING_NS::CString sCurrentTabText = pItem->GetText();

			if(sText != NULL)
			{
				if(sCurrentTabText != sText)
				{
					bSuccess = pItem->SetText(sText);
					m_TabCtrl.UpdateLayout();
					m_TabCtrl.Invalidate();
				}
			}
			else
			{
				LPTSTR sWindowText = NULL;
				int cchWindowText = ::GetWindowTextLength(hWnd);
				if(cchWindowText > 0)
				{
					sWindowText = new TCHAR[cchWindowText + 1];
					if(sWindowText != NULL)
					{
						::GetWindowText(hWnd, sWindowText, cchWindowText+1);

						if(sWindowText != NULL &&
							sCurrentTabText != sWindowText)
						{
							bSuccess = pItem->SetText(sWindowText);
							m_TabCtrl.UpdateLayout();
							m_TabCtrl.Invalidate();
						}

						delete [] sWindowText;
					}
				}
			}
		}

		return bSuccess;
	}

	BOOL UpdateTabImage(HWND hWnd, int nImageIndex = -1)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(nTab);
			int nCurrentImageIndex = pItem->GetImageIndex();
			if(nCurrentImageIndex != nImageIndex)
			{
				bSuccess = pItem->SetImageIndex(nImageIndex);
				m_TabCtrl.UpdateLayout();
				m_TabCtrl.Invalidate();
			}
		}

		return bSuccess;
	}

	BOOL UpdateTabToolTip(HWND hWnd, LPCTSTR sToolTip = NULL)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(nTab);
			_CSTRING_NS::CString sCurrentToolTip = pItem->GetToolTip();
			if(sCurrentToolTip != sToolTip)
			{
				bSuccess = pItem->SetToolTip(sToolTip);
			}
		}

		return bSuccess;
	}

	BOOL HighlightTab(HWND hWnd, bool bHighlight = true)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			bSuccess = m_TabCtrl.HighlightItem((size_t)nTab, bHighlight);
		}

		return bSuccess;
	}

	BOOL UpdateTabCanClose(HWND hWnd, bool bCanClose = true)
	{
		BOOL bSuccess = FALSE;

		TTabCtrl::TItem tcItem;
		tcItem.SetTabView(hWnd);

		int nTab = m_TabCtrl.FindItem(&tcItem, CTFI_TABVIEW);
		if(nTab >= 0)
		{
			TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(nTab);
			bool bCurrentCanClose = pItem->CanClose();
			if(bCurrentCanClose != bCanClose)
			{
				bSuccess = pItem->SetCanClose(bCanClose);
				m_TabCtrl.UpdateLayout();
				m_TabCtrl.Invalidate();
			}
		}

		return bSuccess;
	}
};

/////////////////////////////////////////////////////////////////////////////
//
// CTabbedFrameImpl
//
/////////////////////////////////////////////////////////////////////////////

#define CHAIN_ACTIVETABVIEW_COMMANDS() \
	if(uMsg == WM_COMMAND && m_hWndActive != NULL) \
		::SendMessage(m_hWndActive, uMsg, wParam, lParam);

#define CHAIN_ACTIVETABVIEW_CHILD_COMMANDS(tabClass) \
	if(uMsg == WM_COMMAND) \
	{ \
		HWND hWndChild = tabClass.GetActiveView(); \
		if(hWndChild != NULL) \
			::SendMessage(hWndChild, uMsg, wParam, lParam); \
	}

// Use this if forwarding to an ActiveX control.
#define CHAIN_ACTIVETABVIEW_CHILD_COMMANDS2(tabClass) \
	if(uMsg == WM_COMMAND) \
	{ \
		HWND hWndChild = tabClass.GetActiveView(); \
		if(hWndChild != NULL) \
			::SendMessage(hWndChild, uMsg, wParam, 0); \
	}

template <
	class T,
	class TTabCtrl = CDotNetTabCtrl<CTabViewTabItem>,
	class TBase = WTL::CFrameWindowImpl<T, ATL::CWindow, ATL::CFrameWinTraits> >
class CTabbedFrameImpl :
	public TBase,
	public CCustomTabOwnerImpl<T, TTabCtrl>
{
protected:
	typedef CTabbedFrameImpl<T, TTabCtrl, TBase> thisClass;
	typedef TBase baseClass;
	typedef CCustomTabOwnerImpl<T, TTabCtrl> customTabOwnerClass;

// Member variables
protected:
	bool m_bReflectNotifications, m_bForwardNotifications;
	DWORD m_nTabStyles;
	HWND m_hWndActive;

// Constructors
public:
	CTabbedFrameImpl(bool bReflectNotifications = false, bool bForwardNotifications = false) :
		m_bReflectNotifications(bReflectNotifications),
		m_bForwardNotifications(bForwardNotifications),
		m_nTabStyles(CTCS_BOTTOM | CTCS_TOOLTIPS),
		m_hWndActive(NULL)
	{
		m_nMinTabCountForVisibleTabs = 1;
		m_bKeepTabsHidden = (m_nMinTabCountForVisibleTabs > 0);
	}

// Methods
public:
	void SetReflectNotifications(bool bReflectNotifications = true)
	{
		m_bReflectNotifications = bReflectNotifications;
	}

	bool GetReflectNotifications(void) const
	{
		return m_bReflectNotifications;
	}

	void SetForwardNotifications(bool bForwardNotifications = true)
	{
		m_bForwardNotifications = bForwardNotifications;
	}

	bool GetForwardNotifications(void) const
	{
		return m_bForwardNotifications;
	}

	void SetTabStyles(DWORD nTabStyles)
	{
		m_nTabStyles = nTabStyles;
	}

	DWORD GetTabStyles(void) const
	{
		return m_nTabStyles;
	}

	void ModifyTabStyles(DWORD dwRemove, DWORD dwAdd)
	{
		DWORD dwNewStyle = (m_nTabStyles & ~dwRemove) | dwAdd;
		if(m_nTabStyles != dwNewStyle)
		{
			m_nTabStyles = dwNewStyle;
		}
	}

	HWND GetActiveView(void) const
	{
		return m_hWndActive;
	}

	virtual void OnFinalMessage(HWND /*hWnd*/)
	{
		// TODO: Have support both for "new"ing an
		//  instance of this class, or having
		//  a member variable of this class.
		//  Currently, we don't support deleting our
		//  instance because someone created us with "new"
		//delete this;
	}

// Message Handling
public:
	// The class that derives from this class should set an appropriate background brush
	DECLARE_FRAME_WND_CLASS_EX(_T("TabbedFrame"), 0, 0, COLOR_APPWORKSPACE)

	BEGIN_MSG_MAP(thisClass)
		MESSAGE_HANDLER(WM_CREATE, OnCreate)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
		MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
		MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
		MESSAGE_HANDLER(WM_FORWARDMSG, OnForwardMsg)

		NOTIFY_CODE_HANDLER(NM_CLICK, OnClick)
		NOTIFY_CODE_HANDLER(CTCN_ACCEPTITEMDRAG, OnAcceptItemDrag)
		NOTIFY_CODE_HANDLER(CTCN_CANCELITEMDRAG, OnCancelItemDrag)
		NOTIFY_CODE_HANDLER(CTCN_DELETEITEM, OnDeleteItem)
		NOTIFY_CODE_HANDLER(CTCN_SELCHANGING, OnSelChanging)
		NOTIFY_CODE_HANDLER(CTCN_SELCHANGE, OnSelChange)

		CHAIN_MSG_MAP(baseClass)

		// If there are key messages that haven't been handled yet,
		// pass those along to the active child window
		if(uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST)
		{
			if(m_hWndActive != NULL && ::IsWindow(m_hWndActive))
			{
				lResult = ::SendMessage(m_hWndActive, uMsg, wParam, lParam);

				return TRUE;
			}
		}

		CHAIN_ACTIVETABVIEW_COMMANDS()
		if(m_bReflectNotifications)
		{
			REFLECT_NOTIFICATIONS()
		}
		if(m_bForwardNotifications)
		{
			FORWARD_NOTIFICATIONS()
		}
	END_MSG_MAP()

	LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
	{
		// "baseClass::OnCreate()"
		LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
		bHandled = TRUE;
		if(lRet == -1)
		{
			return -1;
		}

		// The derived C++ class should set the background brush for
		// the window class (DECLARE_FRAME_WND_CLASS_EX)
		//::SetClassLongPtr(m_hWnd, GCLP_HBRBACKGROUND, COLOR_APPWORKSPACE+1);

		this->CreateTabWindow(m_hWnd, rcDefault, m_nTabStyles);

		return 0;
	}

	LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
	{
		DestroyTabWindow();

		// Say that we didn't handle it so that anyone else
		//  interested gets to handle the message
		bHandled = FALSE;
		return 0;
	}

	LRESULT OnSettingChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
	{
		// Be sure tab gets message before we recalculate the tab area height,
		//  so that it can adjust its font metrics first.
		// NOTE: This causes the tab to get the WM_SETTINGCHANGE message twice,
		//  but that's OK.
		m_TabCtrl.SendMessage(uMsg, wParam, lParam);

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

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
	{
		if(m_hWndActive)
		{
			// Let the active view and the tabs do all the drawing
			// as flicker-free as possible.
			bHandled = TRUE;
			return 1;
		}
		else
		{
			// There is no active tab view.
			// Let the default erase happen with the window class brush.
			bHandled = FALSE;
			return 0;
		}
	}

	LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
	{
		// NOTE: ::IsWindowVisible(m_hWndActive) will be false if
		//  the frame is maximized.  So just use "IsWindow" instead.
		if(m_hWndActive != NULL && ::IsWindow(m_hWndActive))
		{
			// Also - only forward the focus on to the active view
			// if the tab isn't currently capturing the mouse
			if(m_TabCtrl != ::GetCapture())
			{
				::SetFocus(m_hWndActive);
			}
		}

		bHandled = FALSE;
		return 1;
	}

	LRESULT OnForwardMsg(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
	{
		//LPMSG pMsg = (LPMSG)lParam;
		//
		//if(PreTranslateMessage(pMsg))
		//	return TRUE;
		//
		//return m_view.PreTranslateMessage(pMsg);

		return ::SendMessage(m_hWndActive, WM_FORWARDMSG, 0, lParam);
	}

	LRESULT OnClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
			// If they left click on an item, set focus on the tab view,
			// but only if the view was already the active tab view.
			NMCTCITEM* item = (NMCTCITEM*)pnmh;
			if(item && (item->iItem >= 0) && (item->iItem == m_TabCtrl.GetCurSel()))
			{
				TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(item->iItem);
				if(pItem->UsingTabView())
				{
					::SetFocus(pItem->GetTabView());
				}
			}
		}

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnAcceptItemDrag(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
			// If finished dragging, set focus on the tab view.
			NMCTC2ITEMS* item = (NMCTC2ITEMS*)pnmh;
			if(item && (item->iItem2 >= 0))
			{
				TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(item->iItem2);
				if(pItem->UsingTabView())
				{
					::SetFocus(pItem->GetTabView());
				}
			}
		}

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnCancelItemDrag(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
			// If finished dragging, set focus on the tab view.
			NMCTCITEM* item = (NMCTCITEM*)pnmh;
			if(item && (item->iItem >= 0))
			{
				TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(item->iItem);
				if(pItem->UsingTabView())
				{
					::SetFocus(pItem->GetTabView());
				}
			}
		}

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnDeleteItem(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
		}

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnSelChanging(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
		}

		bHandled = FALSE;
		return 0;
	}

	LRESULT OnSelChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
	{
		// Be sure the notification is from the tab control
		// (and not from a sibling like a list view control)
		if(pnmh && (m_TabCtrl == pnmh->hwndFrom))
		{
			int nNewTab = m_TabCtrl.GetCurSel();

			if(nNewTab >= 0)
			{
				TTabCtrl::TItem* pItem = m_TabCtrl.GetItem(nNewTab);
				if(pItem->UsingTabView())
				{
					HWND hWndNew = pItem->GetTabView();
					HWND hWndOld = m_hWndActive;
					if( hWndNew != hWndOld )
					{
						m_hWndActive = hWndNew;

						//UpdateLayout is going to essentially do a
						//  "ShowWindow(hWndNew, SW_SHOW)" for us
						// (Call the most derived class's version of UpdateLayout)
						T* pT = static_cast<T*>(this);
						pT->UpdateLayout();

						if(hWndOld)
						{
							::ShowWindow(hWndOld, SW_HIDE);
						}

						::SetFocus(hWndNew);
					}
				}
			}
		}

		bHandled = FALSE;
		return 0;
	}

// Overrides from CCustomTabOwnerImpl
public:

	void OnRemoveTab(size_t nNewTabCount)
	{
		T* pT = static_cast<T*>(this);

		// NOTE: Derived classes should call this base class version as well
		if(nNewTabCount == 0)
		{
			m_hWndActive = NULL;
		}

		customTabOwnerClass::OnRemoveTab(nNewTabCount);
	}

	void SetTabAreaHeight(int nNewTabAreaHeight)
	{
		if(m_bKeepTabsHidden)
		{
			m_nTabAreaHeight = 0;

			T* pT = static_cast<T*>(this);
			pT->UpdateLayout();
			Invalidate();
		}
		else if(m_nTabAreaHeight != nNewTabAreaHeight)
		{
			m_nTabAreaHeight = nNewTabAreaHeight;

			T* pT = static_cast<T*>(this);
			pT->UpdateLayout();
			Invalidate();
		}
	}

// Overrides from TBase
public:

	void UpdateLayout(BOOL bResizeBars = TRUE)
	{
		RECT rect;
		GetClientRect(&rect);

		// position bars and offset their dimensions
		T* pT = static_cast<T*>(this);
		pT->UpdateBarsPosition(rect, bResizeBars);

		/*
		// resize client window
		if(m_hWndClient != NULL)
			::SetWindowPos(m_hWndClient, NULL, rect.left, rect.top,
				rect.right - rect.left, rect.bottom - rect.top,
				SWP_NOZORDER | SWP_NOACTIVATE);
		*/

		int nWindowPosCount=0;
		if(m_TabCtrl) nWindowPosCount++;
		if(m_hWndActive) nWindowPosCount++;

		if(nWindowPosCount > 0)
		{
			HDWP hdwp = BeginDeferWindowPos(nWindowPosCount);
			DWORD dwStyle = (DWORD)m_TabCtrl.GetWindowLong(GWL_STYLE);
			if(CTCS_BOTTOM == (dwStyle & CTCS_BOTTOM))
			{
				if(m_TabCtrl)
				{
					::DeferWindowPos(
						hdwp,
						m_TabCtrl,
						NULL,
						rect.left, rect.bottom - m_nTabAreaHeight,
						rect.right - rect.left, m_nTabAreaHeight,
						SWP_NOZORDER | SWP_NOACTIVATE);
				}
				if(m_hWndActive)
				{
					::DeferWindowPos(
						hdwp,
						m_hWndActive,
						NULL,
						rect.left, rect.top,
						rect.right - rect.left, (rect.bottom-m_nTabAreaHeight) - rect.top,
						SWP_NOZORDER | SWP_SHOWWINDOW);
				}
			}
			else
			{
				if(m_TabCtrl)
				{
					::DeferWindowPos(
						hdwp,
						m_TabCtrl,
						NULL,
						rect.left, rect.top,
						rect.right-rect.left, m_nTabAreaHeight,
						SWP_NOZORDER | SWP_NOACTIVATE);
				}
				if(m_hWndActive)
				{
					::DeferWindowPos(
						hdwp,
						m_hWndActive,
						NULL,
						rect.left, rect.top + m_nTabAreaHeight,
						rect.right - rect.left,
						rect.bottom - (rect.top+m_nTabAreaHeight),
						SWP_NOZORDER | SWP_SHOWWINDOW);
				}
			}
			EndDeferWindowPos(hdwp);
		}

		m_TabCtrl.UpdateLayout();
	}
};

/////////////////////////////////////////////////////////////////////////////
//
// CTabbedPopupFrame
//
/////////////////////////////////////////////////////////////////////////////

typedef ATL::CWinTraits<WS_POPUP | WS_CAPTION | WS_VISIBLE | WS_SYSMENU | WS_THICKFRAME, WS_EX_TOOLWINDOW> TabbedPopupFrameWinTraits;

template <class TTabCtrl = CDotNetTabCtrl<CTabViewTabItem> >
class CTabbedPopupFrame :
	public CTabbedFrameImpl<CTabbedPopupFrame<TTabCtrl>, TTabCtrl, WTL::CFrameWindowImpl<CTabbedPopupFrame<TTabCtrl>, ATL::CWindow, TabbedPopupFrameWinTraits> >
{
protected:
	typedef CTabbedPopupFrame<TTabCtrl> thisClass;
	typedef CTabbedFrameImpl<CTabbedPopupFrame, TTabCtrl, WTL::CFrameWindowImpl<CTabbedPopupFrame, ATL::CWindow, TabbedPopupFrameWinTraits> > baseClass;

// Members:
protected:
	// NOTE: If the "Close Command" is 0, than we really
	//  just let the default frame handling of "closing"
	//  happen, otherwise, we send the specified command to the parent
	WORD m_nCloseCommand;

// Constructors
public:
	CTabbedPopupFrame(bool bReflectNotifications = false) :
		baseClass(bReflectNotifications),
		m_nCloseCommand(0U)
	{
	}

// Accessors
public:
	WORD GetCloseCommand(void) const
	{
		return m_nCloseCommand;
	}

	void SetCloseCommand(WORD nCloseCommand)
	{
		m_nCloseCommand = nCloseCommand;
	}

// Message Handling
public:
	DECLARE_FRAME_WND_CLASS_EX(_T("TabbedPopupFrame"), 0, 0, COLOR_APPWORKSPACE)

	BOOL PreTranslateMessage(MSG* pMsg)
	{
		if(baseClass::PreTranslateMessage(pMsg))
			return TRUE;

		//return m_view.PreTranslateMessage(pMsg);

		HWND hWndFocus = ::GetFocus();
		if(m_hWndActive != NULL && ::IsWindow(m_hWndActive) &&
			(m_hWndActive == hWndFocus || ::IsChild(m_hWndActive, hWndFocus)))
		{
			//active.PreTranslateMessage(pMsg);
			if(::SendMessage(m_hWndActive, WM_FORWARDMSG, 0, (LPARAM)pMsg))
			{
				return TRUE;
			}
		}

		return FALSE;
	}

	BEGIN_MSG_MAP(thisClass)
		if(m_nCloseCommand != 0)
		{
			if(uMsg == WM_SYSCOMMAND && wParam == SC_CLOSE)
			{
				bHandled = TRUE;
				lResult = ::SendMessage(this->GetParent(), WM_COMMAND, MAKEWPARAM(m_nCloseCommand, 0), 0);

				return TRUE;
			}
		}
		CHAIN_MSG_MAP(baseClass)
	END_MSG_MAP()
};

/////////////////////////////////////////////////////////////////////////////
//
// CTabbedChildWindow
//
/////////////////////////////////////////////////////////////////////////////

// We need CTabbedChildWindowBase because of how CTabbedFrameImpl is currently implemented -
// It's expecting that the "base" class to usually be derived from CFrameWindowImpl.
// We'll have this special class for CTabbedChildWindow to
// inherit from instead of CWindowImpl, so that we provide
// the couple of extra things that CTabbedFrameImpl would
// like to be able to depend on (currently - a message map that
// at least handles WM_SIZE and overrideable methods
// "UpdateLayout" and "UpdateBarsPosition")

typedef ATL::CWinTraits<WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE> TabbedChildWindowWinTraits;

template <class T, class TBase = ATL::CWindow, class TWinTraits = TabbedChildWindowWinTraits>
class ATL_NO_VTABLE CTabbedChildWindowBase : public ATL::CWindowImpl< T, TBase, TWinTraits >
{
	typedef CTabbedChildWindowBase< T, TBase, TWinTraits >	thisClass;
	BEGIN_MSG_MAP(thisClass)
		MESSAGE_HANDLER(WM_SIZE, OnSize)
	END_MSG_MAP()

	LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
	{
		if(wParam != SIZE_MINIMIZED)
		{
			T* pT = static_cast<T*>(this);
			pT->UpdateLayout();
		}
		bHandled = FALSE;
		return 1;
	}

// Overrideables
public:
	void UpdateLayout(BOOL bResizeBars = TRUE)
	{
	}

	void UpdateBarsPosition(RECT& /*rect*/, BOOL bResizeBars = TRUE)
	{
		bResizeBars; //avoid level 4 warning
	}
};

template <class TTabCtrl = CDotNetTabCtrl<CTabViewTabItem> >
class CTabbedChildWindow :
	public CTabbedFrameImpl<CTabbedChildWindow<TTabCtrl>, TTabCtrl, CTabbedChildWindowBase<CTabbedChildWindow<TTabCtrl>, ATL::CWindow, TabbedChildWindowWinTraits> >
{
protected:
	typedef CTabbedChildWindow<TTabCtrl> thisClass;
	typedef CTabbedFrameImpl<CTabbedChildWindow<TTabCtrl>, TTabCtrl, CTabbedChildWindowBase<CTabbedChildWindow, ATL::CWindow, TabbedChildWindowWinTraits> > baseClass;

// Constructors
public:
	CTabbedChildWindow(bool bReflectNotifications = false) :
		baseClass(bReflectNotifications)
	{
	}

// Message Handling
public:
	DECLARE_FRAME_WND_CLASS_EX(_T("TabbedChildWindow"), 0, 0, COLOR_APPWORKSPACE)

	BOOL PreTranslateMessage(MSG* pMsg)
	{
		//if(baseClass::PreTranslateMessage(pMsg))
		//	return TRUE;

		//return m_view.PreTranslateMessage(pMsg);

		HWND hWndFocus = ::GetFocus();
		if(m_hWndActive != NULL && ::IsWindow(m_hWndActive) &&
			(m_hWndActive == hWndFocus || ::IsChild(m_hWndActive, hWndFocus)))
		{
			//active.PreTranslateMessage(pMsg);
			if(::SendMessage(m_hWndActive, WM_FORWARDMSG, 0, (LPARAM)pMsg))
			{
				return TRUE;
			}
		}

		return FALSE;
	}

	BEGIN_MSG_MAP(thisClass)
		CHAIN_MSG_MAP(baseClass)
	END_MSG_MAP()
};

#endif // __WTL_TABBED_FRAME_H__


text:
#include "curses.ext"
#include <stdlib.h>

/*
 * This routine deletes a window and releases it back to the system.
 */
int
delwin(win)
        reg WINDOW	*win;
{
	reg int		i;
	reg WINDOW	*wp, *np;

	if (win->_orig == NULL) {
		/*
		 * If we are the original window, delete the space for
		 * all the subwindows, and the array of space as well.
		 */
		for (i = 0; i < win->_maxy && win->_y[i]; i++)
			free(win->_y[i]);
		free(win->_firstch);
		free(win->_lastch);
		wp = win->_nextp;
		while (wp != win) {
			np = wp->_nextp;
			delwin(wp);
			wp = np;
		}
	} else {
		/*
		 * If we are a subwindow, take ourselves out of the
		 * list.  NOTE: if we are a subwindow, the minimum list
		 * is orig followed by this subwindow, so there are
		 * always at least two windows in the list.
		 */
		for (wp = win->_nextp; wp->_nextp != win; wp = wp->_nextp)
			continue;
		wp->_nextp = win->_nextp;
	}
	free(win->_y);
	free(win);
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
@interface SelectTableViewCell : UITableViewCell

@property (nonatomic, strong) SelectModel *model;

@end


text:
            <?php if($menu == "Sales Menu") {?>

                <a href="#" class="list-group-item <?php if (uri_string() == "jobcostings") { ?>active<?php } ?>">Job Costings
                Quotes
                List Data

            <?php } ?>


text:
package com.microsoft.azure.management.batchai.v2017_09_01_preview;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.batchai.v2017_09_01_preview.implementation.BatchAIManager;
import com.microsoft.azure.management.batchai.v2017_09_01_preview.implementation.FileInner;
import org.joda.time.DateTime;

/**
 * Type representing File.
 */
public interface File extends HasInner<FileInner>, HasManager<BatchAIManager> {
    /**
     * @return the contentLength value.
     */
    Long contentLength();

    /**
     * @return the downloadUrl value.
     */
    String downloadUrl();

    /**
     * @return the lastModified value.
     */
    DateTime lastModified();

    /**
     * @return the name value.
     */
    String name();

}


text:
namespace llvm {

class AllocaInst;
class BasicBlock;
class BranchProbabilityInfo;
class CallInst;
class Function;
class GlobalVariable;
class Instruction;
class MachineInstr;
class MachineBasicBlock;
class MachineFunction;
class MachineModuleInfo;
class MachineRegisterInfo;
class SelectionDAG;
class MVT;
class TargetLowering;
class Value;

//===--------------------------------------------------------------------===//
/// FunctionLoweringInfo - This contains information that is global to a
/// function that is used when lowering a region of the function.
///
class FunctionLoweringInfo {
public:
  const Function *Fn;
  MachineFunction *MF;
  const TargetLowering *TLI;
  MachineRegisterInfo *RegInfo;
  BranchProbabilityInfo *BPI;
  /// CanLowerReturn - true iff the function's return value can be lowered to
  /// registers.
  bool CanLowerReturn;

  /// DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg
  /// allocated to hold a pointer to the hidden sret parameter.
  unsigned DemoteRegister;

  /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
  DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;

  /// ValueMap - Since we emit code for the function a basic block at a time,
  /// we must remember which virtual registers hold the values for
  /// cross-basic-block values.
  DenseMap<const Value*, unsigned> ValueMap;

  // Keep track of frame indices allocated for statepoints as they could be used
  // across basic block boundaries.
  // Key of the map is statepoint instruction, value is a map from spilled
  // llvm Value to the optional stack stack slot index.
  // If optional is unspecified it means that we have visited this value
  // but didn't spill it.
  typedef DenseMap<const Value*, Optional<int>> StatepointSpilledValueMapTy;
  DenseMap<const Instruction*, StatepointSpilledValueMapTy>
    StatepointRelocatedValues;

  /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
  /// the entry block.  This allows the allocas to be efficiently referenced
  /// anywhere in the function.
  DenseMap<const AllocaInst*, int> StaticAllocaMap;

  /// ByValArgFrameIndexMap - Keep track of frame indices for byval arguments.
  DenseMap<const Argument*, int> ByValArgFrameIndexMap;

  /// ArgDbgValues - A list of DBG_VALUE instructions created during isel for
  /// function arguments that are inserted after scheduling is completed.
  SmallVector<MachineInstr*, 8> ArgDbgValues;

  /// RegFixups - Registers which need to be replaced after isel is done.
  DenseMap<unsigned, unsigned> RegFixups;

  /// StatepointStackSlots - A list of temporary stack slots (frame indices)
  /// used to spill values at a statepoint.  We store them here to enable
  /// reuse of the same stack slots across different statepoints in different
  /// basic blocks.
  SmallVector<unsigned, 50> StatepointStackSlots;

  /// MBB - The current block.
  MachineBasicBlock *MBB;

  /// MBB - The current insert position inside the current block.
  MachineBasicBlock::iterator InsertPt;

#ifndef NDEBUG
  SmallPtrSet<const Instruction *, 8> CatchInfoLost;
  SmallPtrSet<const Instruction *, 8> CatchInfoFound;
#endif

  struct LiveOutInfo {
    unsigned NumSignBits : 31;
    bool IsValid : 1;
    APInt KnownOne, KnownZero;
    LiveOutInfo() : NumSignBits(0), IsValid(true), KnownOne(1, 0),
                    KnownZero(1, 0) {}
  };

  /// Record the preferred extend type (ISD::SIGN_EXTEND or ISD::ZERO_EXTEND)
  /// for a value.
  DenseMap<const Value *, ISD::NodeType> PreferredExtendType;

  /// VisitedBBs - The set of basic blocks visited thus far by instruction
  /// selection.
  SmallPtrSet<const BasicBlock*, 4> VisitedBBs;

  /// PHINodesToUpdate - A list of phi instructions whose operand list will
  /// be updated after processing the current basic block.
  /// TODO: This isn't per-function state, it's per-basic-block state. But
  /// there's no other convenient place for it to live right now.
  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
  unsigned OrigNumPHINodesToUpdate;

  /// If the current MBB is a landing pad, the exception pointer and exception
  /// selector registers are copied into these virtual registers by
  /// SelectionDAGISel::PrepareEHLandingPad().
  unsigned ExceptionPointerVirtReg, ExceptionSelectorVirtReg;

  /// set - Initialize this FunctionLoweringInfo with the given Function
  /// and its associated MachineFunction.
  ///
  void set(const Function &Fn, MachineFunction &MF, SelectionDAG *DAG);

  /// clear - Clear out all the function-specific state. This returns this
  /// FunctionLoweringInfo to an empty state, ready to be used for a
  /// different function.
  void clear();

  /// isExportedInst - Return true if the specified value is an instruction
  /// exported from its block.
  bool isExportedInst(const Value *V) {
    return ValueMap.count(V);
  }

  unsigned CreateReg(MVT VT);

  unsigned CreateRegs(Type *Ty);

  unsigned InitializeRegForValue(const Value *V) {
    unsigned &R = ValueMap[V];
    assert(R == 0 && "Already initialized this value register!");
    return R = CreateRegs(V->getType());
  }

  /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
  /// register is a PHI destination and the PHI's LiveOutInfo is not valid.
  const LiveOutInfo *GetLiveOutRegInfo(unsigned Reg) {
    if (!LiveOutRegInfo.inBounds(Reg))
      return nullptr;

    const LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
    if (!LOI->IsValid)
      return nullptr;

    return LOI;
  }

  /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
  /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
  /// the register's LiveOutInfo is for a smaller bit width, it is extended to
  /// the larger bit width by zero extension. The bit width must be no smaller
  /// than the LiveOutInfo's existing bit width.
  const LiveOutInfo *GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth);

  /// AddLiveOutRegInfo - Adds LiveOutInfo for a register.
  void AddLiveOutRegInfo(unsigned Reg, unsigned NumSignBits,
                         const APInt &KnownZero, const APInt &KnownOne) {
    // Only install this information if it tells us something.
    if (NumSignBits == 1 && KnownZero == 0 && KnownOne == 0)
      return;

    LiveOutRegInfo.grow(Reg);
    LiveOutInfo &LOI = LiveOutRegInfo[Reg];
    LOI.NumSignBits = NumSignBits;
    LOI.KnownOne = KnownOne;
    LOI.KnownZero = KnownZero;
  }

  /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
  /// register based on the LiveOutInfo of its operands.
  void ComputePHILiveOutRegInfo(const PHINode*);

  /// InvalidatePHILiveOutRegInfo - Invalidates a PHI's LiveOutInfo, to be
  /// called when a block is visited before all of its predecessors.
  void InvalidatePHILiveOutRegInfo(const PHINode *PN) {
    // PHIs with no uses have no ValueMap entry.
    DenseMap<const Value*, unsigned>::const_iterator It = ValueMap.find(PN);
    if (It == ValueMap.end())
      return;

    unsigned Reg = It->second;
    if (Reg == 0)
      return;

    LiveOutRegInfo.grow(Reg);
    LiveOutRegInfo[Reg].IsValid = false;
  }

  /// setArgumentFrameIndex - Record frame index for the byval
  /// argument.
  void setArgumentFrameIndex(const Argument *A, int FI);

  /// getArgumentFrameIndex - Get frame index for the byval argument.
  int getArgumentFrameIndex(const Argument *A);

private:
  void addSEHHandlersForLPads(ArrayRef<const LandingPadInst *> LPads);

  /// LiveOutRegInfo - Information about live out vregs.
  IndexedMap<LiveOutInfo, VirtReg2IndexFunctor> LiveOutRegInfo;
};

/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
/// being passed to this variadic function, and set the MachineModuleInfo's
/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
/// reference to _fltused on Windows, which will link in MSVCRT's
/// floating-point support.
void ComputeUsesVAFloatArgument(const CallInst &I, MachineModuleInfo *MMI);

/// AddLandingPadInfo - Extract the exception handling information from the
/// landingpad instruction and add them to the specified machine module info.
void AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
                       MachineBasicBlock *MBB);

} // end namespace llvm

#endif


text:
/**
 * Wraps the given function so that the history log is saved when it is called, and then the given function
 * is run
 *
 * @param {Mocker} mocker     The mocker object
 * @param {Function} fn       The function to run
 * @return {Function}         The wrapped function
 * @api public
 */
function wrapFn(mocker, fn) {
  return function() {
    //Copy the arguments this function was called with
    var args = Array.prototype.slice.call(arguments);

    //Save the arguments to the log
    mocker.history.push(args);

    return fn.apply(this, arguments);
  };
}

/**
 * Mocker constructor
 *
 * @param {Object} obj            Object to create a mock of
 * @param {String} methodName     Method name to mock
 * @param {Function} mockFn       Mock function
 * @return {Mocker}
 * @api public
 */
function Mocker(obj, methodName, mockFn) {
  this.obj = obj;
  this.methodName = methodName;
  this.originalFn = obj[methodName];
  this.history = [];

  //Assign new function
  mockFn = mockFn || this.originalFn;
  obj[methodName] = wrapFn(this, mockFn);
};

Mocker.prototype.restore = function() {
  this.obj[this.methodName] = this.originalFn;
};

Mocker.prototype.lastArgs = function() {
  var history = this.history;

  return history[history.length - 1];
};

Mocker.prototype.timesCalled = function() {
  return this.history.length;
};

var mocks = [];

/**
 * Creates a new Mocker
 *
 * @param {Object} obj            Object to create a mock of
 * @param {String} methodName     Method name to mock
 * @param {Function} mockFn       Mock function
 * @return {Mocker}
 * @api public
 */
exports.mock = function(obj, methodName, mockFn) {
  var mock = new Mocker(obj, methodName, mockFn);

  mocks.push(mock);

  return mock;
};

/**
 * Restores all mocks and release
 *
 * @api public
 */
exports.restore = function(){
  for (var i = 0; i < mocks.length; i++) {
    mocks[i].restore();
  }
  mocks = [];
}


text:
import logging

from .base import Template
from ..devices.device import Device

logging.basicConfig(format='%(asctime)s <%(name)s> %(message)s')
logger = logging.getLogger('uniform_model.templates.other')
logger.setLevel(logging.DEBUG)

class OtherTemplate(Template):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def _check_device_info(self, device_info):
        lack = super()._check_device_info(device_info)
        for item in self.properties:
            if item not in device_info:
                lack.append(item)
        return lack

    def generate_device(self, device_info):
        device = Device(**device_info)
        return device


text:
import * as DOM from 'vs/base/browser/dom';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { DefaultStyleController, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeElement, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { Iterable } from 'vs/base/common/iterator';
import { localize } from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IListService, IWorkbenchObjectTreeOptions, WorkbenchObjectTree } from 'vs/platform/list/browser/listService';
import { editorBackground, focusBorder, foreground, transparent } from 'vs/platform/theme/common/colorRegistry';
import { attachStyler } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { SettingsTreeFilter } from 'vs/workbench/contrib/preferences/browser/settingsTree';
import { ISettingsEditorViewState, SearchResultModel, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeSettingElement } from 'vs/workbench/contrib/preferences/browser/settingsTreeModels';
import { settingsHeaderForeground } from 'vs/workbench/contrib/preferences/common/settingsEditorColorRegistry';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';

const $ = DOM.$;

export class TOCTreeModel {

	private _currentSearchModel: SearchResultModel | null = null;
	private _settingsTreeRoot!: SettingsTreeGroupElement;

	constructor(
		private _viewState: ISettingsEditorViewState,
		@IWorkbenchEnvironmentService private environmentService: IWorkbenchEnvironmentService
	) {
	}

	get settingsTreeRoot(): SettingsTreeGroupElement {
		return this._settingsTreeRoot;
	}

	set settingsTreeRoot(value: SettingsTreeGroupElement) {
		this._settingsTreeRoot = value;
		this.update();
	}

	get currentSearchModel(): SearchResultModel | null {
		return this._currentSearchModel;
	}

	set currentSearchModel(model: SearchResultModel | null) {
		this._currentSearchModel = model;
		this.update();
	}

	get children(): SettingsTreeElement[] {
		return this._settingsTreeRoot.children;
	}

	update(): void {
		if (this._settingsTreeRoot) {
			this.updateGroupCount(this._settingsTreeRoot);
		}
	}

	private updateGroupCount(group: SettingsTreeGroupElement): void {
		group.children.forEach(child => {
			if (child instanceof SettingsTreeGroupElement) {
				this.updateGroupCount(child);
			}
		});

		const childCount = group.children
			.filter(child => child instanceof SettingsTreeGroupElement)
			.reduce((acc, cur) => acc + (<SettingsTreeGroupElement>cur).count!, 0);

		group.count = childCount + this.getGroupCount(group);
	}

	private getGroupCount(group: SettingsTreeGroupElement): number {
		return group.children.filter(child => {
			if (!(child instanceof SettingsTreeSettingElement)) {
				return false;
			}

			if (this._currentSearchModel && !this._currentSearchModel.root.containsSetting(child.setting.key)) {
				return false;
			}

			// Check everything that the SettingsFilter checks except whether it's filtered by a category
			const isRemote = !!this.environmentService.remoteAuthority;
			return child.matchesScope(this._viewState.settingsTarget, isRemote) &&
				child.matchesAllTags(this._viewState.tagFilters) &&
				child.matchesAnyFeature(this._viewState.featureFilters) &&
				child.matchesAnyExtension(this._viewState.extensionFilters) &&
				child.matchesAnyId(this._viewState.idFilters);
		}).length;
	}
}

const TOC_ENTRY_TEMPLATE_ID = 'settings.toc.entry';

interface ITOCEntryTemplate {
	labelElement: HTMLElement;
	countElement: HTMLElement;
}

export class TOCRenderer implements ITreeRenderer<SettingsTreeGroupElement, never, ITOCEntryTemplate> {

	templateId = TOC_ENTRY_TEMPLATE_ID;

	renderTemplate(container: HTMLElement): ITOCEntryTemplate {
		return {
			labelElement: DOM.append(container, $('.settings-toc-entry')),
			countElement: DOM.append(container, $('.settings-toc-count'))
		};
	}

	renderElement(node: ITreeNode<SettingsTreeGroupElement>, index: number, template: ITOCEntryTemplate): void {
		const element = node.element;
		const count = element.count;
		const label = element.label;

		template.labelElement.textContent = label;
		template.labelElement.title = label;

		if (count) {
			template.countElement.textContent = ` (${count})`;
		} else {
			template.countElement.textContent = '';
		}
	}

	disposeTemplate(templateData: ITOCEntryTemplate): void {
	}
}

class TOCTreeDelegate implements IListVirtualDelegate<SettingsTreeElement> {
	getTemplateId(element: SettingsTreeElement): string {
		return TOC_ENTRY_TEMPLATE_ID;
	}

	getHeight(element: SettingsTreeElement): number {
		return 22;
	}
}

export function createTOCIterator(model: TOCTreeModel | SettingsTreeGroupElement, tree: TOCTree): Iterable<ITreeElement<SettingsTreeGroupElement>> {
	const groupChildren = <SettingsTreeGroupElement[]>model.children.filter(c => c instanceof SettingsTreeGroupElement);

	return Iterable.map(groupChildren, g => {
		const hasGroupChildren = g.children.some(c => c instanceof SettingsTreeGroupElement);

		return {
			element: g,
			collapsed: undefined,
			collapsible: hasGroupChildren,
			children: g instanceof SettingsTreeGroupElement ?
				createTOCIterator(g, tree) :
				undefined
		};
	});
}

class SettingsAccessibilityProvider implements IListAccessibilityProvider<SettingsTreeGroupElement> {
	getWidgetAriaLabel(): string {
		return localize({
			key: 'settingsTOC',
			comment: ['A label for the table of contents for the full settings list']
		},
			"Settings Table of Contents");
	}

	getAriaLabel(element: SettingsTreeElement): string {
		if (!element) {
			return '';
		}

		if (element instanceof SettingsTreeGroupElement) {
			return localize('groupRowAriaLabel', "{0}, group", element.label);
		}

		return '';
	}

	getAriaLevel(element: SettingsTreeGroupElement): number {
		let i = 1;
		while (element instanceof SettingsTreeGroupElement && element.parent) {
			i++;
			element = element.parent;
		}

		return i;
	}
}

export class TOCTree extends WorkbenchObjectTree<SettingsTreeGroupElement> {
	constructor(
		container: HTMLElement,
		viewState: ISettingsEditorViewState,
		@IContextKeyService contextKeyService: IContextKeyService,
		@IListService listService: IListService,
		@IThemeService themeService: IThemeService,
		@IConfigurationService configurationService: IConfigurationService,
		@IInstantiationService instantiationService: IInstantiationService,
	) {
		// test open mode

		const filter = instantiationService.createInstance(SettingsTreeFilter, viewState);
		const options: IWorkbenchObjectTreeOptions<SettingsTreeGroupElement, void> = {
			filter,
			multipleSelectionSupport: false,
			identityProvider: {
				getId(e) {
					return e.id;
				}
			},
			styleController: id => new DefaultStyleController(DOM.createStyleSheet(container), id),
			accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
			collapseByDefault: true,
			horizontalScrolling: false,
			hideTwistiesOfChildlessElements: true
		};

		super(
			'SettingsTOC',
			container,
			new TOCTreeDelegate(),
			[new TOCRenderer()],
			options,
			instantiationService,
			contextKeyService,
			listService,
			themeService,
			configurationService,
		);

		this.disposables.add(attachStyler(themeService, {
			listBackground: editorBackground,
			listFocusOutline: focusBorder,
			listActiveSelectionBackground: editorBackground,
			listActiveSelectionForeground: settingsHeaderForeground,
			listFocusAndSelectionBackground: editorBackground,
			listFocusAndSelectionForeground: settingsHeaderForeground,
			listFocusBackground: editorBackground,
			listFocusForeground: transparent(foreground, 0.9),
			listHoverForeground: transparent(foreground, 0.9),
			listHoverBackground: editorBackground,
			listInactiveSelectionBackground: editorBackground,
			listInactiveSelectionForeground: settingsHeaderForeground,
			listInactiveFocusBackground: editorBackground,
			listInactiveFocusOutline: editorBackground
		}, colors => {
			this.style(colors);
		}));
	}
}


text:
namespace DLaB.Xrm.Entities
{

	[System.Runtime.Serialization.DataContractAttribute()]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
	public enum MailMergeTemplate_MailMergeType
	{

		[System.Runtime.Serialization.EnumMemberAttribute()]
		EmailMessage = 2,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Envelope = 3,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Fax = 6,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Labels = 4,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Letter = 1,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		Quotes = 5,
	}
}


text:
==================
The Local Database
==================

The local database is used as a cache for the remote database. Schedule
generation requests will fetch section data from the remote server when
necessary, but terms and courses must be manually seeded.

If one of the following is true, terms and courses will be lazily downloaded
in the background
 - the server is run via python with zero arguments :code:`$ python runserver.py`
 - the server is run via gunicorn and SECRET_KEY is set :code:`$ export SECRET_KEY=something; gunicorn runserver:app -w 3`

By default, a local database is stored as a SQLite database in the filesystem
at /tmp/classtime.db . In production, PostgreSQL is used, so if you are
developing for prod and want to match your environment (because dev/prod parity
is a good thing), do the following:

1. Install PostgreSQL
2. Set DATABASE_URL to your postgre URI

That's it! It should just work.

.. _`seed-db`:

seed\_db
~~~~~~~~

Seed the database with the specified term and all courses in it.

::

 $ python manage.py seed_db [--term TERM]

:TERM: :ref:`4-digit unique term identifier <4-digit-term-identifier>`
       , default='1490' (Fall Term 2014)

.. _`delete-db`:

delete\_db
~~~~~~~~~~

Delete the database completely. This is irreversible.

::

 $ python manage.py delete_db

.. _`refresh-db`:

refresh\_db
~~~~~~~~~~~

Delete and rebuild the database with the specified term and all courses
in it

::

 $ python manage.py refresh_db [--term TERM]

:TERM: :ref:`4-digit unique term identifier <4-digit-term-identifier>`
       , default='1490' (Fall Term 2014)


text:
<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>FusionCharts Free Documentation</title>
<link rel="stylesheet" type="text/css" href="../Style.css">

FusionCharts PHP Class API > Creating Stacked Chart

FusionCharts Free v2 offers Stacked Chart – a type of  Multi-series chart where multiple datasets are stacked one above the other in  each column. Look at the image below; this is how a Stacked Chart looks like:

Before you go further with this page, we recommend you to please see   the previous pages "Creating First Chart " & "Creating Multi-series chart"  as we start off from concepts explained in   that page.

The process of generating Stacked chart is same as  Multi-series chart. The only difference is here we need to specify a different  chart type. Open and modify the Mulit-series chart you have created in the previous page thus:

<?php

 # Include  FusionCharts PHP Class

   include('../Class/FusionCharts_Gen.php');

 # Create Stacked Column3D chart object using FusionCharts PHP Class

   $FC = new  FusionCharts("StackedColumn3D","350","300");

   # Set the relative  path of the swf file

   $FC->setSWFPath("../FusionCharts/");

    ...

As you can see, we have only chaged the chart type to stackedColumn3D while creating the chart object :

$FC = new FusionCharts("StackedColumn3D","350","300");

This does the trick and you will see that instead of a multiseries chart we render a stacked chart.

    Please go through FusionCharts PHP Class API Reference section to know more about the functions used in the above code.

    Here comes the output:


text:
.validation_error {
    position: relative;
    width: 100%;
}

.validation_error ul {
    position: absolute;
    width: 100%;
    background: #960000;
	border: 4px solid #f51414;
    border-radius: 5px;
    padding: 10px;
    margin-top: 50px;
}
.validation_error ul:after, .validation_error ul:before {
	bottom: 100%;
	border: solid transparent;
	content: " ";
	height: 0;
	width: 0;
	position: absolute;
	pointer-events: none;
}

.validation_error ul:after {
	border-color: rgba(150, 0, 0, 0);
	border-bottom-color: #960000;
	border-width: 30px;
	left: 50%;
	margin-left: -30px;
}
.validation_error ul:before {
	border-color: rgba(245, 20, 20, 0);
	border-bottom-color: #f51414;
	border-width: 36px;
	left: 50%;
	margin-left: -36px;
}

.validation_error li {
    color: #fff;
    font-weight: bold;
    padding: 3px 0;
    margin: 0;
    list-style: none;
}


text:
const {
  assertSame, assertEquals, assertUndefined,
  assertBuiltinFunction,
} = Assert;

/* 26.2.3.7.3 Reflect.Realm.prototype.initGlobal ( ) */

const initGlobal = Reflect.Realm.prototype.initGlobal;

assertBuiltinFunction(initGlobal, "initGlobal", 0);

{
  let realm = new Reflect.Realm();
  let global = realm.global;
  let names = Object.getOwnPropertyNames(global);
  let properties = names.reduce((m, n) => m.set(n, Object.getOwnPropertyDescriptor(global, n)), new Map);

  // Remove all global properties
  names.forEach(n => delete global[n]);

  // Assert non-configurable properties are not removed
  assertEquals(["Infinity", "NaN", "undefined"], Object.getOwnPropertyNames(global).sort());

  // Re-init global
  realm.initGlobal();

  // Assert built-ins are restored to the same values
  assertSame(names.length, Object.getOwnPropertyNames(global).length);
  for (let name of names) {
    assertEquals(properties.get(name), Object.getOwnPropertyDescriptor(global, name));
  }
}

{
  let realm = new Reflect.Realm();
  let global = realm.global;
  let propertyName = "customProperty";

  // Add non-standard property on the global object
  Object.defineProperty(global, propertyName, {value: 123, configurable: true});

  // Remove all global properties
  Object.getOwnPropertyNames(global).forEach(n => delete global[n]);

  // Re-init global
  realm.initGlobal();

  // Assert non-standard property is not revived
  assertUndefined(Object.getOwnPropertyDescriptor(global, propertyName));
}


text:
package io.github.droidkaigi.confsched2017.view.fragment;

import android.content.Context;
import android.content.res.Configuration;
import android.databinding.ObservableList;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import javax.inject.Inject;

import io.github.droidkaigi.confsched2017.R;
import io.github.droidkaigi.confsched2017.databinding.FragmentContributorsBinding;
import io.github.droidkaigi.confsched2017.databinding.ViewContributorCellBinding;
import io.github.droidkaigi.confsched2017.view.customview.ArrayRecyclerAdapter;
import io.github.droidkaigi.confsched2017.view.customview.BindingHolder;
import io.github.droidkaigi.confsched2017.viewmodel.ContributorViewModel;
import io.github.droidkaigi.confsched2017.viewmodel.ContributorsViewModel;

public class ContributorsFragment extends BaseFragment implements ContributorsViewModel.Callback {

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

    @Inject
    ContributorsViewModel viewModel;

    private FragmentContributorsBinding binding;

    private Adapter adapter;

    public static ContributorsFragment newInstance() {
        return new ContributorsFragment();
    }

    public ContributorsFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        getComponent().inject(this);
    }

    @Override
    public void onDetach() {
        viewModel.destroy();
        super.onDetach();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel.setCallback(this);
        viewModel.start();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        binding = FragmentContributorsBinding.inflate(inflater, container, false);
        binding.setViewModel(viewModel);

        initView();
        return binding.getRoot();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        menuInflater.inflate(R.menu.menu_contributors, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_repository:
                viewModel.onClickRepositoryMenu();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        adapter = new Adapter(getContext(), viewModel.getContributorViewModels());
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), getColumnCount()));
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ((GridLayoutManager) binding.recyclerView.getLayoutManager()).setSpanCount(getColumnCount());
    }

    @Override
    public void showError(@StringRes int resId) {
        Snackbar.make(binding.getRoot(), resId, Snackbar.LENGTH_INDEFINITE)
                .setAction(R.string.retry, v -> viewModel.retry())
                .setActionTextColor(ContextCompat.getColor(getActivity(), R.color.white))
                .show();
    }

    private int getColumnCount() {
        return getResources().getInteger(R.integer.contributors_columns);
    }

    private static class Adapter
            extends ArrayRecyclerAdapter<ContributorViewModel, BindingHolder<ViewContributorCellBinding>> {

        public Adapter(@NonNull Context context, @NonNull ObservableList<ContributorViewModel> list) {
            super(context, list);

            list.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<ContributorViewModel>>() {
                @Override
                public void onChanged(ObservableList<ContributorViewModel> contributorViewModels) {
                    notifyDataSetChanged();
                }

                @Override
                public void onItemRangeChanged(ObservableList<ContributorViewModel> contributorViewModels, int i, int i1) {
                    notifyItemRangeChanged(i, i1);
                }

                @Override
                public void onItemRangeInserted(ObservableList<ContributorViewModel> contributorViewModels, int i, int i1) {
                    notifyItemRangeInserted(i, i1);
                }

                @Override
                public void onItemRangeMoved(ObservableList<ContributorViewModel> contributorViewModels, int i, int i1,
                        int i2) {
                    notifyItemMoved(i, i1);
                }

                @Override
                public void onItemRangeRemoved(ObservableList<ContributorViewModel> contributorViewModels, int i, int i1) {
                    notifyItemRangeRemoved(i, i1);
                }
            });
        }

        @Override
        public BindingHolder<ViewContributorCellBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BindingHolder<>(getContext(), parent, R.layout.view_contributor_cell);
        }

        @Override
        public void onBindViewHolder(BindingHolder<ViewContributorCellBinding> holder, int position) {
            ContributorViewModel viewModel = getItem(position);
            ViewContributorCellBinding itemBinding = holder.binding;
            itemBinding.setViewModel(viewModel);
            itemBinding.executePendingBindings();
        }
    }
}


text:
module Rugments
  module Lexers
    class Conf < RegexLexer
      tag 'conf'
      aliases 'config', 'configuration'

      title 'Config File'
      desc 'A generic lexer for configuration files'
      filenames '*.conf', '*.config'

      # short and sweet
      state :root do
        rule /#.*?\n/, Comment
        rule /".*?"/, Str::Double
        rule /'.*?'/, Str::Single
        rule /[a-z]\w*/i, Name
        rule /\d+/, Num
        rule /[^\d\w#"']+/, Text
      end
    end
  end
end


text:
class CreateMilestones < ActiveRecord::Migration
  def self.up
    create_table :milestones do |t|
      t.references :project
      t.string :name
      t.text :description
      t.date :deadline
      t.date :completion_date

      t.timestamps
    end
  end

  def self.down
    drop_table :milestones
  end
end


text:
// This file was auto-generated. Please do not edit it.

import * as p5 from '../../index';

declare module '../../index' {
    interface p5InstanceExtensions {
        /**
         *   Calculates the absolute value (magnitude) of a
         *   number. Maps to Math.abs(). The absolute value of
         *   a number is always positive.
         *   @param n number to compute
         *   @return absolute value of given number
         */
        abs(n: number): number;

        /**
         *   Calculates the closest int value that is greater
         *   than or equal to the value of the parameter. Maps
         *   to Math.ceil(). For example, ceil(9.03) returns
         *   the value 10.
         *   @param n number to round up
         *   @return rounded up number
         */
        ceil(n: number): number;

        /**
         *   Constrains a value between a minimum and maximum
         *   value.
         *   @param n number to constrain
         *   @param low minimum limit
         *   @param high maximum limit
         *   @return constrained number
         */
        constrain(n: number, low: number, high: number): number;

        /**
         *   Calculates the distance between two points, in
         *   either two or three dimensions.
         *   @param x1 x-coordinate of the first point
         *   @param y1 y-coordinate of the first point
         *   @param x2 x-coordinate of the second point
         *   @param y2 y-coordinate of the second point
         *   @return distance between the two points
         */
        dist(x1: number, y1: number, x2: number, y2: number): number;

        /**
         *   Calculates the distance between two points, in
         *   either two or three dimensions.
         *   @param x1 x-coordinate of the first point
         *   @param y1 y-coordinate of the first point
         *   @param z1 z-coordinate of the first point
         *   @param x2 x-coordinate of the second point
         *   @param y2 y-coordinate of the second point
         *   @param z2 z-coordinate of the second point
         *   @return distance between the two points
         */
        dist(x1: number, y1: number, z1: number, x2: number, y2: number, z2: number): number;

        /**
         *   Returns Euler's number e (2.71828...) raised to
         *   the power of the n parameter. Maps to Math.exp().
         *   @param n exponent to raise
         *   @return e^n
         */
        exp(n: number): number;

        /**
         *   Calculates the closest int value that is less than
         *   or equal to the value of the parameter. Maps to
         *   Math.floor().
         *   @param n number to round down
         *   @return rounded down number
         */
        floor(n: number): number;

        /**
         *   Calculates a number between two numbers at a
         *   specific increment. The amt parameter is the
         *   amount to interpolate between the two values where
         *   0.0 equal to the first point, 0.1 is very near the
         *   first point, 0.5 is half-way in between, and 1.0
         *   is equal to the second point. If the value of amt
         *   is more than 1.0 or less than 0.0, the number will
         *   be calculated accordingly in the ratio of the two
         *   given numbers. The lerp function is convenient for
         *   creating motion along a straight path and for
         *   drawing dotted lines.
         *   @param start first value
         *   @param stop second value
         *   @param amt number
         *   @return lerped value
         */
        lerp(start: number, stop: number, amt: number): number;

        /**
         *   Calculates the natural logarithm (the base-e
         *   logarithm) of a number. This function expects the
         *   n parameter to be a value greater than 0.0. Maps
         *   to Math.log().
         *   @param n number greater than 0
         *   @return natural logarithm of n
         */
        log(n: number): number;

        /**
         *   Calculates the magnitude (or length) of a vector.
         *   A vector is a direction in space commonly used in
         *   computer graphics and linear algebra. Because it
         *   has no "start" position, the magnitude of a vector
         *   can be thought of as the distance from the
         *   coordinate 0,0 to its x,y value. Therefore, mag()
         *   is a shortcut for writing dist(0, 0, x, y).
         *   @param a first value
         *   @param b second value
         *   @return magnitude of vector from (0,0) to (a,b)
         */
        mag(a: number, b: number): number;

        /**
         *   Re-maps a number from one range to another.  In
         *   the first example above, the number 25 is
         *   converted from a value in the range of 0 to 100
         *   into a value that ranges from the left edge of the
         *   window (0) to the right edge (width).
         *   @param value the incoming value to be converted
         *   @param start1 lower bound of the value's current
         *   range
         *   @param stop1 upper bound of the value's current
         *   range
         *   @param start2 lower bound of the value's target
         *   range
         *   @param stop2 upper bound of the value's target
         *   range
         *   @param [withinBounds] constrain the value to the
         *   newly mapped range
         *   @return remapped number
         */
        map(
            value: number,
            start1: number,
            stop1: number,
            start2: number,
            stop2: number,
            withinBounds?: boolean
        ): number;

        /**
         *   Determines the largest value in a sequence of
         *   numbers, and then returns that value. max()
         *   accepts any number of Number parameters, or an
         *   Array of any length.
         *   @param n0 Number to compare
         *   @param n1 Number to compare
         *   @return maximum Number
         */
        max(n0: number, n1: number): number;

        /**
         *   Determines the largest value in a sequence of
         *   numbers, and then returns that value. max()
         *   accepts any number of Number parameters, or an
         *   Array of any length.
         *   @param nums Numbers to compare
         */
        max(nums: number[]): number;

        /**
         *   Determines the smallest value in a sequence of
         *   numbers, and then returns that value. min()
         *   accepts any number of Number parameters, or an
         *   Array of any length.
         *   @param n0 Number to compare
         *   @param n1 Number to compare
         *   @return minimum Number
         */
        min(n0: number, n1: number): number;

        /**
         *   Determines the smallest value in a sequence of
         *   numbers, and then returns that value. min()
         *   accepts any number of Number parameters, or an
         *   Array of any length.
         *   @param nums Numbers to compare
         */
        min(nums: number[]): number;

        /**
         *   Normalizes a number from another range into a
         *   value between 0 and 1. Identical to map(value,
         *   low, high, 0, 1). Numbers outside of the range are
         *   not clamped to 0 and 1, because out-of-range
         *   values are often intentional and useful. (See the
         *   example above.)
         *   @param value incoming value to be normalized
         *   @param start lower bound of the value's current
         *   range
         *   @param stop upper bound of the value's current
         *   range
         *   @return normalized number
         */
        norm(value: number, start: number, stop: number): number;

        /**
         *   Facilitates exponential expressions. The pow()
         *   function is an efficient way of multiplying
         *   numbers by themselves (or their reciprocals) in
         *   large quantities. For example, pow(3, 5) is
         *   equivalent to the expression 33333 and pow(3, -5)
         *   is equivalent to 1 / 33333. Maps to Math.pow().
         *   @param n base of the exponential expression
         *   @param e power by which to raise the base
         *   @return n^e
         */
        pow(n: number, e: number): number;

        /**
         *   Calculates the integer closest to the n parameter.
         *   For example, round(133.8) returns the value 134.
         *   Maps to Math.round().
         *   @param n number to round
         *   @return rounded number
         */
        round(n: number): number;

        /**
         *   Squares a number (multiplies a number by itself).
         *   The result is always a positive number, as
         *   multiplying two negative numbers always yields a
         *   positive result. For example, -1 * -1 = 1.
         *   @param n number to square
         *   @return squared number
         */
        sq(n: number): number;

        /**
         *   Calculates the square root of a number. The square
         *   root of a number is always positive, even though
         *   there may be a valid negative root. The square
         *   root s of number a is such that s*s = a. It is the
         *   opposite of squaring. Maps to Math.sqrt().
         *   @param n non-negative number to square root
         *   @return square root of number
         */
        sqrt(n: number): number;

        /**
         * Calculates the fractional part of a number.
         *
         * @param [num] Number whose fractional part needs to be found out
         * @returns fractional part of x, i.e, {x}
         */
        fract(num: number): number;
    }
}


text:
function str = encodevarname(str,varargin)
%
%    newname = encodevarname(name)
%
%    Encode an invalid variable name using a hex-format for bi-directional
%    conversions.

%    This function is sensitive to the default charset
%    settings in MATLAB, please call feature('DefaultCharacterSet','utf8')
%    to set the encoding to UTF-8 before calling this function.
%
%    author: Qianqian Fang (q.fang <at> neu.edu)
%
%    input:
%        name: a string, can be either a valid or invalid variable name
%
%    output:
%        newname: a valid variable name by converting the leading non-ascii
%              letter into "x0xHH_" and non-ascii letters into "_0xHH_"
%              format, where HH is the ascii (or Unicode) value of the
%              character.
%
%              if the encoded variable name CAN NOT be longer than 63, i.e.
%              the maximum variable name specified by namelengthmax, and
%              one uses the output of this function as a struct or variable
%              name, the name will be trucated at 63. Please consider using
%              the name as a containers.Map key, which does not have such
%              limit.
%
%    example:
%        encodevarname('_a')   % returns x0x5F_a
%        encodevarname('a_')   % returns a_ as it is a valid variable name
%        encodevarname('变量')  % returns 'x0xE58F98__0xE9878F_'
%
%    this file is part of EasyH5 Toolbox: https://github.com/fangq/easyh5
%
%    License: BSD 3-clause license, see https://github.com/fangq/easyh5 for details
%

    if(~isvarname(str(1)))
        if(exist('unicode2native','builtin'))
            str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
        else
            str=sprintf('x0x%X_%s',char(str(1))+0,str(2:end));
        end
    end
    if(isvarname(str))
        return;
    end
    if(exist('unicode2native','builtin'))
        str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
    else
        cpos=regexp(str,'[^0-9A-Za-z_]');
        if(isempty(cpos))
            return;
        end
        str0=str;
        pos0=[0 cpos(:)' length(str)];
        str='';
        for i=1:length(cpos)
            str=[str str0(pos0(i)+1:cpos(i)-1) sprintf('_0x%X_',str0(cpos(i))+0)];
        end
        if(cpos(end)~=length(str))
            str=[str str0(pos0(end-1)+1:pos0(end))];
        end
    end
end


text:
<!DOCTYPE html>

	  <title>Dino-snore</title>
	  <meta charset="utf-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

	  	  <link href="all.css" rel="stylesheet" type="text/css">

	  <link href="pixel-picker.css" rel="stylesheet" type="text/css">

		      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

		      </button>

100

Title:

Date: