text:
#include <TranslationKit.h>
#include <Bitmap.h>
#include <stdio.h>

#include "SampleView.h"
#include "MainWindow.h"
#include "Globals.h"
#include "PeakFile.h"
#include "BitmapDrawer.h"
#include "Shortcut.h"
#include "MyClipBoard.h"
#include "VMSystem.h"

extern cookie_record play_cookie;

/*****************************************************
*	Init View
*****************************************************/
SampleView::SampleView(BRect r) :
	BView(r, "Sample view", B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE | B_PULSE_NEEDED)
{
	SetViewColor(B_TRANSPARENT_COLOR);
	drag = false;
	edit = false;
	Pool.update_peak = true;
	stop_following = false;
	drag_selection = false;
	drag_border = false;
	cache_left_valid = false;
	cache_right_valid = false;
	old.Set(-1,-1);
	old_x = -1;

	peak_buffer_l = NULL;
	peak_buffer_r = NULL;
	m_width = -1;

	OffScreen = NULL;
	leftCache = NULL;
	rightCache = NULL;
	leftSelected = NULL;
	rightSelected = NULL;

	m_old_l_pointer = -1;
	m_old_r_pointer = -1;

	m_resized = true;		// need to create background buffers

	if((viewSem = create_sem(1, "SampleView Sem")) < 0){
//		debugger(CREATE_SEM_FAIL_MSG);
	}
}

/*****************************************************
*
*****************************************************/
SampleView::~SampleView()
{
	if (peak_buffer_l)	delete peak_buffer_l;
	if (peak_buffer_r)	delete peak_buffer_r;
	if (leftCache)		delete leftCache;
	if (rightCache)		delete rightCache;
	if (leftSelected)	delete leftSelected;
	if (rightSelected)	delete rightSelected;
	if (OffScreen)		delete OffScreen;
}

/*****************************************************
*
*****************************************************/
void SampleView::AttachedToWindow()
{
}

/*****************************************************
*
*****************************************************/
void SampleView::Init()
{
	peak_buffer_l = new float[ MAX_W * 2 ];
	peak_buffer_r = new float[ MAX_W * 2 ];
	memset( peak_buffer_l, 0, MAX_W * 2 * sizeof(float));	// wipe buffer
	memset( peak_buffer_r, 0, MAX_W * 2 * sizeof(float));	// wipe buffer
}

/*****************************************************
*
*****************************************************/
void SampleView::Pulse()
{
	if (Pool.sample_type == NONE)	return;

	BRect r = Bounds();
	r.top += POINTER_BAR_HEIGHT;

	if (!Pool.IsPlaying() && !play_cookie.pause){
		if (old_x != -1){
			SetDrawingMode(B_OP_INVERT);
			StrokeLine( BPoint( old_x, r.top), BPoint( old_x, r.bottom));
			SetDrawingMode(B_OP_COPY);
			old_x = -1;
		}
		return;
	}
	int64 p = 0;

	if (Pool.sample_type != NONE)
		if (Pool.IsPlaying()){
			p = Pool.last_pointer;
		}else
			p = Pool.pointer;

	if (p!=pointer){
		pointer = p;

		int32 xx = Pool.r_pointer - Pool.l_pointer;
		if (Prefs.follow_playing && !stop_following && pointer < Pool.size - xx/2)
		{
			int64 ptr;
			ptr = p - xx/2;
			if ( ptr > (Pool.size-xx))	ptr = Pool.size-xx;
			if ( ptr < 0 )				ptr = 0;

			if ( Pool.l_pointer != ptr )
			{
				Pool.l_pointer = ptr;
				Pool.r_pointer = Pool.l_pointer + xx;

				Window()->FindView("Pointers view")->Pulse();//Invalidate();
				Pool.update_index = true;	// @TODO: need to be pulse for fast update
				Window()->FindView("Big view")->Pulse();//Draw()Invalidate();
				Window()->FindView("Sample view")->Invalidate();
				Window()->FindView("TimeBar view")->Invalidate();
			}
		}

		// play pointer
		float x = (pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
		SetDrawingMode(B_OP_INVERT);

		StrokeLine( BPoint( old_x, r.top), BPoint( old_x, r.bottom));
		old_x = x;
		StrokeLine( BPoint( x, r.top), BPoint( x, r.bottom));

		SetDrawingMode(B_OP_COPY);
	}
}

/*****************************************************
*
*****************************************************/
void SampleView::Draw(BRect rect)
{
	Looper()->Lock();

	if (Pool.update_draw_cache && !m_resized)
		CalculateCache();

	if (m_resized)
	{
		acquire_sem(viewSem);

		// allocate offscreen bitmap here
		if (OffScreen)	delete OffScreen;
		BRect r = Bounds();
		r.InsetBy(0,-2);
		OffScreen = new BBitmap(r, B_RGB32);

		screenBits = (rgb_color*)OffScreen->Bits();
		screenWidth = OffScreen->Bounds().IntegerWidth()+1;
		screenBits += POINTER_BAR_HEIGHT*screenWidth;		// adjust for the top bar

		// fill upper with gray bar
		int32 width = Bounds().IntegerWidth();
		BitmapDrawer draw(OffScreen);
		rgb_color a;
		for(int32 y=0; y<POINTER_BAR_HEIGHT; y++)
		{
			if (y==0)							a = (rgb_color){255,255,255};
			else if (y==POINTER_BAR_HEIGHT-1)	a = (rgb_color){128,128,128};
			else								a = (rgb_color){192,192,192};
			for(int32 x=0; x<=width; x++)
				draw.PlotBGR(x,y,a);
		}

		release_sem(viewSem);

		// recalculate caches for resized screen
		CalculateCache();
	}

	rect.top = Bounds().top;
	rect.bottom = Bounds().bottom;
	if (Pool.sample_view_dirty)
	{
		switch(Pool.sample_type)
		{
			case MONO:
				if (!cache_left_valid)	break;
				rect.bottom = Bounds().bottom-POINTER_BAR_HEIGHT;
				DrawMono(rect, true, (Pool.selection == BOTH));
				rect.bottom = Bounds().bottom;
				break;

			case STEREO:
				DrawStereo(rect);
				break;

			default:
			{
				BitmapDrawer draw(OffScreen);

				rgb_color a = Prefs.back_color;
				uint8 t = a.red;
				a.red = a.blue;
				a.blue = t;

				int32 bottom = Bounds().IntegerHeight();
				int32 right = Bounds().IntegerWidth();
				// need to fix this !

				for(int32 y=POINTER_BAR_HEIGHT; y<=bottom; y++)
				{
					for(int32 x=0; x<=right; x++)
					{
						draw.PlotBGR(x,y,a);
					}
				}
			}break;
		}
	}

	DrawBitmapAsync( OffScreen, rect, rect);

	if (Pool.sample_type == NONE){
		Looper()->Unlock();
		return;
	}

	// Draw the pointer
	BRect r = Bounds();
	int32 xx = POINTER_BAR_HEIGHT/2 -2;
	if (Pool.selection == NONE){
		float x = (Pool.pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
		SetHighColor(Prefs.pointer_color);
		SetLowColor(Prefs.back_color);

		for (float y = POINTER_BAR_HEIGHT; y<r.bottom; y+=4)
			StrokeLine( BPoint( x, y), BPoint( x, y));
		FillTriangle( BPoint(x, POINTER_BAR_HEIGHT-3), BPoint(x - xx, 5), BPoint(x + xx, 5));
	}else{
		float x = (Pool.pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
		SetHighColor(Prefs.pointer_color);
		FillTriangle( BPoint(x, POINTER_BAR_HEIGHT-3), BPoint(x, 5), BPoint(x + xx, 5));
//		StrokeLine( BPoint( x, POINTER_BAR_HEIGHT), BPoint( x, r.bottom));

		x = (Pool.r_sel_pointer-Pool.l_pointer +1) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);//+1;
		FillTriangle( BPoint(x, POINTER_BAR_HEIGHT-3), BPoint(x, 5), BPoint(x - xx, 5));
//		StrokeLine( BPoint( x, POINTER_BAR_HEIGHT), BPoint( x, r.bottom));
	}

	if (Pool.IsPlaying()){				// remove line
		SetDrawingMode(B_OP_INVERT);
		StrokeLine( BPoint( old_x, Bounds().top+POINTER_BAR_HEIGHT), BPoint( old_x, Bounds().bottom));
		SetDrawingMode(B_OP_COPY);
	}

	// these are to notify screen changes to update peak-caches or scroll fast
	m_old_l_pointer = Pool.l_pointer;
	m_old_r_pointer = Pool.r_pointer;
	m_resized = false;					//  put here, so all sub-routines can benefit
	Pool.update_draw_cache = false;
	Pool.update_peak = false;				// needed for pencil edit

	Looper()->Unlock();
}

/*****************************************************
*
*****************************************************/
void SampleView::MouseDown(BPoint p)
{
	if (Pool.size == 0)	return;

	BMessage *currentMsg = Window()->CurrentMessage();
	uint32 button = 0, clicks = 0;
	currentMsg->FindInt32("buttons", (int32 *)&button);
	currentMsg->FindInt32("clicks", (int32 *)&clicks);

	SetMouseEventMask(B_POINTER_EVENTS, B_NO_POINTER_HISTORY);

	if ( p.y < POINTER_BAR_HEIGHT)
	{
		/* Handle the triangles here */
		return;
	}

	//
	// The selection tool handles all select modes
	//
	switch(Pool.tool_mode){
	case SELECT_TOOL:			/* Select Tool */
	{	if (clicks == 1){
			float middle = (Bounds().Height()-POINTER_BAR_HEIGHT)*0.50+POINTER_BAR_HEIGHT;	// middle
			// calculate position of cursors on screen
			float pointer_x = (Pool.pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
			float sel_pointer_x = (Pool.r_sel_pointer-Pool.l_pointer+1) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);

			bool left_select = false, right_select = false;
			bool left_pointer = (p.x < pointer_x+3 && p.x > pointer_x-3) && Pool.selection != NONE;
			bool right_pointer = (p.x < sel_pointer_x+3 && p.x > sel_pointer_x-3) && Pool.selection != NONE;

			if (Pool.selection == BOTH || (Pool.selection == LEFT && p.y <= middle))	left_select = true;
			if (Pool.selection == BOTH || (Pool.selection == RIGHT && p.y >= middle))	right_select = true;

			bool drag_area = (p.x > pointer_x && p.x < sel_pointer_x) && Pool.selection != NONE
							&& !left_pointer && !right_pointer && (left_select || right_select);

			/* Do the selecting */
			if (button == B_SECONDARY_MOUSE_BUTTON)
			{																/* show a pop-up menu here */
				BMenuItem *menuItem;
				BPopUpMenu *menu = new BPopUpMenu("");

				menu->AddItem(new BMenuItem(Language.get("TRANSPORT_PLAYS"), new BMessage(TRANSPORT_PLAYS), KeyBind.GetKey("TRANSPORT_PLAYS"), KeyBind.GetMod("TRANSPORT_PLAYS")));
				menu->AddItem(menuItem = new BMenuItem(Language.get("TRANSPORT_PAUSE"), new BMessage(TRANSPORT_PAUSE_MAN), KeyBind.GetKey("TRANSPORT_PAUSE"), KeyBind.GetMod("TRANSPORT_PAUSE")));
				if (((MainWindow*)Pool.mainWindow)->transport_view->pause->Value() == B_CONTROL_ON)
					menuItem->SetMarked(true);
				menu->AddItem(new BMenuItem(Language.get("TRANSPORT_STOP"), new BMessage(TRANSPORT_STOP), KeyBind.GetKey("TRANSPORT_STOP"), KeyBind.GetMod("TRANSPORT_STOP")));
				menu->AddSeparatorItem();
				menu->AddItem(menuItem = new BMenuItem(Language.get("COPY"), new BMessage(B_COPY), KeyBind.GetKey("COPY"), KeyBind.GetMod("COPY")));
				menuItem->SetEnabled(Pool.selection != NONE);
				menu->AddItem(menuItem = new BMenuItem(Language.get("COPY_SILENCE"), new BMessage(COPY_SILENCE), KeyBind.GetKey("COPY_SILENCE"), KeyBind.GetMod("COPY_SILENCE")));
				menuItem->SetEnabled(Pool.selection != NONE);
				menu->AddItem(menuItem = new BMenuItem(Language.get("CUT"), new BMessage(B_CUT), KeyBind.GetKey("CUT"), KeyBind.GetMod("CUT")));
				menuItem->SetEnabled(Pool.selection != NONE);
				menu->AddItem(menuItem = new BMenuItem(Language.get("PASTE"), new BMessage(B_PASTE), KeyBind.GetKey("PASTE"), KeyBind.GetMod("PASTE")));
				menuItem->SetEnabled(ClipBoard.HasClip());
				menu->AddItem(menuItem = new BMenuItem(Language.get("PASTE_NEW"), new BMessage(PASTE_NEW), KeyBind.GetKey("PASTE_NEW"), KeyBind.GetMod("PASTE_NEW")));
				menuItem->SetEnabled(ClipBoard.HasClip());
				#ifdef __SAMPLE_STUDIO_LE
					menu->AddItem(menuItem = new BMenuItem(Language.get("EDIT_PASTE_MIX"), new BMessage(PASTE_MIXED), KeyBind.GetKey("EDIT_PASTE_MIX"), KeyBind.GetMod("EDIT_PASTE_MIX")));
					menuItem->SetEnabled(ClipBoard.HasClip());
					menu->AddItem(menuItem = new BMenuItem(Language.get("COPY_TO_STACK"), new BMessage(TO_STACK), KeyBind.GetKey("COPY_TO_STACK"), KeyBind.GetMod("COPY_TO_STACK")));
					menuItem->SetEnabled(Pool.selection != NONE);
				#endif
				menu->AddSeparatorItem();
				menu->AddItem(menuItem = new BMenuItem(Language.get("SELECT_ALL"), new BMessage(B_SELECT_ALL), KeyBind.GetKey("SELECT_ALL"), KeyBind.GetMod("SELECT_ALL")));
				menu->AddItem(menuItem = new BMenuItem(Language.get("UNSELECT_ALL"), new BMessage(UNSELECT_ALL), KeyBind.GetKey("UNSELECT_ALL"), KeyBind.GetMod("UNSELECT_ALL")));
				menuItem->SetEnabled(Pool.selection != NONE);
				menu->AddSeparatorItem();
				BMenu *sub = new BMenu(Language.get("ZERO_CROSS"));
				sub->AddItem(new BMenuItem(Language.get("ZERO_IN"), new BMessage(ZERO_IN), KeyBind.GetKey("ZERO_IN"), KeyBind.GetMod("ZERO_IN")));
				sub->AddItem(new BMenuItem(Language.get("ZERO_OUT"), new BMessage(ZERO_OUT), KeyBind.GetKey("ZERO_OUT"), KeyBind.GetMod("ZERO_OUT")));
				sub->AddItem(new BMenuItem(Language.get("ZERO_LL"), new BMessage(ZERO_LL), KeyBind.GetKey("ZERO_LL"), KeyBind.GetMod("ZERO_LL")));
				sub->AddItem(new BMenuItem(Language.get("ZERO_LR"), new BMessage(ZERO_LR), KeyBind.GetKey("ZERO_LR"), KeyBind.GetMod("ZERO_LR")));
				sub->AddItem(new BMenuItem(Language.get("ZERO_RL"), new BMessage(ZERO_RL), KeyBind.GetKey("ZERO_RL"), KeyBind.GetMod("ZERO_RL")));
				sub->AddItem(new BMenuItem(Language.get("ZERO_RR"), new BMessage(ZERO_RR), KeyBind.GetKey("ZERO_RR"), KeyBind.GetMod("ZERO_RR")));
				sub->SetTargetForItems(Window());
				menu->AddItem(sub);

				menu->AddSeparatorItem();
				sub = new BMenu(Language.get("ZOOM_FUNCTIONS"));
				sub->AddItem(new BMenuItem(Language.get("ZOOM_IN"), new BMessage(ZOOM_IN), KeyBind.GetKey("ZOOM_IN"), KeyBind.GetMod("ZOOM_IN")));
				sub->AddItem(new BMenuItem(Language.get("ZOOM_OUT"), new BMessage(ZOOM_OUT), KeyBind.GetKey("ZOOM_OUT"), KeyBind.GetMod("ZOOM_OUT")));
				sub->AddItem(new BMenuItem(Language.get("ZOOM_FULL"), new BMessage(ZOOM_FULL), KeyBind.GetKey("ZOOM_FULL"), KeyBind.GetMod("ZOOM_FULL")));
				sub->AddItem(menuItem = new BMenuItem(Language.get("ZOOM_SELECTION"), new BMessage(ZOOM_SELECTION), KeyBind.GetKey("ZOOM_SELECTION"), KeyBind.GetMod("ZOOM_SELECTION")));
				menuItem->SetEnabled(Pool.selection != NONE);
				sub->AddItem(menuItem = new BMenuItem(Language.get("ZOOM_LEFT"), new BMessage(ZOOM_LEFT), KeyBind.GetKey("ZOOM_LEFT"), KeyBind.GetMod("ZOOM_LEFT")));
				menuItem->SetEnabled(Pool.selection != NONE);
				sub->AddItem(menuItem = new BMenuItem(Language.get("ZOOM_RIGHT"), new BMessage(ZOOM_RIGHT), KeyBind.GetKey("ZOOM_RIGHT"), KeyBind.GetMod("ZOOM_RIGHT")));
				menuItem->SetEnabled(Pool.selection != NONE);
				sub->SetTargetForItems(Window());
				menu->AddItem(sub);

				ConvertToScreen(&p);
				menu->SetTargetForItems(Window());
				menuItem = menu->Go(p, true, false, true);
//				if ( menuItem && menuItem->Message())
//					Window()->PostMessage(menuItem->Message());

			}
			// Check for extending the selection
			else if ((left_pointer || right_pointer) && (left_select || right_select) ||
					(button == B_PRIMARY_MOUSE_BUTTON && (modifiers() & B_SHIFT_KEY))){
				/* Drag the end-pointers */
				drag_border = true;
				t = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());
				if (t > (Pool.pointer + Pool.r_sel_pointer)/2){					// drag the right part
					drag = true;
					t = (int32)Pool.pointer;			// use original begin of selection
					MouseMoved( p, 0, NULL );
				}else{
					drag = true;
					t = (int32)(Pool.r_sel_pointer);
					MouseMoved( p, 0, NULL );
				}
			}else if (drag_area)			/* start a dragging session */
			{
				drag_selection = true;
				start_selection = p;
			}
			// Here we start a new selection
			else if (button == B_PRIMARY_MOUSE_BUTTON && !(modifiers() & B_SHIFT_KEY)){					// do new selection
				old_x = -1;
				drag = true;
				Pool.selection = NONE;
				Pool.r_sel_pointer = 0;
				t = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());
				Pool.pointer = t;

				old = p;
				start_selection = p;
			}else{
				// interactive zooming

				float factor;
				float y = p.y;
				int32 m = (Pool.r_pointer+Pool.l_pointer)/2;				// center
				int32 x = Pool.r_pointer - Pool.l_pointer;
				float old_y = p.y;

				int32 in = (int32)(x - Bounds().Width()/16);		// possible to zoom in
				int32 out = Pool.size -x;							// possible to zoom out
				if (out > in*6)			out = in*6;
				int32 z;

				float old_x = p.x;

				while(button){
					GetMouse(&p, &button);

					if (p.y != old_y || p.x != old_x){
						factor = (y-p.y) *0.005;		// scaled zoom
						if (factor<0){
							if (factor<-1)	factor =-1;
							z = (int32)((factor+1) * in/2 +Bounds().Width()/32);
						}else{
							if (factor>1)	factor =1;
							z = (int32)(factor * out/2 +x/2);
						}

						int32 add = (int32)((old_x-p.x)*x/Bounds().Width());

						Pool.l_pointer = m - z + add;
						Pool.r_pointer = m + z + add;

						if (Pool.l_pointer < 0)			Pool.l_pointer = 0;
						if (Pool.r_pointer > Pool.size)	Pool.r_pointer = Pool.size;

						Invalidate();
						Pool.update_index = true;
						Window()->FindView("Index view")->Invalidate();
						Window()->FindView("Pointers view")->Invalidate();
						Window()->FindView("TimeBar view")->Invalidate();
						old_y = p.y;
						old_x = p.x;
					}
					snooze(100000);
				}
			}
		}else if (clicks == 2 && Prefs.select_all_on_double){		/* The double-click selection */
			Pool.SelectAll();
		}
		break;
	}
	case DRAW_TOOL:												/* Drawing with the Pencil */
	{
		if (Pool.tool_mode == DRAW_TOOL && clicks == 1){
			// save undo data
			if (Prefs.save_undo){
				Hist.Save(H_REPLACE, Pool.l_pointer, Pool.r_pointer);
				Pool.UpdateMenu();
			}

			edit_channel = NONE;	// needed to track stereo editing
			old = p;
			EditPoint( p );
			edit = true;
		}
		break;
	}
	case PLAY_TOOL:												/* Playing tool */
	{
		stop_following = true;
		Pool.selection = NONE;									// Set the play-pointer
		Pool.r_sel_pointer = 0;
		Pool.pointer = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());
		if (button){
			bool bRight = (button & B_SECONDARY_MOUSE_BUTTON);
			Pool.StartPlaying(Pool.pointer*Pool.sample_type, true);	// play till end
			Draw(Bounds());
			snooze(10000);
			while(button){										// Keep playing as long as the mouse is pressed
				GetMouse(&p, &button);
				Pulse();
				Window()->FindView("Big view")->Pulse();
				snooze(10000);
			}
			Pool.StopPlaying();
			if (bRight)
				Pool.pointer = Pool.last_pointer;
		stop_following = false;
		}
		break;
	}
	case SCRUB_TOOL:											/* Scrubbing Tool */
	{
		stop_following = true;
		Pool.selection = NONE;									// Set the play-pointer
		Pool.r_sel_pointer = 0;
		Pool.pointer = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());

		bool bLoop = Pool.SetLoop(true);

		if (button){
			Pool.StartPlaying(Pool.pointer*Pool.sample_type, true);	// play till end
			Draw(Bounds());
			snooze(10000);
			Pool.last_pointer = Pool.pointer;
			while(button){										// Keep playing as long as the mouse is pressed
				GetMouse(&p, &button);

				float x = (Pool.last_pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
				Pool.frequency = Pool.system_frequency * (p.x-x)/50.0;

				Pulse();
				Window()->FindView("Big view")->Pulse();
				snooze(10000);
			}
			Pool.SetLoop(bLoop);
			Pool.StopPlaying();
			Pool.pointer = Pool.last_pointer;
			Pool.frequency = Pool.system_frequency;
			stop_following = false;
		}
		break;
	}
	default:
		break;
	}

	Invalidate();
	Window()->FindView("Pointers view")->Invalidate();
	Pool.update_index = true;
	Window()->FindView("Index view")->Invalidate();
	Window()->FindView("Big view")->Invalidate();
	Pool.UpdateMenu();
}

/*****************************************************
*	Mouse Moved
*****************************************************/
void SampleView::MouseMoved(BPoint p, uint32 button, const BMessage *msg)
{
	// area where the cursors work for left/right selection
	float top = (Bounds().Height()-POINTER_BAR_HEIGHT)*0.20 +POINTER_BAR_HEIGHT;	// left
	float bottom = (Bounds().Height()-POINTER_BAR_HEIGHT)*0.80+POINTER_BAR_HEIGHT;	// right
	float middle = (Bounds().Height()-POINTER_BAR_HEIGHT)*0.50+POINTER_BAR_HEIGHT;	// middle

	// calculate position of cursors on screen
	float pointer_x = (Pool.pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);
	float sel_pointer_x = (Pool.r_sel_pointer-Pool.l_pointer+1) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);

	bool left_pointer = (p.x < pointer_x+3 && p.x > pointer_x-3) && Pool.selection != NONE;
	bool right_pointer = (p.x < sel_pointer_x+3 && p.x > sel_pointer_x-3) && Pool.selection != NONE;

	bool left_select = false, right_select = false;
	if (Pool.selection == BOTH || (Pool.selection == LEFT && p.y <= middle))	left_select = true;
	if (Pool.selection == BOTH || (Pool.selection == RIGHT && p.y >= middle))	right_select = true;

	bool drag_area = (p.x > pointer_x && p.x < sel_pointer_x) && Pool.selection != NONE
					&& !left_pointer && !right_pointer && (left_select || right_select);

	if (Pool.tool_mode == DRAW_TOOL)			/* pencil mouse cursor */
		SetViewCursor( Pool.mousePencil );
	else if (Pool.tool_mode == SELECT_TOOL)		/* mousecursors for selections */
	{
		if (drag_selection)	SetViewCursor( Pool.mouseArrow );	// drag&drop cursor goes above all
		else if (drag_border || (!drag && (left_pointer || right_pointer) && (left_select || right_select)))
			SetViewCursor( Pool.mouseLeftRight );
		else if (Pool.sample_type != STEREO )
			SetViewCursor( Pool.mouseArrow );
		else
		{
			if (drag_area && !drag)
				SetViewCursor( Pool.mouseMove );
			else if (p.y < top && p.y >= POINTER_BAR_HEIGHT)
				SetViewCursor( Pool.mouseArrowLeft );
			else if (p.y > bottom)
				SetViewCursor( Pool.mouseArrowRight );
			else
				SetViewCursor( Pool.mouseArrow );
		}
	}
	else	SetViewCursor( B_CURSOR_SYSTEM_DEFAULT );

	//
	// Handle the mouse-move events
	//
	/* decide which part would be selected */
	bool full_update = false;

	if (Prefs.drag_drop && drag_selection)				/* drag & drop */
	{
		if (abs(p.x - start_selection.x) >3)
		{
			BRect r = Bounds();
			r.top += POINTER_BAR_HEIGHT;
			r.left = p.x;
			r.right = p.x+1;

			if (modifiers() & B_COMMAND_KEY)
				ClipBoard.Cut(true);
			else
				ClipBoard.Copy();

			BMessage msg(DROP_PASTE);
			DragMessage(&msg, r);

			drag_selection = false;
		}
		old = p;
	}
	else if (drag && p!=old){		/* do the selecting */
		if (Pool.sample_type == MONO)
		{
			Pool.selection = BOTH;
			SetViewCursor( Pool.mouseArrow );
		}
		else	/* Check to see which channels are selected */
		{
			if (p.y < top)
			{
				if (Pool.selection == BOTH)	full_update = true;
				Pool.selection = LEFT;
			}
			else if (p.y > bottom)
			{
				if (Pool.selection == BOTH)	full_update = true;
				Pool.selection = RIGHT;
			}
			else
			{
				if (Pool.selection == LEFT || Pool.selection == RIGHT)	full_update = true;
				Pool.selection = BOTH;
			}
		}

		t2 = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());

		if (t > t2){
			Pool.pointer = t2;
			Pool.r_sel_pointer = t;
		}else{
			Pool.pointer = t;
			Pool.r_sel_pointer = t2;
		}

		if (Pool.pointer < 0)
			Pool.pointer = 0;

		if (Pool.r_sel_pointer > Pool.size)
			Pool.r_sel_pointer = Pool.size;

		Pool.update_index = true;
		Window()->FindView("Pointers view")->Draw(Window()->FindView("Pointers view")->Bounds());
		Window()->FindView("Index view")->Invalidate();
		int32 step = (int32)((Pool.r_pointer-Pool.l_pointer)/Bounds().Width());
		int32 zoom_x = 4;		// normal case just extend the width of the selection triangles
		if (step==0)
			zoom_x =  (int32)MAX(ceil(Bounds().Width()/(Pool.r_pointer - Pool.l_pointer)),POINTER_BAR_HEIGHT) ;

		BRect update;
		if (full_update)
			update = Bounds();
		else if (p.x>old.x)
			update.Set(old.x - zoom_x, 0, p.x + zoom_x, Bounds().bottom);
		else
			update.Set(p.x - zoom_x, 0, old.x + zoom_x, Bounds().bottom);

		if (Pool.IsPlaying()){				// remove line
			SetDrawingMode(B_OP_INVERT);
			StrokeLine( BPoint( old_x, Bounds().top+POINTER_BAR_HEIGHT), BPoint( old_x, Bounds().bottom));
			SetDrawingMode(B_OP_COPY);
		}

		Draw(update);
		old = p;
	}else if (edit){
		EditLine( old, p );
		old = p;
	}
}

/*****************************************************
*	Mouse Up
*****************************************************/
void SampleView::MouseUp(BPoint p)
{
	if (drag_selection && start_selection == p)		/* single clicked in selection without drag -> deselect */
	{
		old_x = -1;
		Pool.selection = NONE;
		Pool.r_sel_pointer = 0;
		Pool.pointer = (int32)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());

		Invalidate();
		Window()->FindView("Pointers view")->Invalidate();
		Pool.update_index = true;
		Window()->FindView("Index view")->Invalidate();
		Window()->FindView("Big view")->Invalidate();
	}

	drag = false;
	drag_selection = false;
	edit = false;
	drag_border = false;
	old.Set(-1,-1);
	Pool.UpdateMenu();
}

//*****************************************************
//
//	Set a sample to a new value indicated by p
//
//*****************************************************
void SampleView::EditPoint(BPoint p)
{
	// the sampleView area
	BRect r = Bounds();
	r.top += POINTER_BAR_HEIGHT;

	if ( p.x < 0 )
		p.x = 0;
	if ( p.x > r.right )
		p.x = r.right;

	// get the offset sample
	int64 ptr = (int64)(Pool.l_pointer + p.x * (Pool.r_pointer - Pool.l_pointer)/Bounds().Width());

	// step between samples
//	float step = (Pool.r_pointer-Pool.l_pointer)/Bounds().Width();
	float v;
//
// Mono
//
	if (Pool.sample_type == MONO){

		float amp = r.Height() /2.0;
		float mid = amp  +POINTER_BAR_HEIGHT;

		v = (mid - p.y)/amp;
		if (v < -1.0)	v = -1.0;
		if (v > 1.0)	v = 1.0;

		DoDraw(ptr, 1, v);
//
// Stereo
//
	}else if (Pool.sample_type == STEREO){

		r.bottom = r.Height()/2.0f -2.0f +r.top;					// calc left area
		float amp = r.Height()/2.0;
		float mid = amp  +r.top;
		if (r.Contains(p) && edit_channel == NONE)	edit_channel = LEFT;

		if (edit_channel == LEFT){
			v = (mid - p.y)/amp;
			if (v < -1.0)	v = -1.0;
			if (v > 1.0)	v = 1.0;

			DoDraw(ptr*2, 2, v);
		}else{
			// right
			r.OffsetTo(0, r.bottom+4.0f);					// calc right area
			mid = amp  +r.top;
			if (r.Contains(p) && edit_channel == NONE)	edit_channel = RIGHT;

			if (edit_channel == RIGHT){
				v = (mid - p.y)/amp;
				if (v < -1.0)	v = -1.0;
				if (v > 1.0)	v = 1.0;

				DoDraw(ptr*2+1, 2, v);
			}
		}
	}

	// Do some screen updating
	Pool.update_peak = true;
	Pool.update_index = true;
	Window()->FindView("Index view")->Invalidate();
	int32 zoom_x =  (int32)MAX(ceil(Bounds().Width()/(Pool.r_pointer - Pool.l_pointer)),POINTER_BAR_HEIGHT) ;
	if (p.x>old.x){
		Invalidate(BRect(BPoint(old.x-zoom_x*2, 0), BPoint(p.x+zoom_x, Bounds().bottom)));
	}else{
		Invalidate(BRect(BPoint(p.x-zoom_x*2, 0), BPoint(old.x+zoom_x, Bounds().bottom)));
	}
	old = p;
}

/*****************************************************
*
*****************************************************/
void SampleView::DoDraw(int64 ptr, int32 add, float v)
{
	int32 step = (int32)ceil((Pool.r_pointer-Pool.l_pointer)/Bounds().Width());

	if (step<=1){
		if (ptr > Pool.size*add) ptr = Pool.size*add;
		if (ptr < 0 ) ptr = 0;
#ifndef __VM_SYSTEM //RAM
		Pool.sample_memory[ptr] = v;
#else
		VM.WriteAt( ptr, v );
#endif
	}else{

		int32 start = ptr - step*add;	// left part
		if (start < 0) start = 0;

		for (int32 i=start; i<=ptr; i+=add){
#ifndef __VM_SYSTEM //RAM
			Pool.sample_memory[i] = v;
#else
			VM.WriteAt( i, v );
#endif
		}

		int32 end = ptr + step*add;	// left part
		if (end > Pool.size*add) end = Pool.size*add;

		for (int32 i=ptr; i<=end; i+=add){
#ifndef __VM_SYSTEM //RAM
			Pool.sample_memory[i] = v;
#else
			VM.WriteAt( i, v );
#endif
		}
	}
}

/*****************************************************
*	Indicate that the frame is resized
*****************************************************/
void SampleView::FrameResized(float width, float height)
{
	m_resized = true;				// re-allocate offscreen bitmap
	Pool.sample_view_dirty = true;	// update the sample-view
	Pool.update_draw_cache = true;	// update the draw cache
}

/*****************************************************
* Create the cache bitmaps for drawing
* This is needed on resize, start and recoloring
*****************************************************/
void SampleView::CalculateCache()
{
	if (Pool.sample_type == NONE)	return;

	acquire_sem(viewSem);

	BFont font;
	GetFont(&font);
	font_height fh;
	font.GetHeight(&fh);

	int conv[] = {0, 2, 4, 8, 8, 10, 10, 10, 20, 20, 20, 20};

	// delete used bitmaps for cache
	if (leftCache)		{ delete leftCache;	leftCache = NULL; cache_left_valid = false;}
	if (rightCache)		{ delete rightCache; rightCache = NULL; cache_right_valid = false;}
	if (leftSelected)	{ delete leftSelected; leftSelected = NULL; }
	if (rightSelected)	{ delete rightSelected; rightSelected = NULL; }

//printf("allocated\n");

	BRect r = Bounds();
	r.bottom -= POINTER_BAR_HEIGHT;
	float amp = (r.IntegerHeight()+1)/2.0;
	int32 size;
	if (Pool.sample_type == MONO)
		size = (int32)amp;
	else
		size = (int32)(amp+1)/2;

	int32 height_div = (int)ceil(amp/font.Size()) & 0xfffffe;
	if (height_div>20)	height_div = 20;
	height_div = conv[height_div/2];

	int32 peak = (int32)(r.top + amp*(1.0f - Prefs.peak));
	// size of cache
	BRect rect(0,0,size, size);

	leftCache = new BBitmap(rect, B_RGB32);
	leftSelected = new BBitmap(rect, B_RGB32);

	leftBits = (rgb_color*)leftCache->Bits();
	leftSelectedBits = (rgb_color*)leftSelected->Bits();
	leftWidth = leftCache->Bounds().IntegerWidth()+1;

	BitmapDrawer draw_left(leftCache);
	BitmapDrawer draw_leftSelected(leftSelected);

	rgb_color back2 = Prefs.back_color;				// background top
	rgb_color back1 = Prefs.back_color2;			// background middle
	rgb_color back2s = Prefs.back_selected_color;	// background top selected
	rgb_color back1s = Prefs.back_selected_color2;	// background middle selected
	rgb_color fore2s = Prefs.left_selected_color;	// foreground top
	rgb_color fore1s = Prefs.left_selected_color2;	// foreground middle
	rgb_color fore2 = Prefs.left_color;				// foreground top selected
	rgb_color fore1 = Prefs.left_color2;			// foreground middle selected

	float grid_y = 0;
	// draw the background
	rgb_color a, b, c, d;
	int32 temp;
	for(int32 y=0; y<=size; y++)
	{
		uint8 alpha = y*255/size;
		if (y==size)
		{
			// middle
			a = Prefs.mid_left_color;
			b = Prefs.mid_left_selected_color;
		}else
		if (Prefs.show_grid && y == (int)grid_y && y != size-1)
		{
			// horizontal grid
			a = Prefs.grid_color;
			b = Prefs.grid_selected_color;
			grid_y += r.Height()/height_div;
		}else
		if (y == peak && Prefs.show_peak)
		{
			// peak lines
			a = Prefs.peak_color;
			b = Prefs.peak_selected_color;
		}
		else
		{
			a.red = INT_BLEND(back1.red, back2.red, alpha, temp);
			a.green = INT_BLEND(back1.green, back2.green, alpha, temp);
			a.blue = INT_BLEND(back1.blue, back2.blue, alpha, temp);

			b.red = INT_BLEND(back1s.red, back2s.red, alpha, temp);
			b.green = INT_BLEND(back1s.green, back2s.green, alpha, temp);
			b.blue = INT_BLEND(back1s.blue, back2s.blue, alpha, temp);
		}

		c.red = INT_BLEND(fore1.red, fore2.red, alpha, temp);
		c.green = INT_BLEND(fore1.green, fore2.green, alpha, temp);
		c.blue = INT_BLEND(fore1.blue, fore2.blue, alpha, temp);

		d.red = INT_BLEND(fore1s.red, fore2s.red, alpha, temp);
		d.green = INT_BLEND(fore1s.green, fore2s.green, alpha, temp);
		d.blue = INT_BLEND(fore1s.blue, fore2s.blue, alpha, temp);

		// background
		for(int32 x=0; x<y; x++)
		{
			draw_left.PlotRGB( size - x, y, c );
			draw_leftSelected.PlotRGB( size - x, y, d );
		}
		// foreground
		for(int32 x=y; x<=size; x++)
		{
			draw_left.PlotRGB( size - x, y, a );
			draw_leftSelected.PlotRGB( size - x, y, b );
		}
	}

	cache_left_valid = true;

	if (Pool.sample_type == STEREO)
	{
		rightCache = new BBitmap(rect, B_RGB32);
		rightSelected = new BBitmap(rect, B_RGB32);

		rightBits = (rgb_color*)rightCache->Bits();
		rightSelectedBits = (rgb_color*)rightSelected->Bits();

		BitmapDrawer draw_right(rightCache);
		BitmapDrawer draw_rightSelected(rightSelected);

		rgb_color fore2s = Prefs.right_selected_color;	// foreground top
		rgb_color fore1s = Prefs.right_selected_color2;	// foreground middle
		rgb_color fore2 = Prefs.right_color;			// foreground top selected
		rgb_color fore1 = Prefs.right_color2;			// foreground middle selected

		float grid_y = 0;
		// draw the background
		rgb_color a, b, c, d;
		int32 temp;
		for(int32 y=0; y<=size; y++)
		{
			uint8 alpha = y*255/size;
			if (y==size)
			{
				// middle
				a = Prefs.mid_right_color;
				b = Prefs.mid_right_selected_color;
			}else
			if (Prefs.show_grid && y == (int)grid_y && y != size-1)
			{
				// horizontal grid
				a = Prefs.grid_color;
				b = Prefs.grid_selected_color;
				grid_y += r.Height()/height_div;
			}else
			if (y == peak && Prefs.show_peak)
			{
				// peak lines
				a = Prefs.peak_color;
				b = Prefs.peak_selected_color;
			}
			else
			{
				a.red = INT_BLEND(back1.red, back2.red, alpha, temp);
				a.green = INT_BLEND(back1.green, back2.green, alpha, temp);
				a.blue = INT_BLEND(back1.blue, back2.blue, alpha, temp);

				b.red = INT_BLEND(back1s.red, back2s.red, alpha, temp);
				b.green = INT_BLEND(back1s.green, back2s.green, alpha, temp);
				b.blue = INT_BLEND(back1s.blue, back2s.blue, alpha, temp);
			}

			c.red = INT_BLEND(fore1.red, fore2.red, alpha, temp);
			c.green = INT_BLEND(fore1.green, fore2.green, alpha, temp);
			c.blue = INT_BLEND(fore1.blue, fore2.blue, alpha, temp);

			d.red = INT_BLEND(fore1s.red, fore2s.red, alpha, temp);
			d.green = INT_BLEND(fore1s.green, fore2s.green, alpha, temp);
			d.blue = INT_BLEND(fore1s.blue, fore2s.blue, alpha, temp);

			// background
			for(int32 x=0; x<y; x++)
			{
				draw_right.PlotRGB( size - x, y, c );
				draw_rightSelected.PlotRGB( size - x, y, d );
			}
			// foreground
			for(int32 x=y; x<=size; x++)
			{
				draw_right.PlotRGB( size - x, y, a );
				draw_rightSelected.PlotRGB( size - x, y, b );
			}
		}
		cache_right_valid = true;
	}
	release_sem(viewSem);
}

/*****************************************************
*	Render MONO view
*****************************************************/
void SampleView::DrawMono(BRect rect, bool left, bool draw_selection)
{
	acquire_sem(viewSem);

	// Update the peak-cache if needed
	if (Pool.update_peak
	 || Pool.update_draw_cache
	 || m_old_l_pointer != Pool.l_pointer
	 || m_old_r_pointer != Pool.r_pointer )
	{
		if (left){
			if (Pool.sample_type == MONO)
				Peak.MonoBuffer(peak_buffer_l, Pool.l_pointer, Pool.r_pointer, Bounds().IntegerWidth()+1);
			else if (Pool.sample_type == STEREO)
				Peak.StereoBuffer(peak_buffer_l, peak_buffer_r, Pool.l_pointer, Pool.r_pointer, Bounds().IntegerWidth()+1);
		}
	}
	int32 size = rect.IntegerHeight();
	int32 size2 = size/2;
	if ((size-size2)==size2)		/* even */
	{
		size = size2;
	}
	else							/* odd */
	{
		size = size2 +1;
	}

	rgb_color *inBits, *inSelectedBits, *outBits;
	rgb_color col, colS;	// this one is used for line drawing
	float *peak_buffer;
	if (left)		/* fill pointers for left channel */
	{
		outBits = screenBits;
		inBits = leftBits;
		inSelectedBits = leftSelectedBits;
		col = Prefs.left_color2;
		colS = Prefs.left_selected_color2;
		peak_buffer = peak_buffer_l;
	}
	else			/* fill pointers for right channel */
	{
		outBits = screenBits + size*2 * screenWidth;
		inBits = rightBits;
		inSelectedBits = rightSelectedBits;
		col = Prefs.right_color2;
		colS = Prefs.right_selected_color2;
		peak_buffer = peak_buffer_r;
	}
	uint8 red = col.red; col.red = col.blue; col.blue = red;	// swap red/blue for direct draw
	red = colS.red; colS.red = colS.blue; colS.blue = red;	// swap red/blue for direct draw

	// do the left part of the back
	if (!draw_selection || Pool.l_pointer<Pool.pointer || Pool.r_sel_pointer<Pool.l_pointer)
	{
		BRect r = Bounds();
		if (draw_selection && Pool.r_pointer>Pool.r_sel_pointer && !(Pool.r_sel_pointer < Pool.l_pointer))		// clip
			r.right -= (Pool.r_pointer-Pool.pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer);

		// only draw when in update section
		if (r.right >= rect.left)
		{
			if (r.left < rect.left)	r.left = rect.left;
			DrawPart( inBits, outBits, col, peak_buffer, r, size, size2);
		}
	}

	// do the middle part of the back
	if (draw_selection && Pool.r_sel_pointer>=Pool.l_pointer && Pool.pointer<=Pool.r_pointer)
	{
		BRect r = Bounds();
		if (Pool.pointer>Pool.l_pointer)		// clip left
			r.left += floor((Pool.pointer-Pool.l_pointer) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer)+1);

		if (Pool.r_sel_pointer<Pool.r_pointer)	// clip right
			r.right -= ceil((Pool.r_pointer-Pool.r_sel_pointer-1) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer)-1);

		if (r.right == r.left)	r.left--;	// make sure there is always a selection visible, even when 1 pixel
		if (r.right >= rect.left && r.left <= rect.right)
		{
			if (r.right > rect.right)	r.right = rect.right;
			if (r.left < rect.left)		r.left = rect.left;
			DrawPart( inSelectedBits, outBits, colS, peak_buffer, r, size, size2);
		}
	}

	// do the right part of the back
	if (draw_selection && Pool.r_sel_pointer>Pool.l_pointer && Pool.r_sel_pointer<Pool.r_pointer)
	{
		BRect r = Bounds();
		r.left += (Pool.r_sel_pointer-Pool.l_pointer+1) * Bounds().Width() /(Pool.r_pointer - Pool.l_pointer)+1;
		if (r.left <= rect.right)
		{
			if (rect.left > r.left)		r.left = rect.left;
			if (rect.right < r.right)	r.right = rect.right;
			DrawPart( inBits, outBits, col, peak_buffer, r, size, size2);
		}
	}
	release_sem(viewSem);
}

/*****************************************************
*	Render STEREO view
*****************************************************/
void SampleView::DrawPart( rgb_color *inBits, rgb_color *outBits,
						   rgb_color col, float *peak_buffer,
						   BRect r, int32 size, int32 size2)
{
//r.PrintToStream();

	rgb_color *src = NULL;
	rgb_color *dest = NULL;

	int32 draw_mode;
	int32 step = (Pool.r_pointer-Pool.l_pointer)/Bounds().IntegerWidth();
//printf("step %d\n", step);

	if (step<1){
		draw_mode = DRAW_POINTS;
	}else if ( step < 64 )
		draw_mode = DRAW_PLAIN;
	else
		draw_mode = DRAW_PEAK;

	switch (draw_mode){
	case DRAW_POINTS:
	case DRAW_PLAIN:
	{
//printf("draw plain\n");
		int middle;
		int32 index = (int32)r.left*2;		// calc startpoint in buffer
//printf("index %d\n", index);
		int32 old_index = index-2;
		if (old_index<0)
			old_index = 0;

		int32 old_x1 = (int32)(size*peak_buffer[old_index]);		// -1
//printf("old_x1 %d left %f right %f\n", old_x1, r.left, r.right);
		for (int32 x = (int32)r.left; x<=(int32)r.right; x++){

			int32 x1 = (int32)(size*peak_buffer[index]);		// -1
//printf("x1 %d\n", x1);

			dest = outBits +x;		// screen
			src = inBits;			// background
			for (int32 y=0; y<=size; y++)
			{
				*dest = *src;
				dest += screenWidth;
				src += leftWidth;
			}
			src -= leftWidth;
			for (int32 y=0; y<size2; y++)
			{
				src -= leftWidth;
				*dest = *src;
				dest += screenWidth;
			}

			if (x1 == old_x1)
			{
//printf("x1==old_x1\n");
				*(outBits + x + (size-x1)*screenWidth) = col;
			}
			else if (x1 < old_x1)
			{
//printf("x1 < old_x1\n");
				middle = ( x1 + old_x1 +1)>>1;
				for (int32 offset = x1; offset < middle; offset++)
					*(outBits + x + (size-offset)*screenWidth) = col;

				if (x != 0)
					for (int32 offset = middle; offset < old_x1; offset++)
						*(outBits + x-1 + (size-offset)*screenWidth) = col;
			}
			else
			{
//printf("x1 > old_x1\n");
				middle = ( x1 + old_x1 )>>1;
				if (x != 0)
					for (int32 offset = old_x1; offset < middle; offset++)
						*(outBits + x-1 + (size-offset)*screenWidth) = col;

				for (int32 offset = middle; offset < x1; offset++)
					*(outBits + x + (size-offset)*screenWidth) = col;
			}
			old_x1 = x1;

			index += 2;
		}
	}	break;

	default:
//printf("default\n");
		// need to do the first unselected part here
		int32 index = (int32)r.left*2;		// calc startpoint in buffer
//printf("index %d left %f right %f p %p  l:%p r:%p\n", index, r.left, r.right, peak_buffer, peak_buffer_l, peak_buffer_r);
		for (int32 x = (int32)r.left; x<=(int32)r.right; x++){
			int32 x1 = (int32)(-size*peak_buffer[index]);		// -1
			int32 x2 = (int32)(size*peak_buffer[index+1]);	// +1

//printf("x %d x1 %d  x2 %d \n", x, x1, x2);
			// offset in screenbuffer
			dest = outBits +x;
//printf("1\n");
			// offset in cache
			src = inBits + x2;
//printf("2 src %p  size %d  sw %d lw %d  inBits %p\n", src, size, screenWidth, leftWidth, inBits);
			for (int32 y=0; y<=size; y++)
			{
				*dest = *src;
				dest += screenWidth;
				src += leftWidth;
			}
//printf("3\n");
			// offset in cache
			src = inBits + x1 +size * leftWidth - leftWidth;
//printf("4\n");
			for (int32 y=0; y<size2; y++)
			{
				*dest = *src;
				dest += screenWidth;
				src -= leftWidth;
			}
//printf("5\n");
			index += 2;
		}
//		printf("/n");
		break;
	}
}

/*****************************************************
*	Render STEREO view
*****************************************************/
void SampleView::DrawStereo(BRect rect)
{
	BRect r = rect;
	r.bottom -= POINTER_BAR_HEIGHT;
	r.bottom /= 2;
	if (cache_left_valid)
		DrawMono(r, true, (Pool.selection == LEFT || Pool.selection == BOTH));

	r.OffsetBy(0, r.Height());
	if (cache_right_valid)
		DrawMono(r, false, (Pool.selection == RIGHT || Pool.selection == BOTH));
}

/*****************************************************
*	Edit a line
*****************************************************/
void SampleView::EditLine(BPoint pa, BPoint pb)
{
	if(pa==pb)
		EditPoint(pa);
	else
	{
		float delta_x = (pa.x - pb.x);
		float delta_y = (pa.y - pb.y);

		if (delta_x < 0) delta_x *= -1;
		if (delta_y < 0) delta_y *= -1;

		float delta = sqrt((delta_x*delta_x) + (delta_y*delta_y));
		float nbpts;

		nbpts = delta / 1.0;

		BPoint pos;
		for (float i = 0; i < nbpts-0; i++){
			pos.x = ROUND(pa.x + i*(pb.x-pa.x)/nbpts);	// was floor
			pos.y = ROUND(pa.y + i*(pb.y-pa.y)/nbpts);

			EditPoint(pos);
		}
	}
}


text:
from jinja2 import Template, Environment, FileSystemLoader
import os, shutil, time, ConfigParser, HTMLParser, hashlib
import string, random, codecs, sys

import lib.markdown as markdown

# Pygments imports
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

env = Environment(loader=FileSystemLoader('templates'))

class Settings:

    def __init__(self):
        if not os.path.isfile('settings.cfg'):
            self.generate_default_config()

    def generate_default_config(self):
        config = '''[main]
# default_section:
# change 'disabled' to name of one of your sections
# to make it default (its index page will be generated
# on the top of other directories)
default_section = disabled

# default_template:
# this template will be used for all sections in case you won't
# specify templates for individual section
default_template = default.html

# output directory: (this may be relative and absolute as well)
# remember not to add slash at the end of key
# default: ./output e.g.: /home/www/my_site
output_directory = ./output

# static_directory:
# this is directory where you can put all your static files:
# images, csses, javascripts, relative link to that directory
# will be provided on all pages - {{ Static }}
static_directory = ./static

# These are your login informations and secret key. Both key and
# password were randomly generated and don't need to be changed.
#login_data

# always regenerate everything:
# if you want to regenerate every file when running generator,
# uncomment line below
# regenerate_everything = True

# example section's configuration:
# [section_name]
# template = template_name.html
# ascending = True

# template:
# if template is specified, section will use it instead of default
# template = template_name.html

# ascending:
# if you want to have oldest post before newer, you should add
# key 'ascending = True', remember that you need also to edit
# template (more in documentation)
# ascending = True

# Automaticaly generated sections
# to regenerate, simply delete settings.cfg

'''

        for section in Manager().get_all_sections():
            config += '['+section+'] \n'
            config += 'per_page = 5 \n\n'

        config = config.replace('#login_data', 'login = admin\n' + 'password = ' \
            + self.generate_password() + '\nsecret_key = ' + self.generate_secret_key())

        with open('settings.cfg', 'wb') as configfile:
            configfile.write(config)

    def get_value(self, section, value):
        parser = ConfigParser.SafeConfigParser()
        parser.read(['settings.cfg'])
        return parser.get(section, value)

    def compare_default_section(self, section):
        default_section = self.get_value('main', 'default_section')
        if default_section != 'disabled':
            return default_section
        else:
            return False

    def get_default_section(self):
        return self.get_value('main', 'default_section')

    def get_output_directory(self):
        return Settings().get_value('main', 'output_directory')

    def get_static_directory(self):
        return Settings().get_value('main', 'static_directory')

    def get_template(self, section):
        try:
            template = self.get_value(section, 'template')
        except:
            template = self.get_value('main', 'default_template')
        return template

    def get_default_template(self):
        return self.get_value('main', 'default_template')

    def get_contents(self):
        with open('settings.cfg') as settings_file:
            return settings_file.read()

    def check_if_ascending(self, section):
        try:
            ascending = self.get_value(section, 'ascending')
            if ascending == 'True':
                return True
        except:
            return False

    def check_regen_policy(self):
        try:
            if self.get_value('main', 'regenerate_everything') == 'True':
                return True
        except:
            return False

    def generate_password(self):
        return ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(10))

    def generate_secret_key(self):
        return ''.join(random.choice(string.ascii_letters + string.digits) for x in range(24))

    def get_login(self):
        return self.get_value('main', 'login')

    def get_password(self):
        return self.get_value('main', 'password')

    def get_secret_key(self):
        return self.get_value('main', 'secret_key')

    def add_new_section(self, section):
        Config = ConfigParser.ConfigParser()
        config_file = open("settings.cfg",'a')

        try:
            Config.add_section(section)
            Config.set(section, 'per_page', '5')

            Config.write(config_file)
            config_file.close()

            return True
        except:
            return False

    def remove_section(self, section):
        config = ConfigParser.RawConfigParser()
        config.read('settings.cfg')
        config.remove_section(section)
        config.write(open('settings.cfg', 'w'))

    def save_config(self, contents):
        with open('settings.cfg', 'w') as config_file:
            config_file.write(contents)

class Syntax(HTMLParser.HTMLParser):

    def highlight(self, html):
        self.tag_stack = []
        self.inputhtml = self.escape(html)
        self.feed(self.inputhtml)
        return self.inputhtml

    def handle_starttag(self, tag, attrs):
        self.tag_stack.append(tag.lower())

    def handle_endtag(self, tag):
        self.tag_stack.pop()

    def escape(self, esc_input):
        esc_input = esc_input.replace('<','apeiron_lt___')
        esc_input = esc_input.replace('>','apeiron_gt___')
        esc_input = esc_input.replace('&', 'apeiron_ampersand___')
        return esc_input

    def unescape(self, esc_input):
        esc_input = esc_input.replace('apeiron_lt___', '<')
        esc_input = esc_input.replace('apeiron_gt___', '>')
        esc_input = esc_input.replace('apeiron_ampersand___', '&')
        return esc_input

    def handle_data(self, data):
        if len(self.tag_stack) and self.tag_stack[-1] == 'code':
            try:
                lexer = get_lexer_by_name(data.splitlines()[0], stripall=True)
                formatter = HtmlFormatter(linenos=True, cssclass="highlight")
                output_html = highlight(data.replace(data.splitlines()[0], '', 1), lexer, formatter)
                self.inputhtml = self.inputhtml.replace(data, self.unescape(output_html))
            except:
                self.inputhtml = self.unescape(self.inputhtml)

class Manager:

    def create_directory(self, directory):
        if not os.path.exists(directory):
            os.makedirs(directory)
            return True
        return False

    def set_static_directory(self):
        static_directory = Settings().get_static_directory()
        output_directory = Settings().get_output_directory()
        self.create_directory(output_directory + '/' + static_directory)

    def parse_url(self, data, source):
        static_directory = Settings().get_static_directory()
        if source == 0:
            return data.replace('{{ Static }}', '../../' + static_directory)
        return data.replace('{{ Static }}', '../' + static_directory)

    def get_sections_pages(self, section):
        filelist = os.walk('input/'+section).next()[2]
        filelist = [item for item in filelist if item.endswith('.md')]

        return filelist

    def get_file_contents(self, filename, section):
        with open('input/' + section + '/' + filename) as input_file:
            return input_file.read()

    def clean_output_directory(self):
        output_directory = Settings().get_output_directory()
        shutil.rmtree(output_directory)

    def delete_section(self, section):
        output_directory = Settings().get_output_directory()
        shutil.rmtree('input/' + section)
        try:
            shutil.rmtree(output_directory+'/'+section)
        except(OSError):
            pass

    def rename_section(self, section, new_name):
        Settings().add_new_section(new_name)
        try:
            Settings().remove_section(section)
        except(NoSectionError):
            pass

        output_directory = Settings().get_output_directory()
        shutil.copytree('input/'+section, 'input/'+new_name)
        self.delete_section(section)

    def delete_page(self, section, page):
        output_directory = Settings().get_output_directory()
        os.remove('input/' + section + '/' + page + '.md')
        try:
            os.remove('input/' + section + '/' + page + '.md.md5')
        except(OSError):
            pass
        try:
            shutil.rmtree(output_directory+'/'+section+'/'+page)
        except(OSError):
            pass

    def get_syntax_css_url(self, source):
        static_directory = Settings().get_static_directory()
        if source == 1:
            return '../../' + static_directory + '/Syntax.css'
        return '../' + static_directory + '/Syntax.css'

    def get_all_sections(self):
        return os.walk('input').next()[1]

    def get_slug(self, filename):
        return os.path.splitext(filename)[0]

    def get_file_hash(self, section, page):
        return hashlib.md5(self.get_file_contents(page, section)).hexdigest()

    def get_saved_hash(self, section, page):
        if not os.path.isfile('input/' + section + '/' + '.' + page + '.md5'):
            return False
        with open('input/' + section + '/' + '.' + page + '.md5', 'r') as input_file:
            return input_file.read()

    def save_file_hash(self, section, page, hash_info):
        with open('input/' + section + '/' + '.' + page + '.md5', 'w+') as input_file:
            input_file.write(hash_info)

    def parse_file(self, filename, contents):
        filetype = os.path.splitext(filename)[1]

        if filetype == '.md':
            contents = self.parse_markdown(contents)
            metadata = contents.metadata

            return {'contents': contents, 'metadata': metadata}
        else:
            return False

    def parse_markdown(self, contents):
        return markdown.markdown(contents, extras=["metadata"])

    def create_pages_dictionary(self, section):
        pages_list = self.get_sections_pages(section)
        pages_dictionary = {}

        for page in pages_list:
            parsed_contents = self.parse_file(page, self.get_file_contents(page, section))
            pages_dictionary[page[:-3]] = parsed_contents['metadata']

        return pages_dictionary

    def save_page_md(self, section, page, content):
        output_directory = Settings().get_output_directory()
        file_location = './input/' + section + '/' + page + '.md'

        with codecs.open(file_location, 'w+', 'utf-8') as output_file:
            output_file.write(content)

    def check_if_page_exists(self, section, page):
        output_directory = Settings().get_output_directory()
        if os.path.isfile(output_directory+'/'+section+'/'+page+'/index.html'):
            return True

    def get_templates(self):
        return os.walk('templates/').next()[2]

    def get_template_code(self, template):
        with open('templates/'+template) as template_file:
            return template_file.read()

    def save_template(self, template, contents):
        with open('templates/' + template, 'w') as template_file:
            template_file.write(contents)

class Generator:

    def __init__(self):
        Manager().set_static_directory()
        self.generate_syntax_css()

    def generate_feedback(self, force):
        return self.generate_pages(force), self.generate_index_pages()

    def generate_pages(self, force):
        self.sections = Manager().get_all_sections()
        feedback = []

        for section in self.sections:
            section_pages = Manager().get_sections_pages(section)
            template = Settings().get_template(section)

            for page in section_pages:
                page_slug = Manager().get_slug(page)

                parsed_contents = Manager().parse_file(page, Manager().get_file_contents(page, section))

                # If file has other extension than markdown
                if parsed_contents == False:
                    continue

                # If there is only one file in section, generate
                # there only one index file without page directory
                if len(section_pages) == 1:
                    page_slug = '.'

                output_directory = Settings().get_output_directory()

                # If not specified, generated are only those files
                # which have no previous generations
                if not Settings().check_regen_policy() and not force:
                    if Manager().check_if_page_exists(section, page_slug):
                        if Manager().get_saved_hash(section, page) == Manager().get_file_hash(section, page):
                            print output_directory+'/'+section+'/'+page_slug+'/index.html' + '\033[94m PASS\033[0m'
                            feedback.append(output_directory+'/'+section+'/'+page_slug+'/index.html' + ' PASS')
                            continue
                        else:
                            Manager().save_file_hash(section, page, Manager().get_file_hash(section, page))

                parsed_metadata = parsed_contents['metadata']
                parsed_contents = parsed_contents['contents']

                # Highlight syntax
                parsed_contents = Syntax().highlight(parsed_contents)

                context = {}

                # Add static url
                if len(section_pages) == 1:
                    parsed_contents = Manager().parse_url(parsed_contents, 1)
                    context['SyntaxCSS'] = Manager().get_syntax_css_url(0)
                else:
                    parsed_contents = Manager().parse_url(parsed_contents, 0)
                    context['SyntaxCSS'] = Manager().get_syntax_css_url(1)

                # Arguments for template generator
                context['Section'] = section
                context['Page'] = page_slug
                context['Contents'] = parsed_contents
                context['Title'] = parsed_metadata.get('Title', '')
                context['Date'] = parsed_metadata.get('Date', '')
                context['Author'] = parsed_metadata.get('Author', '')
                context['Tags'] = parsed_metadata.get('Tags', '')
                context['ID'] = parsed_metadata.get('ID', '')
                context['Menu'] = self.sections

                if page_slug == '.':
                    context['Page'] = section

                # Generate template
                contents = self._generate_static_html(template, **context)

                # and save it to file
                self._save_static_html(section, page_slug, contents)

                if len(section_pages) == 1 and Settings().compare_default_section(section) == section:
                    self._save_static_html(section, '..', contents)
                    feedback.append(output_directory+'/index.html' + ' OK')

                feedback.append(output_directory+'/'+section+'/'+page_slug+'/index.html' + ' OK')

        return feedback

    def generate_index_pages(self):
        index_dict = {}
        feedback = []

        for section in self.sections:
            section_pages = Manager().get_sections_pages(section)

            if len(section_pages) > 1:
                for page in section_pages:
                    parsed_contents = Manager().parse_file(page, Manager().get_file_contents(page, section))
                    if parsed_contents == False:
                        continue

                    # Highlight syntax
                    parsed_contents['contents'] = Syntax().highlight(parsed_contents['contents'])

                    # Add static url
                    parsed_contents['contents'] = Manager().parse_url(parsed_contents['contents'], 1)

                    page_slug = Manager().get_slug(page)
                    page_id = int(parsed_contents['metadata'].get('ID'))
                    contents = parsed_contents['contents']
                    data = parsed_contents['metadata']

                    data['Contents'] = contents
                    data['Slug'] = '../' + page_slug + '/'
                    index_dict[page_id] = data

                feedback.append(self._generate_single_index_page(section, index_dict))

        return feedback

    def _generate_single_index_page(self, section, dictionary):

        feedback = []

        per_page = int(Settings().get_value(section, 'per_page'))
        i = 0

        template = Settings().get_template(section)
        ascending = Settings().check_if_ascending(section)
        count_dict = len(dictionary)

        # This loop is used for split list of all section's
        # contents to pages
        while(i < count_dict):
            page_slug = str(i+1) + '-' + str(i+per_page)

            buffer_dict = {}

            # If there exists key called ascending in config,
            # pages on index page will be generated from
            # oldest to newest. In that case remember to change
            # in your template line with for loop to:
            # {% for page in Dictionary|sort %}
            if ascending:
                for j in dictionary:
                    if j > i and j <= i + per_page:
                        buffer_dict[j] = dictionary[j]
            else:
                for j in dictionary:
                    if j > i and j <= i + per_page:
                        try:
                            buffer_dict[count_dict - j] = dictionary[count_dict - j + 1]
                        except(KeyError):
                            feedback.append('ERROR! Check pages order!')
                            print 'ERROR! Check pages order!'

            context = {}
            context['Index_page'] = True
            context['Dictionary'] = buffer_dict
            context['Menu'] = self.sections
            context['Section'] = section
            context['SyntaxCSS'] = Manager().get_syntax_css_url(0)

            if i < count_dict - per_page:
                context['next_page_url'] = '../' + str(i+1+per_page) + '-' + str(i+per_page*2) + '/'
            if i != 0:
                context['previous_page_url'] = '../' + str(i+1-per_page) + '-' + str(i) + '/'

            contents = self._generate_static_html(template, **context)
            self._save_static_html(section, page_slug, contents)

            output_directory = Settings().get_output_directory()

            # If section was marked as default in config file
            # its index page will be generated in top of other
            # sections. To make urls compatibile with the rest
            # of files, there is need to modify the dictionary
            if i == 0:

                for j in buffer_dict:
                    page_slug_single = str(buffer_dict[j]['Slug']).split('../')[1]
                    buffer_dict[j]['Slug'] = page_slug_single

                if i < count_dict - per_page:
                    context['next_page_url'] = str(i+1+per_page) + '-' + str(i+per_page*2) + '/'
                contents = self._generate_static_html(template, **context)
                self._save_static_html(section, '.', contents)

                if Settings().compare_default_section(section) == section:

                    for j in buffer_dict:
                        buffer_dict[j]['Slug'] = section + '/' + buffer_dict[j]['Slug']

                    if i < count_dict - per_page:
                        context['next_page_url'] = section + '/' + str(i+1+per_page) + '-' + str(i+per_page*2) + '/'
                    contents = self._generate_static_html(template, **context)
                    self._save_static_html(section, '..', contents)

                    feedback.append(output_directory+'/index.html' + ' OK')

            feedback.append(output_directory+'/'+section+'/'+page_slug+'/index.html' + ' OK')
            i += per_page

        return feedback

    def generate_syntax_css(self):
        css_code = HtmlFormatter().get_style_defs('.highlight')
        output_directory = Settings().get_output_directory()
        static_directory = Settings().get_static_directory()
        if not os.path.isfile(output_directory + '/' + static_directory + '/Syntax.css'):
            with open(output_directory + '/' + static_directory + '/Syntax.css', 'w+') as css_file:
                css_file.write(css_code)

    def _generate_static_html(self, template, **context):
        template = env.get_template(template)
        return template.render(context)

    def _save_static_html(self, section, page, contents):
        output_directory = Settings().get_output_directory()
        Manager().create_directory(output_directory+'/'+section+'/'+page)
        try:
            with codecs.open(output_directory+'/'+section+'/'+page+'/index.html', 'w+', 'utf-8') as html_file:
                html_file.write(contents)
            print output_directory+'/'+section+'/'+page+'/index.html' + '\033[92m OK\033[0m'
        except EnvironmentError:
            print output_directory+'/'+section+'/'+page+'/index.html' + '\033[91m ERROR\033[0m'

# Creating settings file
Settings()

if __name__ == "__main__":
    for arg in sys.argv:
        if arg == 'force':
            Generator().generate_feedback(force=True)
            exit()

    Generator().generate_feedback(force=False)

redpajama_set_name: RedPajamaGithub


text:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'tag',
  styleUrls: ['tag.component.scss'],
  template: `
    <div class="tag" [ngClass]="classes">
      {{ tag }}
    </div>
  `
})
export class TagComponent {
  classes: string = '';

  @Input()
  tag: string;

  ngOnInit() {
    switch(this.tag) {
      case 'New':
        this.classes += 'new';
        break;
    }
  }
}


text:
/**
 * Created by shen on 15-6-28.
 */

var Test = function () {
    return {
        /**
         * edit the style of element
         * @param e
         */
        editStyle: function (e) {
            if(!e) return;
            var newStyle = prompt('input css styles', e.hasAttribute('style') ? e.getAttribute('style') : 'color: orange;');
            if (newStyle != null && newStyle != '') {
                e.setAttribute('style', newStyle);
            }
        }
    };
}();


text:
namespace log4cplus { namespace internal {

bool get_env_var (tstring & value, tstring const & name);
bool parse_bool (bool & val, tstring const & str);

inline
#if defined (_WIN32)
DWORD
get_process_id ()
{
    return GetCurrentProcessId ();
}

#elif defined (LOG4CPLUS_HAVE_GETPID)
pid_t
get_process_id ()
{
    return getpid ();
}

#else
int
get_process_id ()
{
    return 0;
}

#endif

} } // namespace log4cplus { namespace internal {

#endif // LOG4CPLUS_INTERNAL_ENV_H


text:
require 'spec_helper'

describe Fosdick::Tracking do
  describe '#tracking_num=' do
    it "strips whitespace from the tracking number" do
      tracking = described_class.new

      tracking.tracking_num = "\tTRACKING\t"

      expect(tracking.tracking_num).to eq("TRACKING")
    end

    it "handles nil values" do
      tracking = described_class.new

      tracking.tracking_num = nil

      expect(tracking.tracking_num).to eq(nil)
    end
  end
end


text:
alert("hola Pendejos");

function respuesta(){
confirm("Esta usted de acuerdo con los nuevos cambios?");
}

getElementById("header"); //Adcedemos a la clase header


text:
package no.ssb.vtl.script.functions;

import no.ssb.vtl.model.VTLInteger;
import no.ssb.vtl.model.VTLNumber;
import no.ssb.vtl.model.VTLObject;

public class VTLCeil extends AbstractVTLFunction<VTLInteger>{

    private static final Argument<VTLNumber> DS = new Argument<>("ds", VTLNumber.class);
    private static VTLCeil instance;

    private VTLCeil() {
        super("ceil", VTLInteger.class, DS);
    }

    public static VTLCeil getInstance() {
        if (instance == null) {
            instance = new VTLCeil();
        }
        return instance;
    }

    @Override
    protected VTLInteger safeInvoke(TypeSafeArguments arguments) {
        VTLNumber ds = arguments.get(DS);

        if (ds.get() == null) {
            return VTLObject.of((Long) null);
        }

        return VTLNumber.of((long) Math.ceil(ds.get().doubleValue()));
    }
}


text:
import * as tslib_1 from "tslib";
import { MDCFoundation } from '@material/base/foundation';
import { cssClasses } from './constants';
var MDCFloatingLabelFoundation = /** @class */ (function (_super) {
    tslib_1.__extends(MDCFloatingLabelFoundation, _super);
    function MDCFloatingLabelFoundation(adapter) {
        var _this = _super.call(this, tslib_1.__assign({}, MDCFloatingLabelFoundation.defaultAdapter, adapter)) || this;
        _this.shakeAnimationEndHandler_ = function () { return _this.handleShakeAnimationEnd_(); };
        return _this;
    }
    Object.defineProperty(MDCFloatingLabelFoundation, "cssClasses", {
        get: function () {
            return cssClasses;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MDCFloatingLabelFoundation, "defaultAdapter", {
        /**
         * See {@link MDCFloatingLabelAdapter} for typing information on parameters and return types.
         */
        get: function () {
            // tslint:disable:object-literal-sort-keys Methods should be in the same order as the adapter interface.
            return {
                addClass: function () { return undefined; },
                removeClass: function () { return undefined; },
                getWidth: function () { return 0; },
                registerInteractionHandler: function () { return undefined; },
                deregisterInteractionHandler: function () { return undefined; },
            };
            // tslint:enable:object-literal-sort-keys
        },
        enumerable: true,
        configurable: true
    });
    MDCFloatingLabelFoundation.prototype.init = function () {
        this.adapter_.registerInteractionHandler('animationend', this.shakeAnimationEndHandler_);
    };
    MDCFloatingLabelFoundation.prototype.destroy = function () {
        this.adapter_.deregisterInteractionHandler('animationend', this.shakeAnimationEndHandler_);
    };
    /**
     * Returns the width of the label element.
     */
    MDCFloatingLabelFoundation.prototype.getWidth = function () {
        return this.adapter_.getWidth();
    };
    /**
     * Styles the label to produce a shake animation to indicate an error.
     * @param shouldShake If true, adds the shake CSS class; otherwise, removes shake class.
     */
    MDCFloatingLabelFoundation.prototype.shake = function (shouldShake) {
        var LABEL_SHAKE = MDCFloatingLabelFoundation.cssClasses.LABEL_SHAKE;
        if (shouldShake) {
            this.adapter_.addClass(LABEL_SHAKE);
        }
        else {
            this.adapter_.removeClass(LABEL_SHAKE);
        }
    };
    /**
     * Styles the label to float or dock.
     * @param shouldFloat If true, adds the float CSS class; otherwise, removes float and shake classes to dock the label.
     */
    MDCFloatingLabelFoundation.prototype.float = function (shouldFloat) {
        var _a = MDCFloatingLabelFoundation.cssClasses, LABEL_FLOAT_ABOVE = _a.LABEL_FLOAT_ABOVE, LABEL_SHAKE = _a.LABEL_SHAKE;
        if (shouldFloat) {
            this.adapter_.addClass(LABEL_FLOAT_ABOVE);
        }
        else {
            this.adapter_.removeClass(LABEL_FLOAT_ABOVE);
            this.adapter_.removeClass(LABEL_SHAKE);
        }
    };
    MDCFloatingLabelFoundation.prototype.handleShakeAnimationEnd_ = function () {
        var LABEL_SHAKE = MDCFloatingLabelFoundation.cssClasses.LABEL_SHAKE;
        this.adapter_.removeClass(LABEL_SHAKE);
    };
    return MDCFloatingLabelFoundation;
}(MDCFoundation));
export { MDCFloatingLabelFoundation };
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCFloatingLabelFoundation;
//# sourceMappingURL=foundation.js.map


text:
from codecs import open

from setuptools import find_packages, setup

with open('README.rst', 'r', 'utf-8') as f:
    readme = f.read()

setup(
    name='django-glitter-news',
    version='0.3.3',
    description='Django Glitter News for Django',
    long_description=readme,
    url='https://github.com/developersociety/django-glitter-news',
    maintainer='The Developer Society',
    maintainer_email='studio@dev.ngo',
    platforms=['any'],
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'django-glitter',
        'django-taggit>=0.21.3',
        'django-admin-sortable>=2.0.0',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    license='BSD',
)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Salsola tunetana Brullo

### Remarks
null


text:
using namespace std;

// Define the number of runs for the test data
// generated
#define RUN 10000

// Define the maximum number of nodes of the tree
#define MAXNODE 100

int main()
{
	set<pair<int, int>> container;
	set<pair<int, int>>::iterator it;

	freopen ("Test_Cases_Unweighted_Tree.in", "w", stdout);

	//For random values every time
	srand(time(NULL));

	int NUM;	// Number of Vertices/Nodes

	for (int i=1; i<=RUN; i++)
	{
		NUM = 1 + rand() % MAXNODE;

		// First print the number of vertices/nodes
		printf("%d\n", NUM);

		// Then print the edges of the form (a b)
		// where 'a' is connected to 'b'
		for (int j=1; j<=NUM-1; j++)
		{
			int a = 1 + rand() % NUM;
			int b = 1 + rand() % NUM;
			pair<int, int> p = make_pair(a, b);
			pair<int, int> reverse_p = make_pair(b, a);

			// Search for a random "new" edge everytime
			// Note - In a tree the edge (a, b) is same
			// as the edge (b, a)
			while (container.find(p) != container.end() ||
				container.find(reverse_p) != container.end())
			{
				a = 1 + rand() % NUM;
				b = 1 + rand() % NUM;
				p = make_pair(a, b);
				reverse_p = make_pair(b, a);
			}
			container.insert(p);
		}

		for (it=container.begin(); it!=container.end(); ++it)
			printf("%d %d\n", it->first, it->second);

		container.clear();
		printf("\n");
	}

	fclose(stdout);
	return(0);
}


text:
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/value/diagnostics/diagnostic.html">

<script>
'use strict';

tr.exportTo('tr.v.d', function() {
  /**
   * Stringify Arrays or dictionaries. Sorts dictionaries keys. Non-recursive.
   *
   * @param {!Object} obj
   * @return {string}
   */
  function stableStringify(obj) {
    let replacer;
    if (!(obj instanceof Array) && obj !== null) {
      replacer = Object.keys(obj).sort();
    }
    return JSON.stringify(obj, replacer);
  }

  /**
   * @typedef {(null|number|string|boolean|Array.<!PlainOldData>|!Object)}
   * PlainOldData
   */

  class GenericSet extends tr.v.d.Diagnostic {
    /**
     * @param {!Iterable.<!PlainOldData>} values
     */
    constructor(values) {
      super();

      if (typeof values[Symbol.iterator] !== 'function') {
        throw new Error('GenericSet must be constructed from an interable.');
      }

      this.values_ = new Set(values);
      this.has_objects_ = false;

      for (const value of values) {
        if (typeof value === 'object') {
          this.has_objects_ = true;
        }
      }
    }

    get size() {
      return this.values_.size;
    }

    get length() {
      return this.values_.size;
    }

    * [Symbol.iterator]() {
      for (const value of this.values_) {
        yield value;
      }
    }

    has(value) {
      if (typeof value !== 'object') return this.values_.has(value);
      const json = JSON.stringify(value);
      for (const x of this) {
        if (typeof x !== 'object') continue;
        if (json === JSON.stringify(x)) return true;
      }
      return false;
    }

    equals(other) {
      if (!(other instanceof GenericSet)) return false;
      if (this.size !== other.size) return false;
      for (const value of this) {
        if (!other.has(value)) return false;
      }
      return true;
    }

    get hashKey() {
      if (this.has_objects_) return undefined;

      if (this.hash_key_ !== undefined) {
        return this.hash_key_;
      }

      let key = '';
      for (const value of Array.from(this.values_.values()).sort()) {
        key += value;
      }
      this.hash_key_ = key;
      return key;
    }

    serialize(serializer) {
      const i = [...this].map(x => serializer.getOrAllocateId(x));
      return (i.length === 1) ? i[0] : i;
    }

    asDictInto_(d) {
      d.values = Array.from(this);
    }

    static deserialize(data, deserializer) {
      if (!(data instanceof Array)) {
        data = [data];
      }
      return new GenericSet(data.map(datum => deserializer.getObject(datum)));
    }

    static fromDict(d) {
      return new GenericSet(d.values);
    }

    clone() {
      return new GenericSet(this.values_);
    }

    canAddDiagnostic(otherDiagnostic) {
      return otherDiagnostic instanceof GenericSet;
    }

    addDiagnostic(otherDiagnostic) {
      const jsons = new Set();
      for (const value of this) {
        if (typeof value !== 'object') continue;
        jsons.add(stableStringify(value));
      }

      for (const value of otherDiagnostic) {
        if (typeof value === 'object') {
          if (jsons.has(stableStringify(value))) {
            continue;
          }
          this.has_objects_ = true;
        }
        this.values_.add(value);
      }
    }
  }

  tr.v.d.Diagnostic.register(GenericSet, {
    elementName: 'tr-v-ui-generic-set-span'
  });

  return {
    GenericSet,
  };
});
</script>


text:
/** @jsx React.DOM */

var React = React || require('react/addons');

// HtmlInput component
var HtmlInput = React.createClass({
    name: 'html-select',
    mixins: [getCommonMixin],

    // attribute definitions
    getAttributes: function() {
        var attributes = [
            { name:'name', type:'string', required:true, defaultValue:'', note:'field name' },
            { name:'dispatcher', type:'object', required:false, defaultValue:null, note:'flux dispatcher' },
            { name:'boxClass', type:'string', required:false, defaultValue:'', note:'container CSS class' },
            { name:'inputClass', type:'string', required:false, defaultValue:'form-control', note:'input element CSS class' },
            { name:'label', type:'string', required:false, defaultValue:'', note:'input label' },
            { name:'value', type:'string', required:false, defaultValue:'', note:'input type' },
            { name:'options', type:'array', required:false, defaultValue:[], note:'options in array' }
        ];
        return attributes;
    },

    getValue: function() {
        return this.state.value;
    },

    onChange: function(event) {
        var newValue = event.target.value;
        this.setState({ value:newValue });
        this.fire('change', [newValue]);
    },

    render: function() {
        // use first option as default value
        if (!this.state.value && this.state.options && this.state.options[0]) {
            this.state.value = this.state.options[0].id || '';
        }
        var options = [];
        for (var i = 0; i < this.state.options.length; i++) {
            var option = this.state.options[i];
            var optionId = option.id || '';
            var optionText = option.display || option.text || '';
            options.push(
                <option value={ optionId } >{ optionText }</option>
            );
        }
        // set content display
        var content =

                { this.state.label }
                <select
                    className={ this.state.inputClass }
                    value={ this.state.value }
                    onChange={this.onChange } >
                    { options }
                </select>

;
        return (

                { content }

        );
    }
});

module.exports = HtmlInput;


text:
export const environment = {
  production: true,
  applicationId : '',
  serverUrl : 'https://open-wall.azurewebsites.net',
  utm_source : 'open-wall'
};


text:
title: OnDataBound
page_title: OnDataBound - RadGrid
description: Check our Web Forms article about OnDataBound.
slug: grid/client-side-programming/events/ondatabound
tags: ondatabound
published: True
position: 29
---

# OnDataBound

##

Telerik.Web.UI.OnDataBound Property

>note To get or set property values for client API properties, you must call property accessor methods that are named with the get_ and set_ prefixes. For example, to get or set a value for a property such as [cancel](https://msdn.microsoft.com/en-us/library/bb310859.aspx), you call the get_cancel or set_cancel.
>

This event will be raised right after the grid is bound to data client-side.

>note Meaningful with client-side data-binding only!
>

|  **Fired by**  | RadGrid |
| ------ | ------ |
| **Arguments** | **N/A** - dom event|
| **Can be canceled** |No|

Example:

````ASP.NET
<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server">
    <ClientSettings>
        <ClientEvents OnDataBound="RadGrid1_DataBound" />
    </ClientSettings>
</telerik:RadGrid>
````

````JavaScript
function RadGrid1_DataBound(sender, args) {
    alert("Grid with id: " + sender.get_element().id + " bound on the client");
}
````


text:
package com.allesad.habraclient.activities;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

import com.allesad.habraclient.R;
import com.allesad.habraclient.adapters.gallery.PhotoGalleryPagerAdapter;
import com.allesad.habraclient.components.ViewPagerExtended;
import com.allesad.habraclient.utils.ArgumentConstants;

public class PhotoGalleryActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v13.app.FragmentStatePagerAdapter}.
     */
    private PhotoGalleryPagerAdapter mAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPagerExtended mViewPager;

    private int mCurrentImagePosition;
    private int mTotalImagesCounter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.view_photo_gallery);

        List<String> imagePaths = getIntent().getStringArrayListExtra(ArgumentConstants.IMAGE_PATHS);
        String selectedImage = getIntent().getStringExtra(ArgumentConstants.SELECTED_IMAGE);
        mCurrentImagePosition = imagePaths.indexOf(selectedImage);
        mTotalImagesCounter = imagePaths.size();

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mAdapter = new PhotoGalleryPagerAdapter(this, imagePaths);

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPagerExtended) findViewById(R.id.pager);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(this);
        mViewPager.setCurrentItem(mCurrentImagePosition);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setDisplayShowHomeEnabled(true);

        setUpTitle();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.photo_gallery, menu);

        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    @Override
    public void onPageSelected(int position) {
        mCurrentImagePosition = position;
        setUpTitle();
    }

    @Override
    public void onPageScrollStateChanged(int state) {}

    private void setUpTitle(){
        String title = (mCurrentImagePosition + 1) + " " + getString(R.string.of) + " " + mTotalImagesCounter;
        setTitle(title);
    }
}


text:
import scrapy
from scrapy.selector import Selector
from XboxBC.items import MetacriticXbox360Item
import re

class MetacriticXbox360(scrapy.Spider):
    name = "MetacriticXbox360"
    allowed_domains = ["metacritic.com"]
    start_urls = (
        'http://www.metacritic.com/browse/games/score/metascore/all/xbox360/all?hardware=all&page=0',
    )

    def parse(self, response):
        numberOfPages = int(response.xpath('//*[@id="main"]/div[1]/div[2]/div/div[2]/ul/li[10]/a/text()').extract()[0])
        for j in range(0,numberOfPages):
            next_page = 'http://www.metacritic.com/browse/games/score/metascore/all/xbox360/all?hardware=all&page=' + str(j)
            yield scrapy.Request(next_page, callback=self.metacriticX360Find)

    def metacriticX360Find(self, response):
            rows_in_big_table = response.xpath('//*[@id="main"]/div[1]/div[1]/div[2]/div[3]/div/div/div')
            print(rows_in_big_table.extract())
            for i, onerow in enumerate(rows_in_big_table):
                metacriticGameItem = MetacriticXbox360Item()
                gameName = onerow.xpath('div[3]/a/text()').extract()[0].strip()
                reviewScorePro = onerow.xpath('div[2]/div/text()').extract()[0].strip()
                reviewScoreUser = onerow.xpath('div[4]/span[2]/text()').extract()[0].strip()
                if reviewScoreUser== 'tbd':
                    reviewScoreUser = ''
                metacriticGameItem['gameName'] = gameName
                metacriticGameItem['reviewScorePro'] = reviewScorePro
                metacriticGameItem['reviewScoreUser'] = reviewScoreUser
                yield metacriticGameItem


text:
using SharpDX;
using System.Collections.Generic;
using System.IO;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Model.Scene
    {
        using Core;
        using Utilities;

        public class Sprite2DNode : SceneNode
        {
            private Stream texture;
            public Stream Texture
            {
                set
                {
                    if (SetAffectsRender(ref texture, value) && IsAttached)
                    {
                        var newView = value == null ? null : EffectTechnique.EffectsManager.MaterialTextureManager.Register(value, true);
                        RemoveAndDispose(ref textureView);
                        TextureView = Collect(newView);
                    }
                }
                get { return texture; }
            }

            public Matrix ProjectionMatrix
            {
                set
                {
                    (RenderCore as Sprite2DRenderCore).ProjectionMatrix = value;
                }
                get
                {
                    return (RenderCore as Sprite2DRenderCore).ProjectionMatrix;
                }
            }

            private SpriteStruct[] sprites;
            public SpriteStruct[] Sprites
            {
                set
                {
                    if(Set(ref sprites, value) && IsAttached)
                    {
                        bufferModel.Sprites = value;
                    }
                }
                get { return sprites; }
            }

            private int spriteCount;
            public int SpriteCount
            {
                set
                {
                    if (SetAffectsRender(ref spriteCount, value) && IsAttached)
                    {
                        bufferModel.SpriteCount = value;
                    }
                }
                get { return spriteCount; }
            }

            private int[] indices;
            public int[] Indices
            {
                set
                {
                    if(SetAffectsRender(ref indices, value) && IsAttached)
                    {
                        bufferModel.Indices = value;
                    }
                }
                get
                {
                    return indices;
                }
            }

            private int indexCount;
            public int IndexCount
            {
                set
                {
                    if(SetAffectsRender(ref indexCount, value) && IsAttached)
                    {
                        bufferModel.IndexCount = value;
                    }
                }
                get { return indexCount; }
            }

            private Sprite2DBufferModel bufferModel;

            private ShaderResourceViewProxy textureView;
            protected ShaderResourceViewProxy TextureView
            {
                set
                {
                    if(SetAffectsRender(ref textureView, value))
                    {
                        (RenderCore as Sprite2DRenderCore).TextureView = value;
                    }
                }
                get { return textureView; }
            }

            protected override RenderCore OnCreateRenderCore()
            {
                return new Sprite2DRenderCore();
            }

            protected override void OnAttached()
            {
                bufferModel = Collect(new Sprite2DBufferModel());
                bufferModel.Sprites = Sprites;
                bufferModel.SpriteCount = SpriteCount;
                if (texture != null)
                {
                    TextureView = Collect(EffectTechnique.EffectsManager.MaterialTextureManager.Register(texture, true));
                }
                base.OnAttached();
            }

            protected override void OnDetach()
            {
                bufferModel = null;
                TextureView = null;
                base.OnDetach();
            }

            protected override bool CanRender(RenderContext context)
            {
                return base.CanRender(context) && sprites != null && indices != null
                    && spriteCount != 0 && indexCount != 0 && textureView != null;
            }

            protected override bool CanHitTest(HitTestContext context)
            {
                return false;
            }

            protected override bool OnHitTest(HitTestContext context, Matrix totalModelMatrix, ref List<HitTestResult> hits)
            {
                return false;
            }
        }
    }

}


text:
<?php

namespace Oro\Bundle\UIBundle\Twig;

use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

use Knp\Menu\MenuItem;

use Oro\Bundle\NavigationBundle\Twig\MenuExtension;
use Oro\Bundle\SecurityBundle\SecurityFacade;

class TabExtension extends \Twig_Extension
{
    const TEMPLATE = 'OroUIBundle::tab_panel.html.twig';
    const DEFAULT_WIDGET_TYPE = 'block';

    /**
     * @var MenuExtension
     */
    protected $menuExtension;

    /**
     * @var RouterInterface
     */
    protected $router;

    /**
     * @var SecurityFacade
     */
    protected $securityFacade;

    /**
     * @var TranslatorInterface
     */
    protected $translator;

    public function __construct(
        MenuExtension $menuExtension,
        RouterInterface $router,
        SecurityFacade $securityFacade,
        TranslatorInterface $translator
    ) {
        $this->menuExtension  = $menuExtension;
        $this->router         = $router;
        $this->securityFacade = $securityFacade;
        $this->translator     = $translator;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            'menuTabPanel' => new \Twig_Function_Method(
                $this,
                'menuTabPanel',
                [
                    'is_safe' => ['html'],
                    'needs_environment' => true
                ]
            ),
            'tabPanel' => new \Twig_Function_Method(
                $this,
                'tabPanel',
                [
                    'is_safe' => ['html'],
                    'needs_environment' => true
                ]
            )
        ];
    }

    /**
     * @param \Twig_Environment $environment
     * @param string $menuName
     * @param array $options
     *
     * @return string
     */
    public function menuTabPanel(\Twig_Environment $environment, $menuName, $options = [])
    {
        $tabs = $this->getTabs($menuName, $options);

        if (empty($tabs)) {
            return '';
        }

        return $environment->render(self::TEMPLATE, ['tabs' => $tabs]);
    }

    /**
     * @param string $menuName
     * @param array  $options
     *
     * @throws \Symfony\Component\Validator\Exception\InvalidArgumentException
     * @return array
     */
    public function getTabs($menuName, $options = [])
    {
        /* @var MenuItem $menu */
        $menu = $this->menuExtension->getMenu($menuName, [], $options);

        $tabs = [];
        foreach ($menu->getChildren() as $child) {
            if (!$child->isDisplayed()) {
                continue;
            }

            if (!$url = $child->getUri()) {
                if ($route = $child->getExtra('widgetRoute')) {
                    $routeParameters = array_merge(
                        $child->getExtra('widgetRouteParameters', []),
                        $options
                    );

                    $routeParametersMap = $child->getExtra('widgetRouteParametersMap', []);
                    foreach ($routeParametersMap as $routeParameter => $optionParameter) {
                        if (isset($options[$optionParameter])) {
                            $routeParameters[$routeParameter] = $options[$optionParameter];

                            unset($routeParameters[$optionParameter]);
                        }
                    }

                    $url = $this->router->generate($route, $routeParameters);
                } else {
                    throw new InvalidArgumentException(
                        sprintf('Extra parameter "widgetRoute" should be defined for %s', $child->getName())
                    );
                }
            }

            if ($this->securityFacade->isGranted($child->getExtra('widgetAcl'))) {
                $label = $child->getLabel();
                if (!empty($label)) {
                    $label = $this->translator->trans($label);
                }
                $tabs[] = [
                    'alias'      => $child->getName(),
                    'label'      => $label,
                    'widgetType' => $child->getExtra('widgetType', self::DEFAULT_WIDGET_TYPE),
                    'url'        => $url
                ];
            }
        }

        if (empty($tabs)) {
            $menu->setDisplay(false);
        }

        return $tabs;
    }

    /**
     * @param \Twig_Environment $environment
     * @param array $tabs
     * @return string
     */
    public function tabPanel(\Twig_Environment $environment, $tabs)
    {
        return $environment->render(
            self::TEMPLATE,
            [
                'tabs' => $tabs
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'oro_ui.tab_panel';
    }
}


text:
<?php

class Params implements ArrayAccess
{
	function offsetGet( $index )
	{
		return Validator::create($_POST[$index], $index);
	}

	function offsetExists($offset) {
		return isset($_POST[$offset]);
	}

	function offsetSet($offset, $value) {
        return false;
    }
	function offsetUnset($offset ) {
        return false;
    }

    public function __call($name,$params)
    {
    	return call_user_func_array('Validator::'.$name, $params);
    }
    public function __get($name)
    {
    	return call_user_func('Validator::'.$name);
    }

}