text:
// HeeksCNC.cpp

#include "stdafx.h"
#include <errno.h>

#ifndef WIN32
#include <dirent.h>
#endif

#include <wx/stdpaths.h>
#include <wx/dynlib.h>
#include <wx/aui/aui.h>
#include <wx/filename.h>
#include "interface/PropertyString.h"
#include "interface/PropertyCheck.h"
#include "interface/PropertyList.h"
#include "interface/Observer.h"
#include "interface/ToolImage.h"
#include "PythonStuff.h"
#include "Program.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "CNCConfig.h"
#include "NCCode.h"
#include "Profile.h"
#include "Pocket.h"
#include "Drilling.h"
#include "CTool.h"
#include "Operations.h"
#include "Tools.h"
#include "interface/strconv.h"
#include "interface/Tool.h"
#include "CNCPoint.h"
#include "Excellon.h"
#include "Tags.h"
#include "Tag.h"
#include "ScriptOp.h"
#include "Simulate.h"
#include "Pattern.h"
#include "Patterns.h"
#include "Surface.h"
#include "Surfaces.h"
#include "Stock.h"
#include "Stocks.h"

#include <sstream>

CHeeksCADInterface* heeksCAD = NULL;

CHeeksCNCApp theApp;

extern void ImportToolsFile( const wxChar *file_path );

wxString HeeksCNCType(const int type);

CHeeksCNCApp::CHeeksCNCApp(){
	m_draw_cutter_radius = true;
	m_program = NULL;
	m_run_program_on_new_line = false;
	m_machiningBar = NULL;
	m_icon_texture_number = 0;
	m_machining_hidden = false;
	m_settings_restored = false;
}

CHeeksCNCApp::~CHeeksCNCApp(){
}

void CHeeksCNCApp::OnInitDLL()
{
}

void CHeeksCNCApp::OnDestroyDLL()
{
	// save any settings
	//config.Write("SolidSimWorkingDir", m_working_dir_for_solid_sim);

#if !defined WXUSINGDLL
	wxUninitialize();
#endif

	heeksCAD = NULL;
}

void OnMachiningBar( wxCommandEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	wxAuiPaneInfo& pane_info = aui_manager->GetPane(theApp.m_machiningBar);
	if(pane_info.IsOk()){
		pane_info.Show(event.IsChecked());
		aui_manager->Update();
	}
}

void OnUpdateMachiningBar( wxUpdateUIEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	event.Check(aui_manager->GetPane(theApp.m_machiningBar).IsShown());
}

void OnProgramCanvas( wxCommandEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	wxAuiPaneInfo& pane_info = aui_manager->GetPane(theApp.m_program_canvas);
	if(pane_info.IsOk()){
		pane_info.Show(event.IsChecked());
		aui_manager->Update();
	}
}

void OnUpdateProgramCanvas( wxUpdateUIEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	event.Check(aui_manager->GetPane(theApp.m_program_canvas).IsShown());
}

static void OnOutputCanvas( wxCommandEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	wxAuiPaneInfo& pane_info = aui_manager->GetPane(theApp.m_output_canvas);
	if(pane_info.IsOk()){
		pane_info.Show(event.IsChecked());
		aui_manager->Update();
	}
}

static void OnPrintCanvas( wxCommandEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	wxAuiPaneInfo& pane_info = aui_manager->GetPane(theApp.m_print_canvas);
	if(pane_info.IsOk()){
		pane_info.Show(event.IsChecked());
		aui_manager->Update();
	}
}

static void OnUpdateOutputCanvas( wxUpdateUIEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	event.Check(aui_manager->GetPane(theApp.m_output_canvas).IsShown());
}

static void OnUpdatePrintCanvas( wxUpdateUIEvent& event )
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	event.Check(aui_manager->GetPane(theApp.m_print_canvas).IsShown());
}

static void GetSketches(std::list<int>& sketches, std::list<int> &tools )
{
	// check for at least one sketch selected

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetIDGroupType() == SketchType)
		{
			sketches.push_back(object->m_id);
		} // End if - then

		if ((object != NULL) && (object->GetType() == ToolType))
		{
			tools.push_back( object->m_id );
		} // End if - then
	}
}

static void NewProfileOp()
{
	std::list<int> tools;
	std::list<int> sketches;
	GetSketches(sketches, tools);

	int sketch = 0;
	if(sketches.size() > 0)sketch = sketches.front();

	CProfile *new_object = new CProfile(sketch, (tools.size()>0)?(*tools.begin()):-1);
	new_object->SetID(heeksCAD->GetNextID(ProfileType));
	new_object->AddMissingChildren(); // add the tags container

	if(new_object->Edit())
	{
		heeksCAD->StartHistory();
		heeksCAD->AddUndoably(new_object, theApp.m_program->Operations());

		if(sketches.size() > 1)
		{
			for(std::list<int>::iterator It = sketches.begin(); It != sketches.end(); It++)
			{
				if(It == sketches.begin())continue;
				CProfile* copy = (CProfile*)(new_object->MakeACopy());
				copy->m_sketch = *It;
				heeksCAD->AddUndoably(copy, theApp.m_program->Operations());
			}
		}
		heeksCAD->EndHistory();
	}
	else
		delete new_object;
}

static void NewProfileOpMenuCallback(wxCommandEvent &event)
{
	NewProfileOp();
}

static void NewPocketOp()
{
	std::list<int> tools;
	std::list<int> sketches;
	GetSketches(sketches, tools);

	int sketch = 0;
	if(sketches.size() > 0)sketch = sketches.front();

	CPocket *new_object = new CPocket(sketch, (tools.size()>0)?(*tools.begin()):-1 );
	new_object->SetID(heeksCAD->GetNextID(PocketType));

	if(new_object->Edit())
	{
		heeksCAD->StartHistory();
		heeksCAD->AddUndoably(new_object, theApp.m_program->Operations());

		if(sketches.size() > 1)
		{
			for(std::list<int>::iterator It = sketches.begin(); It != sketches.end(); It++)
			{
				if(It == sketches.begin())continue;
				CPocket* copy = (CPocket*)(new_object->MakeACopy());
				copy->m_sketch = *It;
				heeksCAD->AddUndoably(copy, theApp.m_program->Operations());
			}
		}
		heeksCAD->EndHistory();
	}
	else
		delete new_object;
}

static void NewPocketOpMenuCallback(wxCommandEvent &event)
{
	NewPocketOp();
}

static void AddNewObjectUndoablyAndMarkIt(HeeksObj* new_object, HeeksObj* parent)
{
	heeksCAD->StartHistory();
	heeksCAD->AddUndoably(new_object, parent);
	heeksCAD->ClearMarkedList();
	heeksCAD->Mark(new_object);
	heeksCAD->EndHistory();
}

static void NewDrillingOp()
{
	std::list<int> points;

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if (object->GetType() == PointType)
		{
			points.push_back( object->m_id );
		} // End if - else
	} // End for

	{
		CDrilling *new_object = new CDrilling( points, 0, -1 );
		new_object->SetID(heeksCAD->GetNextID(DrillingType));
		if(new_object->Edit())
		{
			heeksCAD->StartHistory();
			heeksCAD->AddUndoably(new_object, theApp.m_program->Operations());
			heeksCAD->EndHistory();
		}
		else
			delete new_object;
	}
}

static void NewDrillingOpMenuCallback(wxCommandEvent &event)
{
	NewDrillingOp();
}

static void NewScriptOpMenuCallback(wxCommandEvent &event)
{
	CScriptOp *new_object = new CScriptOp();
	new_object->SetID(heeksCAD->GetNextID(ScriptOpType));
	if(new_object->Edit())
	{
		heeksCAD->StartHistory();
		AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Operations());
		heeksCAD->EndHistory();
	}
	else
		delete new_object;
}

static void NewPatternMenuCallback(wxCommandEvent &event)
{
	CPattern *new_object = new CPattern();

	if(new_object->Edit())
	{
		heeksCAD->StartHistory();
		AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Patterns());
		heeksCAD->EndHistory();
	}
	else
		delete new_object;
}

static void NewSurfaceMenuCallback(wxCommandEvent &event)
{
	// check for at least one solid selected
	std::list<int> solids;

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetIDGroupType() == SolidType)solids.push_back(object->m_id);
	}

	// if no selected solids,
	if(solids.size() == 0)
	{
		// use all the solids in the drawing
		for(HeeksObj* object = heeksCAD->GetFirstObject();object; object = heeksCAD->GetNextObject())
		{
			if(object->GetIDGroupType() == SolidType)solids.push_back(object->m_id);
		}
	}

	{
		CSurface *new_object = new CSurface();
		new_object->m_solids = solids;
		if(new_object->Edit())
		{
			heeksCAD->StartHistory();
			AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Surfaces());
			heeksCAD->EndHistory();
		}
		else
			delete new_object;
	}
}

static void NewStockMenuCallback(wxCommandEvent &event)
{
	// check for at least one solid selected
	std::list<int> solids;

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetIDGroupType() == SolidType)solids.push_back(object->m_id);
	}

	// if no selected solids,
	if(solids.size() == 0)
	{
		// use all the solids in the drawing
		for(HeeksObj* object = heeksCAD->GetFirstObject();object; object = heeksCAD->GetNextObject())
		{
			if(object->GetIDGroupType() == SolidType)solids.push_back(object->m_id);
		}
	}

	{
		CStock *new_object = new CStock();
		new_object->m_solids = solids;
		if(new_object->Edit())
		{
			heeksCAD->StartHistory();
			AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Stocks());
			heeksCAD->EndHistory();
		}
		else
			delete new_object;
	}
}

static void AddNewTool(CToolParams::eToolType type)
{
	// find next available tool number
	int max_tool_number = 0;
	for(HeeksObj* object = theApp.m_program->Tools()->GetFirstChild(); object; object = theApp.m_program->Tools()->GetNextChild())
	{
		if(object->GetType() == ToolType)
		{
			int tool_number = ((CTool*)object)->m_tool_number;
			if(tool_number > max_tool_number)max_tool_number = tool_number;
		}
	}

	// Add a new tool.
	CTool *new_object = new CTool(NULL, type, max_tool_number + 1);
	if(new_object->Edit())
		AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Tools());
	else
		delete new_object;
}

static void NewDrillMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eDrill);
}

static void NewCentreDrillMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eCentreDrill);
}

static void NewEndmillMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eEndmill);
}

static void NewSlotCutterMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eSlotCutter);
}

static void NewBallEndMillMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eBallEndMill);
}

static void NewChamferMenuCallback(wxCommandEvent &event)
{
	AddNewTool(CToolParams::eChamfer);
}

void CHeeksCNCApp::RunPythonScript()
{
	{
		// clear the output file
		wxFile f(m_program->GetOutputFileName().c_str(), wxFile::write);
		if(f.IsOpened())f.Write(_T("\n"));
	}

	// Check to see if someone has modified the contents of the
	// program canvas manually.  If so, replace the m_python_program
	// with the edited program.  We don't want to do this without
	// this check since the maximum size of m_textCtrl is sometimes
	// a limitation to the size of the python program.  If the first 'n' characters
	// of m_python_program matches the full contents of the m_textCtrl then
	// it's likely that the text control holds as much of the python program
	// as it can hold but more may still exist in m_python_program.
	unsigned int text_control_length = m_program_canvas->m_textCtrl->GetLastPosition();
	if (m_program->m_python_program.substr(0,text_control_length) != m_program_canvas->m_textCtrl->GetValue())
	{
		// copy the contents of the program canvas to the string
		m_program->m_python_program.clear();
		m_program->m_python_program << theApp.m_program_canvas->m_textCtrl->GetValue();
	}

#ifdef FREE_VERSION
	::wxLaunchDefaultBrowser(_T("http://heeks.net/help/buy-heekscnc-1-0"));
#endif

	HeeksPyPostProcess(m_program, m_program->GetOutputFileName(), true );
}

static void RunScriptMenuCallback(wxCommandEvent &event)
{
	theApp.RunPythonScript();
}

static void PostProcessMenuCallback(wxCommandEvent &event)
{
	// write the python program
	theApp.m_program->RewritePythonProgram();

	// run it
	theApp.RunPythonScript();
}

static void CancelMenuCallback(wxCommandEvent &event)
{
	HeeksPyCancel();
}

#ifdef WIN32
static void SimulateCallback(wxCommandEvent &event)
{
	RunVoxelcutSimulation();
}
#endif

static void OpenNcFileMenuCallback(wxCommandEvent& event)
{
	// Default directory
	wxString defaultDir = wxEmptyString;
	if(heeksCAD->GetProjectFileName().IsOk()) // Project have already been opened/saved from/to a file
	{
		// Extract default directory from project filename
		defaultDir = heeksCAD->GetProjectFileName().GetPath();
	}

	// Default extension filter
	wxFileName defaultFileName(theApp.m_program->GetOutputFileName());
	wxString wildcard_string = wxString::Format(wxT("%s (*.%s)|*.%s|%s (%s)|%s"),
			_("NC files"), defaultFileName.GetExt().c_str(), defaultFileName.GetExt().c_str(),
			_("All files"), wxFileSelectorDefaultWildcardStr, wxFileSelectorDefaultWildcardStr
			);

	wxFileDialog dialog(theApp.m_output_canvas, _("Open NC file"), defaultDir, wxEmptyString, wildcard_string);
	dialog.CentreOnParent();

	if (dialog.ShowModal() == wxID_OK)
	{
		HeeksPyBackplot(theApp.m_program, theApp.m_program, dialog.GetPath().c_str());
	}
}

// create a temporary file for ngc output
// run appropriate command to make 'Machine' read ngc file
// linux/emc/axis: this would typically entail calling axis-remote <filename>

static void SendToMachineMenuCallback(wxCommandEvent& event)
{
	HeeksSendToMachine(theApp.m_output_canvas->m_textCtrl->GetValue());
}

static void SaveNcFileMenuCallback(wxCommandEvent& event)
{
#if wxCHECK_VERSION(3, 0, 0)
	wxStandardPaths& sp = wxStandardPaths::Get();
#else
	wxStandardPaths sp;
#endif
	// Default directory
	wxString defaultDir = sp.GetDocumentsDir();
	if(heeksCAD->GetProjectFileName().IsOk()) // Project have already been opened/saved from/to a file
	{
    	// Extract default directory from project filename
		defaultDir = heeksCAD->GetProjectFileName().GetPath();
	}

    // Default filename
	wxFileName defaultFileName(theApp.m_program->GetOutputFileName());

	// Default extension filter
	wxString wildcard_string = wxString::Format(wxT("%s (%s)|%s|%s (*.%s)|*.%s"),
			_("All files"), wxFileSelectorDefaultWildcardStr, wxFileSelectorDefaultWildcardStr,
			_("NC files"), defaultFileName.GetExt().c_str(), defaultFileName.GetExt().c_str()
			);

	wxFileDialog fd(theApp.m_output_canvas, _("Save NC file"), defaultDir, defaultFileName.GetFullName(), wildcard_string, wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
	fd.SetFilterIndex(1);
	if (fd.ShowModal() == wxID_OK)
	{
		wxString nc_file_str = fd.GetPath().c_str();
		{
			wxFile ofs(nc_file_str.c_str(), wxFile::write);
			if(!ofs.IsOpened())
			{
				wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + nc_file_str);
				return;
			}

			if(theApp.m_use_DOS_not_Unix == true)   //DF -added to get DOS line endings HeeksCNC running on Unix
			{
				long line_num= 0;
				bool ok = true;
				int nLines = theApp.m_output_canvas->m_textCtrl->GetNumberOfLines();
				for ( int nLine = 0; ok && nLine < nLines; nLine ++)
				{
					ok = ofs.Write(theApp.m_output_canvas->m_textCtrl->GetLineText(line_num) + _T("\r\n") );
					line_num = line_num+1;
				}
			}

			else
				ofs.Write(theApp.m_output_canvas->m_textCtrl->GetValue());
		}
		HeeksPyBackplot(theApp.m_program, theApp.m_program, nc_file_str);
	}
}

static void HelpMenuCallback(wxCommandEvent& event)
{
	::wxLaunchDefaultBrowser(_T("http://heeks.net/help"));
}

// a class to re-use existing "OnButton" functions in a Tool class
class CCallbackTool: public Tool{
	public:
		wxString m_title;
		wxString m_bitmap_path;
		void(*m_callback)(wxCommandEvent&);

		CCallbackTool(const wxString& title, const wxString& bitmap_path, void(*callback)(wxCommandEvent&)): m_title(title), m_bitmap_path(bitmap_path), m_callback(callback){}

		// Tool's virtual functions
		const wxChar* GetTitle(){return m_title;}
		void Run(){
			wxCommandEvent dummy_evt;
			(*m_callback)(dummy_evt);
		}
		wxString BitmapPath(){ return m_bitmap_path;}
};

static CCallbackTool new_drill_tool(_("New Drill..."), _T("drill"), NewDrillMenuCallback);
static CCallbackTool new_centre_drill_tool(_("New Centre Drill..."), _T("centredrill"), NewCentreDrillMenuCallback);
static CCallbackTool new_endmill_tool(_("New End Mill..."), _T("endmill"), NewEndmillMenuCallback);
static CCallbackTool new_slotdrill_tool(_("New Slot Drill..."), _T("slotdrill"), NewSlotCutterMenuCallback);
static CCallbackTool new_ball_end_mill_tool(_("New Ball End Mill..."), _T("ballmill"), NewBallEndMillMenuCallback);
static CCallbackTool new_chamfer_mill_tool(_("New Chamfer Mill..."), _T("chamfmill"), NewChamferMenuCallback);

void CHeeksCNCApp::GetNewToolTools(std::list<Tool*>* t_list)
{
	t_list->push_back(&new_drill_tool);
	t_list->push_back(&new_centre_drill_tool);
	t_list->push_back(&new_endmill_tool);
	t_list->push_back(&new_slotdrill_tool);
	t_list->push_back(&new_ball_end_mill_tool);
	t_list->push_back(&new_chamfer_mill_tool);
}

static CCallbackTool new_pattern_tool(_("New Pattern..."), _T("pattern"), NewPatternMenuCallback);

void CHeeksCNCApp::GetNewPatternTools(std::list<Tool*>* t_list)
{
	t_list->push_back(&new_pattern_tool);
}

static CCallbackTool new_surface_tool(_("New Surface..."), _T("surface"), NewSurfaceMenuCallback);

void CHeeksCNCApp::GetNewSurfaceTools(std::list<Tool*>* t_list)
{
	t_list->push_back(&new_surface_tool);
}

static CCallbackTool new_stock_tool(_("New Stock..."), _T("stock"), NewStockMenuCallback);

void CHeeksCNCApp::GetNewStockTools(std::list<Tool*>* t_list)
{
	t_list->push_back(&new_stock_tool);
}

#define MAX_XML_SCRIPT_OPS 10

std::vector< CXmlScriptOp > script_ops;
int script_op_flyout_index = 0;

static void NewXmlScriptOp(int i)
{
	CScriptOp *new_object = new CScriptOp();
	new_object->m_title_made_from_id = false;
	new_object->m_title = script_ops[i].m_name;
	new_object->m_str = script_ops[i].m_script;
	new_object->m_user_icon = true;
	new_object->m_user_icon_name = script_ops[i].m_icon;

	if(new_object->Edit())
	{
		heeksCAD->StartHistory();
		AddNewObjectUndoablyAndMarkIt(new_object, theApp.m_program->Operations());
		heeksCAD->EndHistory();
	}
	else
		delete new_object;
}

static void NewXmlScriptOpCallback0(wxCommandEvent &event)
{
	NewXmlScriptOp(0);
}

static void NewXmlScriptOpCallback1(wxCommandEvent &event)
{
	NewXmlScriptOp(1);
}

static void NewXmlScriptOpCallback2(wxCommandEvent &event)
{
	NewXmlScriptOp(2);
}

static void NewXmlScriptOpCallback3(wxCommandEvent &event)
{
	NewXmlScriptOp(3);
}

static void NewXmlScriptOpCallback4(wxCommandEvent &event)
{
	NewXmlScriptOp(4);
}

static void NewXmlScriptOpCallback5(wxCommandEvent &event)
{
	NewXmlScriptOp(5);
}

static void NewXmlScriptOpCallback6(wxCommandEvent &event)
{
	NewXmlScriptOp(6);
}

static void NewXmlScriptOpCallback7(wxCommandEvent &event)
{
	NewXmlScriptOp(7);
}

static void NewXmlScriptOpCallback8(wxCommandEvent &event)
{
	NewXmlScriptOp(8);
}

static void NewXmlScriptOpCallback9(wxCommandEvent &event)
{
	NewXmlScriptOp(9);
}

static void AddXmlScriptOpMenuItems(wxMenu *menu = NULL)
{
	script_ops.clear();
	CProgram::GetScriptOps(script_ops);

	int i = 0;
	for(std::vector< CXmlScriptOp >::iterator It = script_ops.begin(); It != script_ops.end(); It++, i++)
	{
		CXmlScriptOp &s = *It;
		if(i >= MAX_XML_SCRIPT_OPS)break;
		void(*onButtonFunction)(wxCommandEvent&) = NULL;
		switch(i)
		{
			case 0:
				onButtonFunction = NewXmlScriptOpCallback0;
				break;
			case 1:
				onButtonFunction = NewXmlScriptOpCallback1;
				break;
			case 2:
				onButtonFunction = NewXmlScriptOpCallback2;
				break;
			case 3:
				onButtonFunction = NewXmlScriptOpCallback3;
				break;
			case 4:
				onButtonFunction = NewXmlScriptOpCallback4;
				break;
			case 5:
				onButtonFunction = NewXmlScriptOpCallback5;
				break;
			case 6:
				onButtonFunction = NewXmlScriptOpCallback6;
				break;
			case 7:
				onButtonFunction = NewXmlScriptOpCallback7;
				break;
			case 8:
				onButtonFunction = NewXmlScriptOpCallback8;
				break;
			case 9:
				onButtonFunction = NewXmlScriptOpCallback9;
				break;
		}

		if(menu)
			heeksCAD->AddMenuItem(menu, s.m_name, ToolImage(s.m_bitmap), onButtonFunction);
		else
			heeksCAD->AddFlyoutButton(s.m_name, ToolImage(s.m_bitmap), s.m_name, onButtonFunction);
	}
}

static void AddToolBars()
{
	if(!theApp.m_machining_hidden)
	{
		wxFrame* frame = heeksCAD->GetMainFrame();
		if(theApp.m_machiningBar)delete theApp.m_machiningBar;
		theApp.m_machiningBar = new wxToolBar(frame, -1, wxDefaultPosition, wxDefaultSize, wxTB_NODIVIDER | wxTB_FLAT);
		theApp.m_machiningBar->SetToolBitmapSize(wxSize(ToolImage::GetBitmapSize(), ToolImage::GetBitmapSize()));

		heeksCAD->StartToolBarFlyout(_("Milling operations"));
		heeksCAD->AddFlyoutButton(_T("Profile"), ToolImage(_T("opprofile")), _("New Profile Operation..."), NewProfileOpMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Pocket"), ToolImage(_T("pocket")), _("New Pocket Operation..."), NewPocketOpMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Drill"), ToolImage(_T("drilling")), _("New Drill Cycle Operation..."), NewDrillingOpMenuCallback);
		heeksCAD->EndToolBarFlyout((wxToolBar*)(theApp.m_machiningBar));

		heeksCAD->StartToolBarFlyout(_("Other operations"));
		heeksCAD->AddFlyoutButton(_T("ScriptOp"), ToolImage(_T("scriptop")), _("New Script Operation..."), NewScriptOpMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Pattern"), ToolImage(_T("pattern")), _("New Pattern..."), NewPatternMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Surface"), ToolImage(_T("surface")), _("New Surface..."), NewSurfaceMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Stock"), ToolImage(_T("stock")), _("New Stock..."), NewStockMenuCallback);
		AddXmlScriptOpMenuItems();

		heeksCAD->EndToolBarFlyout((wxToolBar*)(theApp.m_machiningBar));

		heeksCAD->StartToolBarFlyout(_("Tools"));
		heeksCAD->AddFlyoutButton(_T("drill"), ToolImage(_T("drill")), _("Drill..."), NewDrillMenuCallback);
		heeksCAD->AddFlyoutButton(_T("centredrill"), ToolImage(_T("centredrill")), _("Centre Drill..."), NewCentreDrillMenuCallback);
		heeksCAD->AddFlyoutButton(_T("endmill"), ToolImage(_T("endmill")), _("End Mill..."), NewEndmillMenuCallback);
		heeksCAD->AddFlyoutButton(_T("slotdrill"), ToolImage(_T("slotdrill")), _("Slot Drill..."), NewSlotCutterMenuCallback);
		heeksCAD->AddFlyoutButton(_T("ballmill"), ToolImage(_T("ballmill")), _("Ball End Mill..."), NewBallEndMillMenuCallback);
		heeksCAD->AddFlyoutButton(_T("chamfmill"), ToolImage(_T("chamfmill")), _("Chamfer Mill..."), NewChamferMenuCallback);
		heeksCAD->EndToolBarFlyout((wxToolBar*)(theApp.m_machiningBar));

		heeksCAD->StartToolBarFlyout(_("Post Processing"));
		heeksCAD->AddFlyoutButton(_T("PostProcess"), ToolImage(_T("postprocess")), _("Post-Process"), PostProcessMenuCallback);
		heeksCAD->AddFlyoutButton(_T("Run Python Script"), ToolImage(_T("runpython")), _("Run Python Script"), RunScriptMenuCallback);
		heeksCAD->AddFlyoutButton(_T("OpenNC"), ToolImage(_T("opennc")), _("Open NC File"), OpenNcFileMenuCallback);
		heeksCAD->AddFlyoutButton(_T("SaveNC"), ToolImage(_T("savenc")), _("Save NC File"), SaveNcFileMenuCallback);
#ifndef WIN32
		heeksCAD->AddFlyoutButton(_T("Send to Machine"), ToolImage(_T("tomachine")), _("Send to Machine"), SendToMachineMenuCallback);
#endif
		heeksCAD->AddFlyoutButton(_T("Cancel"), ToolImage(_T("cancel")), _("Cancel Python Script"), CancelMenuCallback);
#ifdef WIN32
		heeksCAD->AddFlyoutButton(_T("Simulate"), ToolImage(_T("simulate")), _("Simulate"), SimulateCallback);
#endif
		heeksCAD->EndToolBarFlyout((wxToolBar*)(theApp.m_machiningBar));

		theApp.m_machiningBar->Realize();
		heeksCAD->RegisterToolBar(theApp.m_machiningBar, _T("MachiningBar"), _("Machining tools"));
	}
}

void OnBuildTexture()
{
	wxString filepath = theApp.GetResFolder() + _T("/icons/iconimage.png");
	theApp.m_icon_texture_number = heeksCAD->LoadIconsTexture(filepath.c_str());
}

static void ImportExcellonDrillFile( const wxChar *file_path )
{
	Excellon drill;

	wxString message(_("Select how the file is to be interpreted"));
	wxString caption(_("Excellon drill file interpretation"));

	wxArrayString choices;

	choices.Add(_("Produce drill pattern as described"));
	choices.Add(_("Produce mirrored drill pattern"));

	wxString choice = ::wxGetSingleChoice( message, caption, choices );

	if (choice == choices[0])
	{
		drill.Read( Ttc(file_path), false );
	}

	if (choice == choices[1])
	{
		drill.Read( Ttc(file_path), true );
	}
}

static void UnitsChangedHandler( const double units )
{
	// The view units have changed.  See if the user wants the NC output units to change
	// as well.

	if (units != theApp.m_program->m_units)
	{
		int response;
		response = wxMessageBox( _("Would you like to change the NC code generation units too?"), _("Change Units"), wxYES_NO );
		if (response == wxYES)
		{
			theApp.m_program->m_units = units;
		}
	}
}

class SketchBox{
	public:
		CBox m_box;
		gp_Vec m_latest_shift;

		SketchBox(const CBox &box);

		SketchBox(const SketchBox &s)
		{
			m_box = s.m_box;
			m_latest_shift = s.m_latest_shift;
		}

		void UpdateBoxAndSetShift(const CBox &new_box)
		{
			// use Centre
			double old_centre[3], new_centre[3];
			m_box.Centre(old_centre);
			new_box.Centre(new_centre);
			m_latest_shift = gp_Vec(new_centre[0] - old_centre[0], new_centre[1] - old_centre[1], 0.0);
			m_box = new_box;
		}
};
SketchBox::SketchBox(const CBox &box)
{
	m_box = box;
	m_latest_shift = gp_Vec(0, 0, 0);
}

class HeeksCADObserver: public Observer
{
	public:
		std::map<int, SketchBox> m_box_map;

		void OnChanged(const std::list<HeeksObj*>* added, const std::list<HeeksObj*>* removed, const std::list<HeeksObj*>* modified)
		{
			if(added)
			{
				for(std::list<HeeksObj*>::const_iterator It = added->begin(); It != added->end(); It++)
				{
					HeeksObj* object = *It;
					if(object->GetType() == SketchType)
					{
						CBox box;
						object->GetBox(box);
						m_box_map.insert(std::make_pair(object->GetID(), SketchBox(box)));
					}
				}
			}

			if(modified)
			{
				for(std::list<HeeksObj*>::const_iterator It = modified->begin(); It != modified->end(); It++)
				{
					HeeksObj* object = *It;
					if(object->GetType() == SketchType)
					{
						CBox new_box;
						object->GetBox(new_box);
						std::map<int, SketchBox>::iterator FindIt = m_box_map.find(object->GetID());
						if(FindIt != m_box_map.end())
						{
							SketchBox &sketch_box = FindIt->second;
							sketch_box.UpdateBoxAndSetShift(new_box);
						}
					}
				}

				// check all the profile operations, so we can move the tags
				for(HeeksObj* object = theApp.m_program->Operations()->GetFirstChild(); object; object = theApp.m_program->Operations()->GetNextChild())
				{
					if(object->GetType() == ProfileType)
					{
						CProfile* profile = (CProfile*)object;
						std::map<int, SketchBox>::iterator FindIt = m_box_map.find(object->GetID());
						if (FindIt != m_box_map.end())
						{
							SketchBox &sketch_box = FindIt->second;
							for (HeeksObj* tag = profile->Tags()->GetFirstChild(); tag; tag = profile->Tags()->GetNextChild())
							{
								((CTag*)tag)->m_pos[0] += sketch_box.m_latest_shift.X();
								((CTag*)tag)->m_pos[1] += sketch_box.m_latest_shift.Y();
							}

							profile->m_profile_params.m_start[0] += sketch_box.m_latest_shift.X();
							profile->m_profile_params.m_start[1] += sketch_box.m_latest_shift.Y();
							profile->m_profile_params.m_start[2] += sketch_box.m_latest_shift.Z();

							profile->m_profile_params.m_end[0] += sketch_box.m_latest_shift.X();
							profile->m_profile_params.m_end[1] += sketch_box.m_latest_shift.Y();
							profile->m_profile_params.m_end[2] += sketch_box.m_latest_shift.Z();

							profile->m_profile_params.m_roll_on_point[0] += sketch_box.m_latest_shift.X();
							profile->m_profile_params.m_roll_on_point[1] += sketch_box.m_latest_shift.Y();
							profile->m_profile_params.m_roll_on_point[2] += sketch_box.m_latest_shift.Z();

							profile->m_profile_params.m_roll_off_point[0] += sketch_box.m_latest_shift.X();
							profile->m_profile_params.m_roll_off_point[1] += sketch_box.m_latest_shift.Y();
							profile->m_profile_params.m_roll_off_point[2] += sketch_box.m_latest_shift.Z();
						}
					}
				}

				for(std::map<int, SketchBox>::iterator It = m_box_map.begin(); It != m_box_map.end(); It++)
				{
					SketchBox &sketch_box = It->second;
					sketch_box.m_latest_shift = gp_Vec(0, 0, 0);
				}
			}
		}

		void Clear()
		{
			m_box_map.clear();
		}
}heekscad_observer;

class NewProfileOpTool:public Tool
{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("New Profile Operation");}
	void Run(){
		NewProfileOp();
	}
	wxString BitmapPath(){ return _T("opprofile");}
};

class NewPocketOpTool:public Tool
{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("New Pocket Operation");}
	void Run(){
		NewPocketOp();
	}
	wxString BitmapPath(){ return _T("pocket");}
};

class NewDrillingOpTool:public Tool
{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("New Drilling Operation");}
	void Run(){
		NewDrillingOp();
	}
	wxString BitmapPath(){ return _T("drilling");}
};

static void GetMarkedListTools(std::list<Tool*>& t_list)
{
	std::set<int> group_types;

	const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
	for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		group_types.insert(object->GetIDGroupType());
	}

	for(std::set<int>::iterator It = group_types.begin(); It != group_types.end(); It++)
	{
		switch(*It)
		{
			case SketchType:
				t_list.push_back(new NewProfileOpTool);
				t_list.push_back(new NewPocketOpTool);
				break;
			case PointType:
				t_list.push_back(new NewDrillingOpTool);
				break;
		}
	}
}

static void OnRestoreDefaults()
{
	CNCConfig config;
	config.DeleteAll();
	theApp.m_settings_restored = true;
}

void CHeeksCNCApp::OnStartUp(CHeeksCADInterface* h, const wxString& dll_path)
{
	m_dll_path = dll_path;
	heeksCAD = h;
#if !defined WXUSINGDLL
	wxInitialize();
#endif

	// to do, use os_id
	wxOperatingSystemId os_id = wxGetOsVersion();

	CNCConfig config;

	// About box, stuff
	heeksCAD->AddToAboutBox(wxString(_T("\n\n")) + _("HeeksCNC is the free machining add-on to HeeksCAD")
			+ _T("\n") + _T("          http://code.google.com/p/heekscnc/")
			+ _T("\n") + _("Written by Dan Heeks, Hirutso Enni, Perttu Ahola, David Nicholls")
			+ _T("\n") + _("With help from archivist, crotchet1, DanielFalck, fenn, Sliptonic")
			+ _T("\n\n") + _("geometry code, donated by Geoff Hawkesford, Camtek GmbH http://www.peps.de/")
			+ _T("\n") + _("pocketing code from http://code.google.com/p/libarea/ , derived from the kbool library written by Klaas Holwerda http://boolean.klaasholwerda.nl/bool.html")
			+ _T("\n") + _("Zig zag code from opencamlib http://code.google.com/p/opencamlib/")
			+ _T("\n\n") + _("This HeeksCNC software installation is restricted by the GPL license http://www.gnu.org/licenses/gpl-3.0.txt")
			+ _T("\n") + _("  which means it is free and open source, and must stay that way")
			);

	// add menus and toolbars
	wxFrame* frame = heeksCAD->GetMainFrame();
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();

	// tool bars
	heeksCAD->RegisterAddToolBars(AddToolBars);
	AddToolBars();

	// Help menu
	wxMenu *menuHelp = heeksCAD->GetHelpMenu();
	menuHelp->AppendSeparator();
	heeksCAD->AddMenuItem(menuHelp, _("Online HeeksCNC Manual"), ToolImage(_T("help")), HelpMenuCallback);

	// Milling Operations menu
	wxMenu *menuMillingOperations = new wxMenu;
	heeksCAD->AddMenuItem(menuMillingOperations, _("Profile Operation..."), ToolImage(_T("opprofile")), NewProfileOpMenuCallback);
	heeksCAD->AddMenuItem(menuMillingOperations, _("Pocket Operation..."), ToolImage(_T("pocket")), NewPocketOpMenuCallback);
	heeksCAD->AddMenuItem(menuMillingOperations, _("Drilling Operation..."), ToolImage(_T("drilling")), NewDrillingOpMenuCallback);

	// Additive Operations menu
	wxMenu *menuOperations = new wxMenu;
	heeksCAD->AddMenuItem(menuOperations, _("Script Operation..."), ToolImage(_T("scriptop")), NewScriptOpMenuCallback);
	heeksCAD->AddMenuItem(menuOperations, _("Pattern..."), ToolImage(_T("pattern")), NewPatternMenuCallback);
	heeksCAD->AddMenuItem(menuOperations, _("Surface..."), ToolImage(_T("surface")), NewSurfaceMenuCallback);
	heeksCAD->AddMenuItem(menuOperations, _("Stock..."), ToolImage(_T("stock")), NewStockMenuCallback);
	AddXmlScriptOpMenuItems(menuOperations);

	// Tools menu
	wxMenu *menuTools = new wxMenu;
	heeksCAD->AddMenuItem(menuTools, _("Drill..."), ToolImage(_T("drill")), NewDrillMenuCallback);
	heeksCAD->AddMenuItem(menuTools, _("Centre Drill..."), ToolImage(_T("centredrill")), NewCentreDrillMenuCallback);
	heeksCAD->AddMenuItem(menuTools, _("End Mill..."), ToolImage(_T("endmill")), NewEndmillMenuCallback);
	heeksCAD->AddMenuItem(menuTools, _("Slot Drill..."), ToolImage(_T("slotdrill")), NewSlotCutterMenuCallback);
	heeksCAD->AddMenuItem(menuTools, _("Ball End Mill..."), ToolImage(_T("ballmill")), NewBallEndMillMenuCallback);
	heeksCAD->AddMenuItem(menuTools, _("Chamfer Mill..."), ToolImage(_T("chamfmill")), NewChamferMenuCallback);

	// Machining menu
	wxMenu *menuMachining = new wxMenu;
	heeksCAD->AddMenuItem(menuMachining, _("Add New Milling Operation"), ToolImage(_T("ops")), NULL, NULL, menuMillingOperations);
	heeksCAD->AddMenuItem(menuMachining, _("Add Other Operation"), ToolImage(_T("ops")), NULL, NULL, menuOperations);
	heeksCAD->AddMenuItem(menuMachining, _("Add New Tool"), ToolImage(_T("tools")), NULL, NULL, menuTools);
	heeksCAD->AddMenuItem(menuMachining, _("Run Python Script"), ToolImage(_T("runpython")), RunScriptMenuCallback);
	heeksCAD->AddMenuItem(menuMachining, _("Post-Process"), ToolImage(_T("postprocess")), PostProcessMenuCallback);
#ifdef WIN32
	heeksCAD->AddMenuItem(menuMachining, _("Simulate"), ToolImage(_T("simulate")), SimulateCallback);
#endif
	heeksCAD->AddMenuItem(menuMachining, _("Open NC File..."), ToolImage(_T("opennc")), OpenNcFileMenuCallback);
	heeksCAD->AddMenuItem(menuMachining, _("Save NC File as..."), ToolImage(_T("savenc")), SaveNcFileMenuCallback);
#ifndef WIN32
	heeksCAD->AddMenuItem(menuMachining, _("Send to Machine"), ToolImage(_T("tomachine")), SendToMachineMenuCallback);
#endif
	frame->GetMenuBar()->Insert( frame->GetMenuBar()->GetMenuCount()-1, menuMachining,  _("&Machining"));

	// add the program canvas
	m_program_canvas = new CProgramCanvas(frame);
	aui_manager->AddPane(m_program_canvas, wxAuiPaneInfo().Name(_("Program")).Caption(_("Program")).Bottom().BestSize(wxSize(600, 200)));

	// add the output canvas
	m_output_canvas = new COutputCanvas(frame);
	aui_manager->AddPane(m_output_canvas, wxAuiPaneInfo().Name(_("Output")).Caption(_("Output")).Bottom().BestSize(wxSize(600, 200)));

	// add the print canvas
	m_print_canvas = new CPrintCanvas(frame);
	aui_manager->AddPane(m_print_canvas, wxAuiPaneInfo().Name(_("Print")).Caption(_("Print")).Bottom().BestSize(wxSize(600, 200)));

	bool program_visible;
	bool output_visible;
	bool print_visible;

	config.Read(_T("ProgramVisible"), &program_visible);
	config.Read(_T("OutputVisible"), &output_visible);
	config.Read(_T("PrintVisible"), &print_visible);

	// read other settings
	CNCCode::ReadColorsFromConfig();
	CProfile::ReadFromConfig();
	CPocket::ReadFromConfig();
	CSpeedOp::ReadFromConfig();
	CSendToMachine::ReadFromConfig();
	config.Read(_T("UseClipperNotBoolean"), &m_use_Clipper_not_Boolean, false);
	config.Read(_T("UseDOSNotUnix"), &m_use_DOS_not_Unix, false);
	aui_manager->GetPane(m_program_canvas).Show(program_visible);
	aui_manager->GetPane(m_output_canvas).Show(output_visible);
	aui_manager->GetPane(m_print_canvas).Show(print_visible);

	// add tick boxes for them all on the view menu
	wxMenu* window_menu = heeksCAD->GetWindowMenu();
	window_menu->AppendSeparator();
	heeksCAD->AddMenuItem(window_menu, _("Program"), wxBitmap(), OnProgramCanvas, OnUpdateProgramCanvas, NULL, true);
	heeksCAD->AddMenuItem(window_menu, _("Output"), wxBitmap(), OnOutputCanvas, OnUpdateOutputCanvas, NULL, true);
	heeksCAD->AddMenuItem(window_menu, _("Print"), wxBitmap(), OnPrintCanvas, OnUpdatePrintCanvas, NULL, true);
	window_menu->AppendSeparator();
	heeksCAD->AddMenuItem(window_menu, _("Machining Tool Bar"), wxBitmap(), OnMachiningBar, OnUpdateMachiningBar, NULL, true);
	heeksCAD->RegisterHideableWindow(m_program_canvas);
	heeksCAD->RegisterHideableWindow(m_output_canvas);
	heeksCAD->RegisterHideableWindow(m_print_canvas);
	heeksCAD->RegisterHideableWindow(m_machiningBar);

	// add object reading functions
	heeksCAD->RegisterReadXMLfunction("Program", CProgram::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("nccode", CNCCode::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Operations", COperations::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Tools", CTools::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Profile", CProfile::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Pocket", CPocket::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Drilling", CDrilling::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Tool", CTool::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("CuttingTool", CTool::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Tags", CTags::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Tag", CTag::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("ScriptOp", CScriptOp::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Pattern", CPattern::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Patterns", CPatterns::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Surface", CSurface::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Surfaces", CSurfaces::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Stock", CStock::ReadFromXMLElement);
	heeksCAD->RegisterReadXMLfunction("Stocks", CStocks::ReadFromXMLElement);

	// icons
	heeksCAD->RegisterOnBuildTexture(OnBuildTexture);

	// Import functions.
	{
		std::list<wxString> file_extensions;
		file_extensions.push_back(_T("cnc"));
		file_extensions.push_back(_T("drl"));
		file_extensions.push_back(_T("drill"));
		if (! heeksCAD->RegisterFileOpenHandler( file_extensions, ImportExcellonDrillFile ))
		{
			printf("Failed to register handler for Excellon dril files\n");
		}
	}
	{
		std::list<wxString> file_extensions;
		file_extensions.push_back(_T("tool"));
		file_extensions.push_back(_T("tools"));
		file_extensions.push_back(_T("tooltable"));
		if (! heeksCAD->RegisterFileOpenHandler( file_extensions, ImportToolsFile ))
		{
			printf("Failed to register handler for Tool Table files\n");
		}
	}

	heeksCAD->RegisterObserver(&heekscad_observer);

	heeksCAD->RegisterUnitsChangeHandler( UnitsChangedHandler );
	heeksCAD->RegisterHeeksTypesConverter( HeeksCNCType );

	heeksCAD->RegisterMarkeListTools(&GetMarkedListTools);
	heeksCAD->RegisterOnRestoreDefaults(&OnRestoreDefaults);
}

std::list<wxString> CHeeksCNCApp::GetFileNames( const char *p_szRoot ) const
#ifdef WIN32
{
	std::list<wxString>	results;

	WIN32_FIND_DATA file_data;
	HANDLE hFind;

	std::string pattern = std::string(p_szRoot) + "\\*";
	hFind = FindFirstFile(Ctt(pattern.c_str()), &file_data);

	// Now recurse down until we find document files within 'current' directories.
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			if ((file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) continue;

			results.push_back( file_data.cFileName );
		} while (FindNextFile( hFind, &file_data));

		FindClose(hFind);
	} // End if - then

	return(results);
} // End of GetFileNames() method.
#else
{
	// We're in UNIX land now.

	std::list<wxString>	results;

	DIR *pdir = opendir(p_szRoot);	// Look in the current directory for files
	// whose names begin with "default."
	if (pdir != NULL)
	{
		struct dirent *pent = NULL;
		while ((pent=readdir(pdir)))
		{
			results.push_back(Ctt(pent->d_name));
		} // End while
		closedir(pdir);
	} // End if - then

	return(results);
} // End of GetFileNames() method
#endif

void CHeeksCNCApp::OnNewOrOpen(bool open, int res)
{
	// check for existance of a program

	bool program_found = false;
	for(HeeksObj* object = heeksCAD->GetFirstObject(); object; object = heeksCAD->GetNextObject())
	{
		if(object->GetType() == ProgramType)
		{
			program_found = true;
			break;
		}
	}

	if(!program_found)
	{
		// add the program
		m_program = new CProgram;

		m_program->AddMissingChildren();
		heeksCAD->GetMainObject()->Add(m_program, NULL);
		theApp.m_program_canvas->Clear();
		theApp.m_output_canvas->Clear();
		theApp.m_print_canvas->Clear();

		heeksCAD->OpenXMLFile(GetResourceFilename(wxT("default.tooltable")), theApp.m_program->Tools());
	} // End if - then
}

void on_set_use_clipper(bool value, HeeksObj* object)
{
	theApp.m_use_Clipper_not_Boolean = value;
}

void on_set_use_DOS(bool value, HeeksObj* object)
{
	theApp.m_use_DOS_not_Unix = value;
}

void CHeeksCNCApp::GetOptions(std::list<Property *> *list){
	PropertyList* machining_options = new PropertyList(_("machining options"));
	CNCCode::GetOptions(&(machining_options->m_list));
	CSpeedOp::GetOptions(&(machining_options->m_list));
	CProfile::GetOptions(&(machining_options->m_list));
	CPocket::GetOptions(&(machining_options->m_list));
	CSendToMachine::GetOptions(&(machining_options->m_list));
	machining_options->m_list.push_back ( new PropertyCheck ( _("Use Clipper not Boolean"), m_use_Clipper_not_Boolean, NULL, on_set_use_clipper ) );
	machining_options->m_list.push_back ( new PropertyCheck ( _("Use DOS Line Endings"), m_use_DOS_not_Unix, NULL, on_set_use_DOS ) );

	list->push_back(machining_options);

	PropertyList* excellon_options = new PropertyList(_("Excellon options"));
	Excellon::GetOptions(&(excellon_options->m_list));
	list->push_back(excellon_options);
}

void CHeeksCNCApp::OnFrameDelete()
{
	wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
	CNCConfig config;
	config.Write(_T("ProgramVisible"), aui_manager->GetPane(m_program_canvas).IsShown());
	config.Write(_T("OutputVisible"), aui_manager->GetPane(m_output_canvas).IsShown());
	config.Write(_T("PrintVisible"), aui_manager->GetPane(m_print_canvas).IsShown());
	config.Write(_T("MachiningBarVisible"), aui_manager->GetPane(m_machiningBar).IsShown());

	CNCCode::WriteColorsToConfig();
	CProfile::WriteToConfig();
	CPocket::WriteToConfig();
	CSpeedOp::WriteToConfig();
	CSendToMachine::WriteToConfig();
	config.Write(_T("UseClipperNotBoolean"), m_use_Clipper_not_Boolean);
	config.Write(_T("UseDOSNotUnix"), m_use_DOS_not_Unix);
}

Python CHeeksCNCApp::SetTool( const int new_tool )
{
	Python python;

	// Select the right tool.
	CTool *pTool = (CTool *) CTool::Find(new_tool);
	if (pTool != NULL)
	{
		if (m_tool_number != new_tool)
		{

			python << _T("tool_change( id=") << new_tool << _T(")\n");
		}

		if(m_attached_to_surface)
		{
			python << _T("nc.creator.set_ocl_cutter(") << pTool->OCLDefinition(m_attached_to_surface) << _T(")\n");
		}
	} // End if - then

	m_tool_number = new_tool;

	return(python);
}

wxString CHeeksCNCApp::GetDllFolder() const
{
	return m_dll_path;
}

wxString CHeeksCNCApp::GetResFolder() const
{
#if defined(WIN32) || defined(RUNINPLACE) //compile with 'RUNINPLACE=yes make' then skip 'sudo make install'
	#ifdef CMAKE_UNIX
		return (m_dll_path + _T("/.."));
	#else
		return m_dll_path;
	#endif
#else
	#ifdef CMAKE_UNIX
		// Unix
		#if wxCHECK_VERSION(3, 0, 0)
			wxStandardPaths& sp = wxStandardPaths::Get();
		#else
			wxStandardPaths sp;
		#endif
		return (sp.GetInstallPrefix() + wxT("/share/heekscnc"));
	#else // CMAKE_UNIX
		// Windows
		return (m_dll_path + _T("/../../share/heekscnc"));
	#endif // CMAKE_UNIX
#endif // defined(WIN32) || defined(RUNINPLACE)
}

wxString CHeeksCNCApp::GetResourceFilename(const wxString resource, const bool writableOnly) const
{
	wxString filename;

#ifdef WIN32
	// Windows
	filename = GetDllFolder() + wxT("/") + resource;
#else
	// Unix
	// Under Unix, it looks for a user-defined resource first.
	// According to FreeDesktop XDG standards, HeeksCNC user-defineable resources should be placed in XDG_CONFIG_HOME (usually: ~/.config/heekscnc/)
	filename = (wxGetenv(wxT("XDG_CONFIG_HOME")) ? wxString(wxGetenv(wxT("XDG_CONFIG_HOME"))) : wxFileName::GetHomeDir() + wxT("/.config"));
	filename += wxT("/heekscnc/") + resource;

	// Under Unix user can't save its resources in system (permissions denied), so we always return a user-writable file
	if(!writableOnly)
	{
		// If user-defined file exists, the resource is located
		if(!wxFileName::FileExists(filename))
		{
			// Else it fallbacks to system-wide resource file (installed with HeeksCNC)
			filename = GetResFolder() + wxT("/") + resource;
			// Note: it should be a good idea to use wxStandardPaths::GetResourcesDir() but it returns HeeksCAD's resource dir (eg. /usr/share/heekscad)
		}
	}
	else
	{
		// Writable file is wanted, so ressource directories should exists (ie. mkdir -p ~/.config/heekscnc)
		wxFileName fn(filename);
		wxFileName::Mkdir(fn.GetPath(), 0700, wxPATH_MKDIR_FULL);
	}

#endif
	wprintf(wxT("Resource: ") + resource + wxT(" found at: ") + filename + wxT("\n"));
	return filename;
}

class MyApp : public wxApp
{
	public:

		virtual bool OnInit(void);
};

bool MyApp::OnInit(void)
{
	return true;
}

DECLARE_APP(MyApp)
IMPLEMENT_APP(MyApp)

wxString HeeksCNCType( const int type )
{
	switch (type)
	{
		case ProgramType:       return(_("Program"));
		case NCCodeBlockType:       return(_("NCCodeBlock"));
		case NCCodeType:       return(_("NCCode"));
		case OperationsType:       return(_("Operations"));
		case ProfileType:       return(_("Profile"));
		case PocketType:       return(_("Pocket"));
		case DrillingType:       return(_("Drilling"));
		case ToolType:       return(_("Tool"));
		case ToolsType:       return(_("Tools"));
		case TagsType:       return(_("Tags"));
		case TagType:       return(_("Tag"));
		case ScriptOpType:       return(_("ScriptOp"));

		default:
								 return(_T("")); // Indicates that this function could not make the conversion.
	} // End switch
} // End HeeksCNCType() routine


text:
package com.dialogdata.spring.security.intro.data.entities;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "User")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "FIRSTNAME")
    private String firstName;

    @Column(name = "LASTNAME")
    private String lastName;

    @Column(name = "USERNAME")
    private String userName;

    private String password;

    private Boolean isActive;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Boolean isActive() {
        return isActive;
    }

    public void setIsActive(Boolean isActive) {
        this.isActive = isActive;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("User{");
        sb.append("id=").append(id);
        sb.append(", firstName='").append(firstName).append('\'');
        sb.append(", lastName='").append(lastName).append('\'');
        sb.append(", userName='").append(userName).append('\'');
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != null ? !id.equals(user.id) : user.id != null) return false;
        if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
        if (lastName != null ? !lastName.equals(user.lastName) : user.lastName != null) return false;
        if (userName != null ? !userName.equals(user.userName) : user.userName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        result = 31 * result + (userName != null ? userName.hashCode() : 0);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from datetime import datetime
from timeit import default_timer as timer

import numpy as np
import pandas as pd

from great_expectations.dataset.pandas_dataset import PandasDataset

np.random.seed(42)

N_ROWS = 1_000_000
COL_NAME = "x"
N = 10

INT_MIN = 0.0
INT_MAX = 10_000

FLOAT_MIN = 0.0
FLOAT_MAX = 10_000.0

DT_MIN = datetime(2020, 1, 1)
DT_MAX = datetime(2021, 1, 1)

dataset_int = PandasDataset(
    {COL_NAME: pd.Series(np.random.randint(low=INT_MIN, high=INT_MAX, size=N_ROWS))}
)
dataset_float = PandasDataset(
    {COL_NAME: pd.Series(np.random.uniform(low=FLOAT_MIN, high=FLOAT_MAX, size=N_ROWS))}
)

dataset_dt = PandasDataset(
    {
        COL_NAME: tuple(
            datetime.fromtimestamp(val).isoformat()
            for val in np.random.randint(
                low=DT_MIN.timestamp(), high=DT_MAX.timestamp(), size=N_ROWS // 100
            )
        )
    }
)

benchmark_int = lambda: dataset_int.expect_column_values_to_be_between(
    column=COL_NAME, min_value=INT_MIN, max_value=INT_MAX
)
benchmark_float = lambda: dataset_float.expect_column_values_to_be_between(
    column=COL_NAME, min_value=FLOAT_MIN, max_value=FLOAT_MAX
)
benchmark_dt = lambda: dataset_dt.expect_column_values_to_be_between(
    column=COL_NAME,
    min_value=DT_MIN.isoformat(),
    max_value=DT_MAX.isoformat(),
    parse_strings_as_datetimes=True,
)

def _time(func):
    start = timer()
    func()
    return timer() - start

def time_multiple(func, n):
    return tuple(_time(func) for _ in range(n))

if __name__ == "__main__":
    measurements_int = time_multiple(benchmark_int, N)
    measurements_float = time_multiple(benchmark_float, N)
    measurements_dt = time_multiple(benchmark_dt, N)
    results = pd.DataFrame(
        {
            "int": measurements_int,
            "float": measurements_float,
            "datetime": measurements_dt,
        }
    )
    print(results)
    results.to_csv("benchmark.csv", index=False)


text:
use glib_sys::{gboolean, gpointer};
use gobject_sys::{self, GCallback};
use libc::{c_char, c_ulong, c_void};
use object::ObjectType;
use std::mem;
use std::num::NonZeroU64;
use translate::{from_glib, FromGlib, ToGlib, ToGlibPtr};

/// The id of a signal that is returned by `connect`.
#[derive(Debug, Eq, PartialEq)]
pub struct SignalHandlerId(NonZeroU64);

impl ToGlib for SignalHandlerId {
    type GlibType = c_ulong;

    #[inline]
    fn to_glib(&self) -> c_ulong {
        self.0.get() as c_ulong
    }
}

impl FromGlib<c_ulong> for SignalHandlerId {
    #[inline]
    fn from_glib(val: c_ulong) -> SignalHandlerId {
        assert_ne!(val, 0);
        SignalHandlerId(unsafe { NonZeroU64::new_unchecked(val as u64) })
    }
}

/// Whether to propagate the signal to the default handler.
///
/// Don't inhibit default handlers without a reason, they're usually helpful.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Inhibit(pub bool);

#[doc(hidden)]
impl ToGlib for Inhibit {
    type GlibType = gboolean;

    #[inline]
    fn to_glib(&self) -> gboolean {
        self.0.to_glib()
    }
}

#[allow(clippy::missing_safety_doc)]
pub unsafe fn connect_raw<F>(
    receiver: *mut gobject_sys::GObject,
    signal_name: *const c_char,
    trampoline: GCallback,
    closure: *mut F,
) -> SignalHandlerId {
    unsafe extern "C" fn destroy_closure<F>(ptr: *mut c_void, _: *mut gobject_sys::GClosure) {
        // destroy
        Box::<F>::from_raw(ptr as *mut _);
    }
    assert_eq!(mem::size_of::<*mut F>(), mem::size_of::<gpointer>());
    assert!(trampoline.is_some());
    let handle = gobject_sys::g_signal_connect_data(
        receiver,
        signal_name,
        trampoline,
        closure as *mut _,
        Some(destroy_closure::<F>),
        0,
    );
    assert!(handle > 0);
    from_glib(handle)
}

pub fn signal_handler_block<T: ObjectType>(instance: &T, handler_id: &SignalHandlerId) {
    unsafe {
        gobject_sys::g_signal_handler_block(
            instance.as_object_ref().to_glib_none().0,
            handler_id.to_glib(),
        );
    }
}

pub fn signal_handler_unblock<T: ObjectType>(instance: &T, handler_id: &SignalHandlerId) {
    unsafe {
        gobject_sys::g_signal_handler_unblock(
            instance.as_object_ref().to_glib_none().0,
            handler_id.to_glib(),
        );
    }
}

#[allow(clippy::needless_pass_by_value)]
pub fn signal_handler_disconnect<T: ObjectType>(instance: &T, handler_id: SignalHandlerId) {
    unsafe {
        gobject_sys::g_signal_handler_disconnect(
            instance.as_object_ref().to_glib_none().0,
            handler_id.to_glib(),
        );
    }
}

pub fn signal_stop_emission_by_name<T: ObjectType>(instance: &T, signal_name: &str) {
    unsafe {
        gobject_sys::g_signal_stop_emission_by_name(
            instance.as_object_ref().to_glib_none().0,
            signal_name.to_glib_none().0,
        );
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: yumparse.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: yumparse.js

/**
 * @module yumparse
 * @author Risto Stevcev
 */
var mustache = require('mustache');

/**
 * Creates a yumparse Parser
 * @class
 * @param {Object} args - Arguments to pass into the parser
 * @param {String} [args.template] - The template that should be used for help/usage
 * @param {Object[]} args.options - The options that should be parsed
 * @param {String} args.options.shortFlag - The short flag for that option
 * @param {String} [args.options.longFlag] - The long flag for that option
 * @param {*} [args.options.type=String] - The type for that option
 * @param {Boolean} [args.options.required=false] - Set it to make it a required option
 * @param {String} args.options.description - The description of the option
 * @param {*} [args.options.defaultValue] - The default value for the option
 */
exports.Parser = function(args) {
  'use strict';

  /**
   * Creates a YumparseError
   * @class
   * @param {String} message - The error message
   */
  function YumparseError(message) {
    this.name = 'YumparseError';
    this.message = message || '';

    if (args && args.debug === true) {
      var error = new Error(message);
      error.name = this.name;
      this.stack = error.stack;
    }
  }
  YumparseError.prototype = Object.create(Error.prototype);

  /**
   * Underline text (xterm color)
   * @type {String}
   * @private
   */
  var _U = '\u001b[4m';

  /**
   * Bold text (xterm color)
   * @type {String}
   * @private
   */
  var _B = '\u001b[1m';

  /**
   * Normal text (xterm color, ends bold text)
   * @type {String}
   * @private
   */
  var B_ = '\u001b[21m';

  /**
   * Normal text (xterm color, ends underlined text)
   * @type {String}
   * @private
   */
  var U_ = '\u001b[24m';

  /**
   * The default template
   * @type {String}
   * @instance
   */
  this.template = '' +
    '{{#program.description}}' +
    _B+'{{{program.name}}}'+B_ + ' - {{{program.description}}}\n' +
    '{{/program.description}}' +
    '\n\n' +

    _U+'Usage'+U_+'\n' +
    '  {{{program.name}}} [options]\n\n' +

    _U+'Options'+U_+'\n' +
    '{{#optionsList}}' +
    '  {{{flagBlock}}}    {{{description}}}\n' +
    '{{/optionsList}}' +

    '{{#example}}' +
    '\n\n' +
    _U+'Example'+U_+'\n' +
    '  {{{example}}}\n' +
    '{{/example}}';

  if (!args || !args.options) {
    throw new YumparseError('At least one flag needs to be given to the Parser');
  }

  if (args.program) {
    this.program = args.program;
  }
  else {
    this.program = { name: process.argv[1] };
  }

  if (args.example) {
    this.example = args.example;
  }

  if (args.template) {
    this.template = args.template;
  }

  if (!(args.options instanceof Array)) {
    throw new YumparseError('Options must be passed in as an array');
  }

  /**
   * The original options list that was passed in
   * @type {Array}
   * @instance
   */
  this.optionsList = args.options;

  /**
   * The list of options that have a required set to true
   * @type {Array}
   * @instance
   */
  this.requiredList = [];

  /**
   * The longest flag length
   * @type {Number}
   */
  var longestFlag = this.optionsList.reduce(function(previous, current) {
    return current.longFlag && current.longFlag.length > previous ?
           current.longFlag.length : previous;
  }, 0);

  /**
   * A mustache js helper function that returns a flag block
   * @returns {String} A flag block string
   * @this module:yumparse.Parser~parseOptions
   */
  this.flagBlock = function() {
    return (this.longFlag ?
            (new Array(longestFlag - this.longFlag.length + 1)).join(' ') +
            this.longFlag + ', ' :
            (new Array(longestFlag + 1)).join(' ') + '  ') +

           this.shortFlag;
  };

  /**
   * Available flag options
   * @readonly
   * @enum {Array}
   */
  this.flagTypeOptions = [Boolean, Number, String, Array, Object];

  /**
   * Convert a flag (spinal case) to a variable name (camel case)
   * @param {String} flag - The flag to convert
   * @returns {String} The variable name
   */
  this.flagToName = function(flag) {
    if (flag.match(/^--[-a-z]*$/)) {
      flag = flag.replace(/^--/, '');
      var idx = flag.search(/-[a-z]/);
      for (idx; idx > -1; idx = flag.search(/-[a-z]/)) {
        flag = flag.slice(0, idx) +
               flag[idx + 1].toUpperCase() +
               flag.slice(idx + 2, flag.length);
      }
      return flag;
    }
    else if (flag.match(/^-[a-z]$/)) {
      return flag[1];
    }
  };

  /**
   * Convert a variable name (camel case) to a flag (spinal case)
   * @param {String} name - The name to convert
   * @returns {String} The flag
   */
  this.nameToFlag = function(name) {
    if (name.length === 1 && name.match(/[a-z]/)) {
      return '-' + name;
    }
    else if (name.length > 1 && name.match(/[A-Za-z]/)) {
      var idx = name.search(/[A-Z]/);
      for (idx; idx > -1; idx = name.search(/[A-Z]/)) {
        name = name.slice(0, idx) +
               '-' + name[idx].toLowerCase() +
               name.slice(idx + 1, name.length);
      }
      return '--' + name;
    }
  };

  /**
   * Returns an object with parsed (String flag, JSON option) pairs
   * @type {Object}
   */
  this.parsedOptions = {};

  /**
   * Parse options
   * @param {Object} options - The options to parse
   * @return {Object} The parsed options
   */
  var parseOptions = function(options) {
    var flags = {};
    options.forEach(function(option) {
      if (!option.shortFlag || !option.type || !option.description) {
        throw new YumparseError('Parser object requires a flag that has at least ' +
                        'shortFlag, type, and description attributes set');
      }

      if (!this.flagTypeOptions.some(function(type) {
                                       return type === option.type;
                                     })) {
        throw new YumparseError('The type given is not one of the valid types: ' +
                        this.flagTypeOptions.map(function(type) {
                          return type.name;
                        }).join(', '));
      }

      if (!option.shortFlag.match(/^-[a-z]/)) {
        throw new YumparseError('Short flag "' + option.shortFlag +
                        '" must match the format: -[a-z]');
      }
      option.shortFlagName = this.flagToName(option.shortFlag);
      flags[option.shortFlagName] = option;

      if (option.longFlag) {
        if (!option.longFlag.match(/^--[-a-z]/)) {
          throw new YumparseError('Long flag "' + option.longFlag +
                          '" must match the format --[-a-z]*');
        }
        option.longFlagName = this.flagToName(option.longFlag);
        flags[option.longFlagName] = option;
      }

      if (option.required) {
        this.requiredList.push(option);
      }

      if (option.defaultValue) {
        option.value = option.defaultValue;
        this.parsedOptions[option.shortFlagName] = option;

        if (option.longFlagName) {
          this.parsedOptions[option.longFlagName] = option;
        }
      }
    }, this);
    return flags;
  };

  /**
   * An object with (String flagName, JSON option) pairs
   * @type {Object}
   */
  this.options = parseOptions.call(this, args.options);

  this.options.help = this.options.h = {
    shortFlag: '-h',
    longFlag: '--help',
    type: Boolean,
    description: 'Help message'
  };

  /**
   * Contains the list of rules to be checked after parsing
   * @type {Array}
   */
  this.rules = [];

  /**
   * Adds a rule to check as part of the parsing
   * @param {Object} rule - The rule object
   * @param {Function} [rule.message] - A function that returns an error message if the rule fails
   * @param {Function} rule.check - The rule-check function to run. Returns true on success and false on failure.
   */
  this.addRule = function(rule) {
    this.rules.push(function() {
      if (!rule.check.call(this)) {
        throw new YumparseError(rule.message ? rule.message.call(this) : 'Invalid options');
      }
    });
  };

  /**
   * Help string
   * @returns {String} The help string
   */
  this.helpString = function() {
    return mustache.render(this.template, this);
  };

  /** Display help and exit the program */
  this.displayHelp = function() {
    console.log(this.helpString());
    process.exit();
  };

  /**
   * @description Parses the process.argv arguments and runs the checks for the rules
   * @returns Sets this.parsedOptions to the parsed options after all rules pass
   */
  this.parse = function() {
    /**
     * Adds a parsed option (see: {@link module:yumparse.Parser#parse})
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    var addParsedOption = function(flag, flagValue) {
      this.parsedOptions[flag] = this.options[flag];

      (function setParsedOptionsValue() {
        if (flagValue === undefined && this.options[flag].defaultValue) {
          this.parsedOptions[flag].value = this.options[flag].defaultValue;
        }
        else {
          this.parsedOptions[flag].value = flagValue;
        }
      }).call(this);
    };

    /**
     * Collects the flags and thier values from process.argv and adds them to parsedOptions (see {@link module:yumparse.Parser#parse})
     * @name collectFlags
     * @function
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    (function collectFlags() {
      var flag, flagValue;
      var args = process.argv.slice(2);
      args.forEach(function(arg) {
        var isFlag = arg.match(/^-[a-z]$/) || arg.match(/^--[-a-z]*$/);
        if (isFlag) {
          var flagName = this.flagToName(arg);
          if (!this.options[flagName]) {
            throw new YumparseError(arg + ' is not a valid option');
          }

          if (flag) {
            addParsedOption.call(this, flag, flagValue);
          }

          flag = flagName;
          flagValue = undefined;
        }
        else {
          if (flagValue && !(flagValue instanceof Array)) {
            flagValue = [flagValue];
          }
          if (flagValue && flagValue instanceof Array) {
            flagValue.push(arg);
          }
          else {
            flagValue = arg;
          }
        }
      }, this);

      if (flag) {
        addParsedOption.call(this, flag, flagValue);
      }
    }).call(this);

    /**
     * Check if required flags are passed (see {@link module:yumparse.Parser#parse})
     * @name checkRequiredFlags
     * @function
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    (function checkRequiredFlags() {
      var notParsed = [];
      var requiredIsParsed = true;

      this.requiredList.forEach(function(requiredFlag) {
        var isParsed = this.parsedOptions[requiredFlag.shortFlagName] !== undefined ||
                       this.parsedOptions[requiredFlag.longFlagName] !== undefined;

        if (!isParsed) {
          notParsed.push(requiredFlag.shortFlag +
                         (requiredFlag.longFlag ? ' | ' + requiredFlag.longFlag : ''));
        }

        requiredIsParsed = requiredIsParsed && isParsed;
      }, this);

      if (!requiredIsParsed) {
        throw new YumparseError('Required flags ' + JSON.stringify(notParsed) +
                                ' were not given');
      }
    }).call(this);

    /**
     * Typecheck the parsed options
     * @name typeCheck
     * @function
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    (function typeCheck() {
      Object.keys(this.parsedOptions).forEach(function(flag) {
        var option = this.parsedOptions[flag];

        switch (option.type) {
          case Boolean:
            if (option.value === undefined) {
              option.value = true;
            }
            else if (typeof JSON.parse(option.value) === 'boolean') {
              option.value = JSON.parse(option.value);
            }
            else {
              throw new YumparseError(option.value + ' is not a boolean value');
            }
            break;
          case Number:
            if (!isNaN(option.value)) {
              option.value = parseInt(option.value);
            }
            else {
              throw new YumparseError(option.value + ' is not a number');
            }
            break;
          case Array:
            if (!option.value) {
              throw new YumparseError('A value was not given for flag "' + option.shortFlag + '"');
            }
            if (!(option.value instanceof Array) && (typeof option.value === 'string')) {
                option.value = [option.value];
            }
            break;
          case String:
            if (typeof option.value !== 'string') {
              throw new YumparseError(JSON.stringify(option.value) + ' is not a string');
            }
            break;
          case Object:
            if (!option.value) {
              throw new YumparseError('A value was not given for flag "' + option.shortFlag + '"');
            }
            if (typeof option.value !== 'string') {
              throw new YumparseError('JSON needs to be passed as a string');
            }

            try {
              option.value = JSON.parse(option.value);
            }
            catch (e) {
              throw new YumparseError('Not a JSON object');
            }
            break;
          default:
            throw new YumparseError('Type ' + option.type + ' is not a valid type');
        }
      }, this);
    }).call(this);

    /**
     * Display parsed help
     * @name displayParsedHelp
     * @function
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    (function displayParsedHelp() {
      if (this.parsedOptions.h || this.parsedOptions.help) {
        this.displayHelp();
      }
    }).call(this);

    /**
     * Check rules
     * @name checkRules
     * @function
     * @inner
     * @private
     * @memberof module:yumparse.Parser
     * @this module:yumparse.Parser
     */
    (function checkRules() {
      this.rules.forEach(function(rule) {
        rule.call(this);
      }, this);
    }).call(this);
  };
};

/** Helper functions for rules */
exports.helpers = require('./helpers.js');

/** Rule factory functions for generating rules */
exports.rules = require('./rules.js');

Index

Modules

helpers

rules

yumparse

Classes

Parser

YumparseError

    Documentation generated by JSDoc 3.2.2 on Mon Dec 29 2014 23:32:09 GMT-0800 (PST)


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.core.compositeeditor;

import docking.ActionContext;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataTypeComponent;

/**
 * Action for use in the composite data type editor.
 * This action has help associated with it.
 */
public class ShowComponentPathAction extends CompositeEditorTableAction {

	public final static String ACTION_NAME = "Show Component Path";
	private final static String GROUP_NAME = BASIC_ACTION_GROUP;
	private final static String DESCRIPTION =
		"Show the category for the selected component's data type";
	private static String[] POPUP_PATH = new String[] { ACTION_NAME };
	private static String[] MENU_PATH = new String[] { ACTION_NAME };

	public ShowComponentPathAction(CompositeEditorProvider provider) {
		super(provider, EDIT_ACTION_PREFIX + ACTION_NAME, GROUP_NAME, POPUP_PATH, MENU_PATH, null);
		setDescription(DESCRIPTION);
		adjustEnablement();
	}

	@Override
	public void actionPerformed(ActionContext context) {
		String message = " ";
		int index = model.getMinIndexSelected();
		DataTypeComponent dtc = model.getComponent(index);
		if (dtc != null) {
			DataType dt = dtc.getDataType();
			message =
				dt.getDisplayName() + " is in category \"" + dt.getCategoryPath().getPath() + "\".";

		}
		model.setStatus(message, false);
		requestTableFocus();
	}

	@Override
	public void adjustEnablement() {
		setEnabled(model.isSingleComponentRowSelection());
	}
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/ThemeColor</item>
        <item name="colorPrimaryDark">@color/ThemeColorDark</item>
        <item name="colorAccent">@color/Accent</item>
        <item name="colorControlNormal">@color/HintColor</item>
        <item name="colorControlActivated">@color/Accent</item>
        <item name="colorControlHighlight">@color/Accent</item>
    </style>

    <style name="Login_Field_Content"  parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:textSize">15sp</item>
        <item name="android:singleLine">true</item>
    </style>

    <style name="Card_Field_Content"  parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:textSize">15sp</item>
        <item name="android:inputType">number</item>
        <item name="android:singleLine">true</item>
    </style>

    <style name="Login_Error_Message" parent="@android:style/TextAppearance.Medium">
        <item name="android:text">@string/error_message</item>
        <item name="android:textColor">@color/ErrorMessageColor</item>
        <item name="android:gravity">end</item>
        <item name="android:visibility">gone</item>
        <item name="android:textSize">12sp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">match_parent</item>
    </style>

    <style name="Error_Message" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">@color/HintColor</item>
        <item name="android:gravity">end</item>
        <item name="android:visibility">visible</item>
        <item name="android:textSize">12sp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">match_parent</item>
    </style>

    <style name="Login_Icon"  parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_weight">1</item>
        <item name="android:padding">@dimen/icon_padding</item>
        <item name="android:tint">@color/ThemeColor</item>
    </style>

    <style name="Icon"  parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_weight">.3</item>
        <item name="android:tint">@color/ThemeColor</item>
        <item name="android:padding">@dimen/icon_padding</item>
    </style>

    <style name="Button_Style" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_margin">10dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">@dimen/field_content_size</item>
        <item name="android:elevation">@dimen/elevation</item>
        <item name="android:layout_marginTop">@dimen/activity_horizontal_margin</item>
        <item name="android:textColor">@color/White</item>
    </style>

    <style name="Slogan_Icon" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:padding">@dimen/icon_padding</item>
    </style>

    <style name="Receipt_Field_Layout" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginStart">20dp</item>
        <item name="android:layout_marginLeft">20dp</item>
        <item name="android:layout_marginRight">10dp</item>
        <item name="android:layout_marginEnd">10dp</item>
        <item name="android:layout_marginBottom">10dp</item>
        <item name="android:orientation">horizontal</item>
    </style>

    <style name="Line" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">2dp</item>
        <item name="android:layout_marginStart">10dp</item>
        <item name="android:layout_marginLeft">10dp</item>
        <item name="android:layout_marginRight">10dp</item>
        <item name="android:layout_marginEnd">10dp</item>
        <item name="android:layout_marginBottom">10dp</item>
        <item name="android:background">@color/HistoryLineColor</item>
    </style>

</resources>


text:
# node-text-teaser

This is a wrapper for the [TextTeaser API](http://www.textteaser.com/)

## Installation

```
npm install text-teaser
```

### `#post()`

Send request to the API

```js
var key = process.env.TEXTTEASER_KEY
var subdomain = process.env.TEXTTEASER_DOMAIN || ''
var tt = require('text-teaser')(key, subdomain)

var data = {
  title: 'TITLE...............',
  text: 'TEXT...................'
}

tt.post(data, function(err, id){
  if (err) { /* handle err */ }
  console.log(id)
})
```

### `#get()`

Get the summarized content from the API

```js
var key = process.env.TEXTTEASER_KEY
var subdomain = process.env.TEXTTEASER_DOMAIN || ''
var tt = require('text-teaser')(key, subdomain)
var id = 123 // for example

tt.get(id, { count: 3 }, function(err, data){
  if (err) { /* handle err */ }
  console.log(data)
})
```

## Testing

```
TEXTTEASER_KEY=YOUR_KEY npm test
```

## LICENSE

MIT License


text:
package manager

import (
	"encoding/json"
	"log"
	"net/http"
	"runtime"
	"time"

	"github.com/garyburd/redigo/redis"

	"strings"

	"github.com/barracudanetworks/GoWorker/config"
	"github.com/barracudanetworks/GoWorker/job"
	"github.com/barracudanetworks/GoWorker/provider"
	"github.com/barracudanetworks/GoWorker/worker"
)

const (
	MANAGER_PREFIX          = "manager:"
	CONNECTION_REFRESH_RATE = 360
	DEFAULT_MAX_WORKERS     = 20
)

// Manager is used to manage worker processes
type Manager struct {
	// WorkerFactories a map of WorkerFactories that can create workers of a spesific type
	// WorkerFactories map[string]worker.WorkerFactory
	// // ProviderFactories a map of ProviderFactory taht can create providers fo a spesific type
	// ProviderFactories map[string]provider.ProviderFactory
	// KillChan if recieved on this channel, kill all workers
	KillChan chan struct{}
	// Stats keeps track of statistics of jobs running through the manager
	Stats *ManagerStats
	// Providers a map of provider.Provider's that can be used to request work
	Providers map[string]provider.Provider
	// AllWorkers, whether available or not
	allWorkers map[uint64]worker.Worker
	// readyWorkers a map to buffered channels of workers of various types
	readyWorkers map[string]chan worker.Worker
	// jobChan channel the manager uses to receive work
	jobChan chan job.Job
	// currentWorkers current number of workers per type
	currentWorkers map[string]int
	// redisConn is a connection to the redis server used for discovory
	redisConn redis.Conn
	// currentConfig holds the most recent app config
	currentConfig *config.AppConfig
	// statsServer
	statsServer *http.ServeMux
	// FailureHandler is a worker that handles failed jobs which have reached their retry limit
	failureHandlers []chan worker.Worker
	// handleFailures if this is set, the manager will look for a failure handler worker for failed jobs
	handleFailures bool
	numWorkers     *Counter
}

// Manage create and manage workers
func (m *Manager) Manage() {

	go func() {
		for {
			time.Sleep(10 * time.Second)
			runtime.GC()
		}
	}()
	// start the web server
	for n, p := range m.Providers {
		go func(n string, p provider.Provider) {
			// request ten jobs so we can see how long they take
			log.Printf("Requesting %d jobs from %s for load analysis", 10, n)
			m.RequestWork(p, 10)
			time.Sleep(5 * time.Second)
			for {
				count := m.numJobsToRequest(p, p.WaitTime(0))
				log.Printf("Requesting %d jobs from %s", count, n)
				m.RequestWork(p, count)
				time.Sleep(p.WaitTime(0))
			}
		}(n, p)
	}

	for {
		select {
		case <-m.KillChan:
			m.killAll()
			return
		case job := <-m.jobChan:
			m.runJob(job)
		}
	}
}

// numJobsToRequest calculate the number of jobs to request
func (m *Manager) numJobsToRequest(p provider.Provider, d time.Duration) int {

	// count = target jobs per second * time we have to do those jobs
	count := p.Target() * d.Seconds()

	// if we can't handle the target load, hard limit on our maximum
	if m.capasityByProvider(p) < p.Target() {
		count = m.capasityByProvider(p)
	}

	return int(count)
}

// capasityByProvider get the number of jobs we can handle from a provider.
// the result is given in jobs per second
func (m *Manager) capasityByProvider(p provider.Provider) float64 {

	// get the average duration it takes for work from this provider to complete
	avgDuration := m.Stats.AverageDurationByProvider(p).Seconds()

	// the capsity is defined by number of workers we have * jobs we can do per second per worker
	return float64(len(m.allWorkers)) * (time.Second.Seconds() / avgDuration)
}

// requestWork takes a map of providers, and request work from each of them
func (m *Manager) RequestWork(p provider.Provider, numJobs int) {
	p.RequestWork(numJobs, m.jobChan)
}

// runJob takes a job, finds the best suited worker, and runs the job and waits for the results, after which performs cleanup tasks
func (m *Manager) runJob(j job.Job) {
	config := j.Config()
	workerChan, ok := m.readyWorkers[config.Type]
	if !ok {
		log.Println("Unknown job type", config.Type)
		return
	}

	// attempt to get an existing worker, if non is available, and the worker limit has not been reached, create a new one
	worker := <-workerChan
	go func() {
		stats := worker.Work(j)

		// recycle worker and send it back on the worker chan
		worker.Recycle()
		workerChan <- worker

		// Log outcome of job
		log.Printf("%s completed with status %d and %d retries. Job took %s to complete", config.Name, stats.Status(), stats.Retries(), stats.Duration())

		// if their was a failure, set the job as a retry
		if stats.Status() != job.STATUS_SUCCESS {
			m.handleFailure(j, stats)
		} else {
			// if the job succeded confirm and consume stats normally
			if err := j.JobConfirmer().ConfirmJob(j); err != nil {
				log.Println(err)
			}
			m.Stats.consumeStats(j, stats)
		}
	}()
}

// HandleFailure given a job that has failed to complete, asses it's status and handle accordingly
func (m *Manager) handleFailure(j job.Job, s *job.JobStats) {

	config := j.Config()
	// if the job was not successful decrement it's retries
	config.Retries = config.Retries - 1

	// if it is out of retires and the manager has a way to handle the error, send it to the failure handler
	if config.Retries <= 0 {
		s.End(job.STATUS_FAILURE)
		m.Stats.consumeStats(j, s)
		if m.handleFailures {
			for i := range m.failureHandlers {
				worker := <-m.failureHandlers[i]
				log.Println("sending failed job to failure handler")
				stats := worker.Work(j)
				log.Printf("FAILURE_HANDLER::%s completed with status %d and %d retries. Job took %s to complete", config.Name, stats.Status(), stats.Retries(), stats.Duration())
				m.failureHandlers[i] <- worker
			}

		} else {
			log.Printf("job %+v failed with no failure handler provided\n", j)
		}
	} else {
		// set the job stats to a retry
		s.End(job.STATUS_RETRY)
		m.Stats.consumeStats(j, s)
		// if the job still has retries left, send it back to the manager to try again
		m.jobChan <- j
	}
	if err := j.JobConfirmer().ConfirmJob(j); err != nil {
		log.Println(err)
	}
}

// killAll kill all available workers, and set them to nil
func (m *Manager) killAll() error {
	var err error
	for _, worker := range m.allWorkers {
		worker.Kill()
		if err != nil {
			return err
		}
	}
	return nil
}

// applyConfig apply a new configuration to the manager
func (m *Manager) applyConfig(conf *config.AppConfig) {
	m.populateProviders(conf.ProviderConfigs)
	m.populateWorkers(conf.WorkerConfigs)
	m.populateFailureHandlers(conf.FailureHanldlerConfigs)
}

// populateProviders initilizes all providers supplied by the AppConfig
func (m *Manager) populateProviders(confs []config.ConfigPair) {
	for i := range confs {
		c := confs[i]
		p, err := provider.Create(c.Type, c.Config)
		if err != nil {
			log.Println(err)
			continue
		}
		m.Providers[c.Type] = p
	}
}

// populateWorkers creates a cache of workers for every type we have and puts it on the channel for that type
func (m *Manager) populateWorkers(confs []config.ConfigPair) {
	for i := range confs {
		c := confs[i]
		count := struct {
			NumWorkers int `json:"workers"`
		}{
			DEFAULT_MAX_WORKERS,
		}
		jErr := json.Unmarshal(c.Config, &count)
		if jErr != nil {
			count.NumWorkers = DEFAULT_MAX_WORKERS
		}

		// populate the workers
		m.readyWorkers[string(c.Type)] = make(chan worker.Worker, count.NumWorkers)
		for i := 0; i < count.NumWorkers; i++ {
			w, err := worker.Create(string(c.Type), c.Config)
			if err != nil {
				log.Println(err)
				break
			}
			m.readyWorkers[string(c.Type)] <- w
			m.allWorkers[m.numWorkers.Val()] = w
			m.numWorkers.Inc()
		}
		log.Println("created", count.NumWorkers, c.Type, "workers")
	}
}

// populateFialureHandler creates a worker to handle failed jobs which have reached their retry limit
func (m *Manager) populateFailureHandlers(confs []config.ConfigPair) {
	m.failureHandlers = make([]chan worker.Worker, 0)

	// for every config, add another error handler
	for i := range confs {
		c := confs[i]
		w, err := worker.Create(string(c.Type), c.Config)
		if err != nil {
			log.Println(err)
			log.Println("Unable to initilize failure handler")
		}

		m.failureHandlers = append(m.failureHandlers, make(chan worker.Worker, 1))
		m.failureHandlers[len(m.failureHandlers)-1] <- w
		m.handleFailures = true
		log.Println("created", c.Type, "worker as a failure handler")
	}
}

// ConfigStruct returns the struct used to configure the manager
func (m *Manager) ConfigStruct() interface{} {
	return config.DefaultAppConfig()
}

// Init initilize the manager
func (m *Manager) Init(i interface{}) error {
	conf, ok := i.(*config.AppConfig)
	if !ok {
		return config.WRONG_CONFIG_TYPE
	}
	m.numWorkers = &Counter{}
	m.currentConfig = conf
	m.jobChan = make(chan job.Job, 10)

	m.Stats = NewManagerStats(m)

	m.applyConfig(conf)

	// register handler
	m.statsServer.HandleFunc("/manager/stats", m.Stats.ReportStats)

	// set up all of the web servers
	go func() {
		log.Fatal(http.ListenAndServe(conf.StatsPort, m.statsServer))
	}()
	return nil
}

// NewManager create and return a referance to a manager
func NewManager() *Manager {
	m := &Manager{}
	m.KillChan = make(chan struct{})
	m.Providers = make(map[string]provider.Provider)
	m.allWorkers = make(map[uint64]worker.Worker)
	m.readyWorkers = make(map[string]chan worker.Worker)
	m.currentWorkers = make(map[string]int)
	m.statsServer = http.NewServeMux()
	return m
}

// remove a prefix from ever string in a slice
func trimStrings(s []string, pre string) []string {
	for i := 0; i < len(s); i++ {
		s[i] = strings.TrimPrefix(s[i], pre)
	}
	return s
}


text:
namespace Schemin.Primitives.GeneralOperations
{
	using System;
	using Schemin.Evaluate;
	using Schemin.AST;
	using Environment = Schemin.Evaluate.Environment;

	public class Case : Primitive
	{
		public Case()
		{
			base.Rewriter = true;
		}

		public override IScheminType Execute(Environment env, Evaluator eval, ScheminPair args)
		{
			IScheminType key = args.Car;
			ScheminPair checks = args.ListCdr();

			foreach (IScheminType type in checks)
			{
				ScheminPair pairCase = (ScheminPair) type;
				IScheminType group = pairCase.Car;
				IScheminType result = pairCase.ListCdr().Car;

				if ((group as ScheminAtom) != null)
				{
					ScheminAtom atomClause = (ScheminAtom) group;
					if (atomClause.Name == "else")
					{
						return result;
					}
					else
					{
						throw new Exception("atom besides 'else' found in case statement");
					}
				}

				ScheminPair pairGroup = (ScheminPair) group;
				foreach (IScheminType checkType in pairGroup)
				{
					if (key.Equivalent(checkType))
						return result;
				}
			}

			return new ScheminPair();
		}
	}
}


text:
ttms-auction-2017-B
====================

#### Summary
The website catalog for the Three Tree Montessori School's 2017 Auction.

Based on the Landing Page layout by PureCSS.io (http://purecss.io/).

#### Check it out at:
### http://kgentner.github.io/ttms-auction-2017-B


text:
<?php

namespace Oro\Bundle\ImportExportBundle\File;

use Symfony\Component\Filesystem\Filesystem;

/**
 * @deprecated since 2.1. Please use FileManager class for working with files instead as it supports gaufrette.
 */
class FileSystemOperator
{
    /**
     * @var string
     */
    protected $cacheDirectory;

    /**
     * @var string
     */
    protected $temporaryDirectoryName;

    /**
     * @var string
     */
    protected $temporaryDirectory;

    /**
     * @param string $cacheDirectory
     * @param string $temporaryDirectoryName
     */
    public function __construct($cacheDirectory, $temporaryDirectoryName)
    {
        $this->cacheDirectory = $cacheDirectory;
        $this->temporaryDirectoryName = $temporaryDirectoryName;
    }

    /**
     * @param bool $readOnly
     * @return string
     * @throws \LogicException
     */
    public function getTemporaryDirectory($readOnly = false)
    {
        if (!$this->temporaryDirectory) {
            $cacheDirectory = rtrim($this->cacheDirectory, DIRECTORY_SEPARATOR);
            $temporaryDirectory = $cacheDirectory . DIRECTORY_SEPARATOR . $this->temporaryDirectoryName;
            if (!file_exists($temporaryDirectory) && !is_dir($temporaryDirectory)) {
                $fs = new Filesystem();
                $fs->mkdir($temporaryDirectory, 0755);
                $fs->chmod($temporaryDirectory, 0755);
            }

            if (!is_readable($temporaryDirectory)) {
                throw new \LogicException('Import/export directory is not readable');
            }
            if (!$readOnly && !is_writable($temporaryDirectory)) {
                throw new \LogicException('Import/export directory is not writeable');
            }

            $this->temporaryDirectory = $temporaryDirectory;
        }

        return $this->temporaryDirectory;
    }

    /**
     * @param $fileName
     * @param bool $readOnly
     * @return \SplFileObject
     * @throws \LogicException
     */
    public function getTemporaryFile($fileName, $readOnly = false)
    {
        $temporaryDirectory = $this->getTemporaryDirectory($readOnly);
        $fullFileName = $temporaryDirectory . DIRECTORY_SEPARATOR . $fileName;
        if (!file_exists($fullFileName) || !is_file($fullFileName) || !is_readable($fullFileName)) {
            throw new \LogicException(sprintf('Can\'t read file %s', $fileName));
        }

        return new \SplFileObject($fullFileName);
    }

    /**
     * @param string $prefix
     * @param string $extension
     * @return string
     */
    public function generateTemporaryFileName($prefix, $extension = 'tmp')
    {
        $temporaryDirectory = $this->getTemporaryDirectory();

        $filePrefix = sprintf('%s_%s', $prefix, date('Y_m_d_H_i_s'));
        do {
            $fileName = sprintf(
                '%s%s%s.%s',
                $temporaryDirectory,
                DIRECTORY_SEPARATOR,
                preg_replace('~\W~', '_', uniqid($filePrefix . '_')),
                $extension
            );
        } while (file_exists($fileName));

        return $fileName;
    }
}


text:
package org.keysupport.bc.scvp.asn1;

import org.bouncycastle.asn1.ASN1EncodableVector;

public class UserPolicySet extends SeqOfASN1Object {

	public UserPolicySet(ASN1EncodableVector oids) {
		super(oids);
	}

	public UserPolicySet() {
		super();
	}

}


text:
Bits of Haskell code from excercises in various Haskell courses/books, or just trying things out.

Code is sorted by book:

| Directory | Textbook                                                                |
| --------- | ----------------------------------------------------------------------- |
| cis194    | [CIS 194: Introduction to Haskell](https://www.seas.upenn.edu/~cis194/) |
| realworld | [Real World Haskell](http://book.realworldhaskell.org/)                 |
| wikibook  | [Haskell (on Wikibooks)](https://en.wikibooks.org/wiki/Haskell)         |

Source files in the project root are random experiments.


text:
using System;

namespace FluidDbClient.Sandbox.Models
{
    public class Widget
    {
        public Widget(int widgetId, Guid globalId, string name, string description)
        {
            WidgetId = widgetId;
            GlobalId = globalId;
            Name = name;
            Description = description;
        }

        public int WidgetId { get; }
        public Guid GlobalId { get; }
        public string Name { get; }
        public string Description { get; }
    }
}


text:
<?php

/**
 * General utility class in Swift Mailer, not to be instantiated.
 *
 * @package Swift
 *
 * @author Chris Corbyn
 */
abstract class Swift
{
    public static $initialized = false;
    public static $inits = array();

    /** Swift Mailer Version number generated during dist release process */
    const VERSION = '5.0.3';

    /**
     * Registers an initializer callable that will be called the first time
     * a SwiftMailer class is autoloaded.
     *
     * This enables you to tweak the default configuration in a lazy way.
     *
     * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class
     */
    public static function init($callable)
    {
        self::$inits[] = $callable;
    }

    /**
     * Internal autoloader for spl_autoload_register().
     *
     * @param string $class
     */
    public static function autoload($class)
    {
        // Don't interfere with other autoloaders
        if (0 !== strpos($class, 'Swift_')) {
            return;
        }

        $path = dirname(__FILE__).'/'.str_replace('_', '/', $class).'.php';

        if (!file_exists($path)) {
            return;
        }

        require $path;

        if (self::$inits && !self::$initialized) {
            self::$initialized = true;
            foreach (self::$inits as $init) {
                call_user_func($init);
            }
        }
    }

    /**
     * Configure autoloading using Swift Mailer.
     *
     * This is designed to play nicely with other autoloaders.
     *
     * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class
     */
    public static function registerAutoload($callable = null)
    {
        if (null !== $callable) {
            self::$inits[] = $callable;
        }
        spl_autoload_register(array('Swift', 'autoload'));
    }
}


text:
import hold from './hold'
import mockSignal from '../internal/mockSignal'

let s, t
let next, error, complete
let emit

describe('hold', () => {
  beforeEach(() => {
    s = mockSignal()
    t = mockSignal()

    next = jest.fn()
    error = jest.fn()
    complete = jest.fn()

    emit = { next, error, complete }
  })

  it('stops emitting values from the target signal while the control signal is truthy', () => {
    hold(s, t)(emit)

    expect(next).not.toHaveBeenCalled()
    s.next(false)
    t.next('foo')
    expect(next).toHaveBeenCalledTimes(1)
    expect(next).toHaveBeenLastCalledWith('foo')
    s.next(true)
    t.next('bar')
    expect(next).toHaveBeenCalledTimes(1)
    expect(next).toHaveBeenLastCalledWith('foo')
  })

  it('emits an error when either signal emits an error', () => {
    hold(s, t)(emit)

    expect(error).not.toHaveBeenCalled()
    s.error('foo')
    expect(error).toHaveBeenCalledTimes(1)
    expect(error).toHaveBeenLastCalledWith('foo')
    t.error('bar')
    expect(error).toHaveBeenCalledTimes(2)
    expect(error).toHaveBeenLastCalledWith('bar')
  })

  it('completes when the target signal is completed', () => {
    hold(s, t)(emit)

    expect(complete).not.toHaveBeenCalled()
    t.complete()
    expect(complete).toHaveBeenCalledTimes(1)
  })

  it('completes when the control signal is completed', () => {
    hold(s, t)(emit)

    expect(complete).not.toHaveBeenCalled()
    s.complete()
    expect(complete).toHaveBeenCalledTimes(1)
  })

  it('unmounts the control signal when the unsubscribe function is called', () => {
    const unsubscribe = hold(s, t)(emit)

    expect(s.unmount).not.toHaveBeenCalled()
    unsubscribe()
    expect(s.unmount).toHaveBeenCalledTimes(1)
  })

  it('unmounts the target signal when the unsubscribe function is called', () => {
    const unsubscribe = hold(s, t)(emit)

    expect(t.unmount).not.toHaveBeenCalled()
    unsubscribe()
    expect(t.unmount).toHaveBeenCalledTimes(1)
  })
})


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>SimpleApp Resource</comment>
<entry key="title">SimpleApp サンプル#6</entry>
<entry key="dirChooser.title">フォルダの選択</entry>

<entry key="directory">ディレクトリ(_D)</entry>
<entry key="browse">参照(_B)</entry>
<entry key="namePattern">ファイル名パターン(_P)</entry>
<entry key="includeSubDirs">サブディレクトリを含む(_S)</entry>

<entry key="file">ファイル(_F)</entry>
<entry key="close">閉じる(_X)</entry>
<entry key="command">コマンド(_C)</entry>
<entry key="help">ヘルプ(_H)</entry>

<entry key="ok">実行</entry>
<entry key="cancel">キャンセル</entry>

<entry key="closeConfirmAlertTitle">確認</entry>
<entry key="closeConfirmAlertHeaderText">アプリケーションを終了してもよろしいですか?</entry>
</properties>