<commit_before>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#ifdef VC6
# pragma warning (disable : 4786)
#endif

#include <iostream>
#include <sstream>
#include <string>

#include "partsummary.h"
#include "rational.h"
#include "xml_tree_browser.h"
#include "xml2guidovisitor.h"
#include "xmlpart2guido.h"
#include "tree_browser.h"

using namespace std;

namespace MusicXML2
{

//______________________________________________________________________________
xml2guidovisitor::xml2guidovisitor(bool generateComments, bool generateStem, bool generateBar) :
	fGenerateComments(generateComments), fGenerateStem(generateStem),
	fGenerateBars(generateBar), fGeneratePositions(true),
	fCurrentStaffIndex(0), previousStaffHasLyrics(false), fCurrentAccoladeIndex(0)
{}

//______________________________________________________________________________
Sguidoelement xml2guidovisitor::convert (const Sxmlelement& xml)
{
	Sguidoelement gmn;
	if (xml) {
		tree_browser<xmlelement> browser(this);
		browser.browse(*xml);
		gmn = current();
	}
	return gmn;
}

//______________________________________________________________________________
// the score header contains information like title, author etc..
// it must be written only once, at the beginning of the first guido voice
// thus the function clears the data when flushed so that further calls do nothing
//______________________________________________________________________________
void xml2guidovisitor::flushHeader ( scoreHeader& header )
{
	if (header.fTitle) {
		Sguidoelement tag = guidotag::create("title");
		string title = header.fTitle->getValue();
		int pos = title.find ('"');
		while (pos != string::npos) {
			title = title.replace (pos, 1, "'");
			pos = title.find ('"', pos);
		}
		tag->add (guidoparam::create(title));
		add (tag);
		header.fTitle = 0;
	}
	vector<S_creator>::const_iterator i;
	for (i=header.fCreators.begin(); i!=header.fCreators.end(); i++) {
		string type = (*i)->getAttributeValue("type");
		if ((type == "Composer") || (type == "composer")) {
			Sguidoelement tag = guidotag::create("composer");
			tag->add (guidoparam::create((*i)->getValue()));
			tag->add (guidoparam::create("dy=4hs", false));
			add (tag);
		}
	}
	header.fCreators.clear();
}

//______________________________________________________________________________
// the part header contains information like part name
// it must be written only once, at the beginning of the corresponding guido voice
// thus the function clears the data when flushed so that further calls do nothing
//______________________________________________________________________________
void xml2guidovisitor::flushPartHeader ( partHeader& header )
{
	if (header.fPartName && header.fPartName->getValue().size()) {
		Sguidoelement tag = guidotag::create("instr");
		stringstream s1, s2;
		string instr = header.fPartName->getValue();
		int offset = instr.size() * 2;

		s1 << "dx=-" << offset << "hs";
		tag->add (guidoparam::create(instr));
		tag->add (guidoparam::create(s1.str(), false));
		tag->add (guidoparam::create("dy=-5hs", false));
		add (tag);

		tag = guidotag::create("systemFormat");
		tag->add (guidoparam::create(""));
		s2 << "dx=" << offset << "hs";
		tag->add (guidoparam::create(s2.str(), false));
		add (tag);
		header.fPartName = 0;
	}
}

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_score_partwise& elt )
{
    Sguidoelement chord = guidochord ::create();
    start(chord);
}

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_movement_title& elt )		{ fHeader.fTitle = elt; }
void xml2guidovisitor::visitStart ( S_creator& elt )			{ fHeader.fCreators.push_back(elt); }
void xml2guidovisitor::visitStart ( S_score_part& elt )			{ fCurrentPartID = elt->getAttributeValue("id"); }
void xml2guidovisitor::visitStart ( S_part_name& elt )			{ fPartHeaders[fCurrentPartID].fPartName = elt; }

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_part& elt )
{
	partsummary ps;
	xml_tree_browser browser(&ps);
	browser.browse(*elt);

	smartlist<int>::ptr voices = ps.getVoices ();
	int targetStaff = 0xffff;	// initialized to a value we'll unlikely encounter
	bool notesOnly = false;
	rational currentTimeSign (0,1);

	// browse the parts voice by voice: allows to describe voices that spans over several staves
	for (unsigned int i = 0; i < voices->size(); i++) {
        int targetVoice = (*voices)[i];
		int mainstaff = ps.getMainStaff(targetVoice);
		if (targetStaff == mainstaff) {
			notesOnly = true;
		}
		else {
			notesOnly = false;
			targetStaff = mainstaff;
			fCurrentStaffIndex++;
		}

        //cout<<"Generating PART with voice "<<targetVoice<<" staff "<<targetStaff<<" coveringStaffs: "<<ps.countStaves()<< " notesOnly="<<(int)(notesOnly) <<endl;

		Sguidoelement seq = guidoseq::create();
		push (seq);

		Sguidoelement tag = guidotag::create("staff");
		tag->add (guidoparam::create(fCurrentStaffIndex, false));
		add (tag);

        //// Add staffFormat if needed
        // Case1: If previous staff has Lyrics, then move current staff lower to create space: \staffFormat<dy=-5>
        if (previousStaffHasLyrics)
        {
            Sguidoelement tag2 = guidotag::create("staffFormat");
            tag2->add (guidoparam::create("dy=-5", false));
            add (tag2);
        }
        //// Add Accolade if countStaves on this Part is >1, and we are entering span
        if ((ps.countStaves()>1)&&(fCurrentStaffIndex>fCurrentAccoladeIndex))
        {
            std::string accolParams = "id="+std::to_string(fCurrentAccoladeIndex)+", range=\"";
            int rangeEnd = fCurrentStaffIndex + ps.countStaves() - 1;

            accolParams += std::to_string(fCurrentStaffIndex)+"-"+std::to_string(rangeEnd)+"\"";

            Sguidoelement tag3 = guidotag::create("accol");
            tag3->add (guidoparam::create(accolParams, false));
            add (tag3);
            fCurrentAccoladeIndex = rangeEnd;
        }
        ////

		flushHeader (fHeader);
		flushPartHeader (fPartHeaders[elt->getAttributeValue("id")]);

		xmlpart2guido pv(fGenerateComments, fGenerateStem, fGenerateBars);
		pv.generatePositions (fGeneratePositions);
		xml_tree_browser browser(&pv);
		pv.initialize(seq, targetStaff, fCurrentStaffIndex, targetVoice, notesOnly, currentTimeSign);
		browser.browse(*elt);
		pop();
		currentTimeSign = pv.getTimeSign();
        previousStaffHasLyrics = pv.hasLyrics();
	}
}

//______________________________________________________________________________
void xml2guidovisitor::addPosition	( Sxmlelement elt, Sguidoelement& tag, int yoffset)
{
	float posx = elt->getAttributeFloatValue("default-x", 0) + elt->getAttributeFloatValue("relative-x", 0);
	if (posx) {
		posx = (posx / 10) * 2;   // convert to half spaces
		stringstream s;
		s << "dx=" << posx << "hs";
		tag->add (guidoparam::create(s.str(), false));
	}
	float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
	if (posy) {
		posy = (posy / 10) * 2;   // convert to half spaces
		posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
		stringstream s;
		s << "dy=" << posy << "hs";
		tag->add (guidoparam::create(s.str(), false));
	}
}

    //______________________________________________________________________________
    void xml2guidovisitor::addPosition	( Sxmlelement elt, Sguidoelement& tag, int yoffset, int xoffset)
    {
        float posx = elt->getAttributeFloatValue("default-x", 0) + elt->getAttributeFloatValue("relative-x", 0);
        if (posx) {
            posx = (posx / 10) * 2;   // convert to half spaces
            posx += xoffset;
            stringstream s;
            s << "dx=" << posx << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
        float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
        if (posy) {
            posy = (posy / 10) * 2;   // convert to half spaces
            posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
            stringstream s;
            s << "dy=" << posy << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

    //______________________________________________________________________________
    void xml2guidovisitor::addPosY	( Sxmlelement elt, Sguidoelement& tag, int yoffset)
    {
        float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
        if (posy) {
            posy = (posy / 10) * 2;   // convert to half spaces
            posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
            stringstream s;
            s << "dy=" << posy << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

    void xml2guidovisitor::addPlacement	( Sxmlelement elt, Sguidoelement& tag)
    {
        string placement = elt->getAttributeValue("placement");

        if (placement.size()) {

            stringstream s;
            s << "position=\"" << placement << "\"";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

}

<commit_msg>xml2guido: fix minor generation ordering<commit_after>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#ifdef VC6
# pragma warning (disable : 4786)
#endif

#include <iostream>
#include <sstream>
#include <string>

#include "partsummary.h"
#include "rational.h"
#include "xml_tree_browser.h"
#include "xml2guidovisitor.h"
#include "xmlpart2guido.h"
#include "tree_browser.h"

using namespace std;

namespace MusicXML2
{

//______________________________________________________________________________
xml2guidovisitor::xml2guidovisitor(bool generateComments, bool generateStem, bool generateBar) :
	fGenerateComments(generateComments), fGenerateStem(generateStem),
	fGenerateBars(generateBar), fGeneratePositions(true),
	fCurrentStaffIndex(0), previousStaffHasLyrics(false), fCurrentAccoladeIndex(0)
{}

//______________________________________________________________________________
Sguidoelement xml2guidovisitor::convert (const Sxmlelement& xml)
{
	Sguidoelement gmn;
	if (xml) {
		tree_browser<xmlelement> browser(this);
		browser.browse(*xml);
		gmn = current();
	}
	return gmn;
}

//______________________________________________________________________________
// the score header contains information like title, author etc..
// it must be written only once, at the beginning of the first guido voice
// thus the function clears the data when flushed so that further calls do nothing
//______________________________________________________________________________
void xml2guidovisitor::flushHeader ( scoreHeader& header )
{
	if (header.fTitle) {
		Sguidoelement tag = guidotag::create("title");
		string title = header.fTitle->getValue();
		int pos = title.find ('"');
		while (pos != string::npos) {
			title = title.replace (pos, 1, "'");
			pos = title.find ('"', pos);
		}
		tag->add (guidoparam::create(title));
		add (tag);
		header.fTitle = 0;
	}
	vector<S_creator>::const_iterator i;
	for (i=header.fCreators.begin(); i!=header.fCreators.end(); i++) {
		string type = (*i)->getAttributeValue("type");
		if ((type == "Composer") || (type == "composer")) {
			Sguidoelement tag = guidotag::create("composer");
			tag->add (guidoparam::create((*i)->getValue()));
			tag->add (guidoparam::create("dy=4hs", false));
			add (tag);
		}
	}
	header.fCreators.clear();
}

//______________________________________________________________________________
// the part header contains information like part name
// it must be written only once, at the beginning of the corresponding guido voice
// thus the function clears the data when flushed so that further calls do nothing
//______________________________________________________________________________
void xml2guidovisitor::flushPartHeader ( partHeader& header )
{
	if (header.fPartName && header.fPartName->getValue().size()) {
		Sguidoelement tag = guidotag::create("instr");
		stringstream s1, s2;
		string instr = header.fPartName->getValue();
		int offset = instr.size() * 2;

		s1 << "dx=-" << offset << "hs";
		tag->add (guidoparam::create(instr));
		tag->add (guidoparam::create(s1.str(), false));
		tag->add (guidoparam::create("dy=-5hs", false));
		add (tag);

		tag = guidotag::create("systemFormat");
		tag->add (guidoparam::create(""));
		s2 << "dx=" << offset << "hs";
		tag->add (guidoparam::create(s2.str(), false));
		add (tag);
		header.fPartName = 0;
	}
}

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_score_partwise& elt )
{
    Sguidoelement chord = guidochord ::create();
    start(chord);
}

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_movement_title& elt )		{ fHeader.fTitle = elt; }
void xml2guidovisitor::visitStart ( S_creator& elt )			{ fHeader.fCreators.push_back(elt); }
void xml2guidovisitor::visitStart ( S_score_part& elt )			{ fCurrentPartID = elt->getAttributeValue("id"); }
void xml2guidovisitor::visitStart ( S_part_name& elt )			{ fPartHeaders[fCurrentPartID].fPartName = elt; }

//______________________________________________________________________________
void xml2guidovisitor::visitStart ( S_part& elt )
{
	partsummary ps;
	xml_tree_browser browser(&ps);
	browser.browse(*elt);

	smartlist<int>::ptr voices = ps.getVoices ();
	int targetStaff = 0xffff;	// initialized to a value we'll unlikely encounter
	bool notesOnly = false;
	rational currentTimeSign (0,1);

	// browse the parts voice by voice: allows to describe voices that spans over several staves
	for (unsigned int i = 0; i < voices->size(); i++) {
        int targetVoice = (*voices)[i];
		int mainstaff = ps.getMainStaff(targetVoice);
		if (targetStaff == mainstaff) {
			notesOnly = true;
		}
		else {
			notesOnly = false;
			targetStaff = mainstaff;
			fCurrentStaffIndex++;
		}

        //cout<<"Generating PART with voice "<<targetVoice<<" staff "<<targetStaff<<" coveringStaffs: "<<ps.countStaves()<< " notesOnly="<<(int)(notesOnly) <<endl;

		Sguidoelement seq = guidoseq::create();
		push (seq);

		Sguidoelement tag = guidotag::create("staff");
		tag->add (guidoparam::create(fCurrentStaffIndex, false));
		add (tag);

        //// Add staffFormat if needed
        // Case1: If previous staff has Lyrics, then move current staff lower to create space: \staffFormat<dy=-5>
        if (previousStaffHasLyrics)
        {
            Sguidoelement tag2 = guidotag::create("staffFormat");
            tag2->add (guidoparam::create("dy=-5", false));
            add (tag2);
        }
        ////

		flushHeader (fHeader);
		flushPartHeader (fPartHeaders[elt->getAttributeValue("id")]);

        //// Add Accolade if countStaves on this Part is >1, and we are entering span
        if ((ps.countStaves()>1)&&(fCurrentStaffIndex>fCurrentAccoladeIndex))
        {
            std::string accolParams = "id="+std::to_string(fCurrentAccoladeIndex)+", range=\"";
            int rangeEnd = fCurrentStaffIndex + ps.countStaves() - 1;

            accolParams += std::to_string(fCurrentStaffIndex)+"-"+std::to_string(rangeEnd)+"\"";

            Sguidoelement tag3 = guidotag::create("accol");
            tag3->add (guidoparam::create(accolParams, false));
            add (tag3);
            fCurrentAccoladeIndex = rangeEnd;
        }
        ////

		xmlpart2guido pv(fGenerateComments, fGenerateStem, fGenerateBars);
		pv.generatePositions (fGeneratePositions);
		xml_tree_browser browser(&pv);
		pv.initialize(seq, targetStaff, fCurrentStaffIndex, targetVoice, notesOnly, currentTimeSign);
		browser.browse(*elt);
		pop();
		currentTimeSign = pv.getTimeSign();
        previousStaffHasLyrics = pv.hasLyrics();
	}
}

//______________________________________________________________________________
void xml2guidovisitor::addPosition	( Sxmlelement elt, Sguidoelement& tag, int yoffset)
{
	float posx = elt->getAttributeFloatValue("default-x", 0) + elt->getAttributeFloatValue("relative-x", 0);
	if (posx) {
		posx = (posx / 10) * 2;   // convert to half spaces
		stringstream s;
		s << "dx=" << posx << "hs";
		tag->add (guidoparam::create(s.str(), false));
	}
	float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
	if (posy) {
		posy = (posy / 10) * 2;   // convert to half spaces
		posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
		stringstream s;
		s << "dy=" << posy << "hs";
		tag->add (guidoparam::create(s.str(), false));
	}
}

    //______________________________________________________________________________
    void xml2guidovisitor::addPosition	( Sxmlelement elt, Sguidoelement& tag, int yoffset, int xoffset)
    {
        float posx = elt->getAttributeFloatValue("default-x", 0) + elt->getAttributeFloatValue("relative-x", 0);
        if (posx) {
            posx = (posx / 10) * 2;   // convert to half spaces
            posx += xoffset;
            stringstream s;
            s << "dx=" << posx << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
        float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
        if (posy) {
            posy = (posy / 10) * 2;   // convert to half spaces
            posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
            stringstream s;
            s << "dy=" << posy << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

    //______________________________________________________________________________
    void xml2guidovisitor::addPosY	( Sxmlelement elt, Sguidoelement& tag, int yoffset)
    {
        float posy = elt->getAttributeFloatValue("default-y", 0) + elt->getAttributeFloatValue("relative-y", 0);
        if (posy) {
            posy = (posy / 10) * 2;   // convert to half spaces
            posy += yoffset;		  // anchor point convertion (defaults to upper line in xml)
            stringstream s;
            s << "dy=" << posy << "hs";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

    void xml2guidovisitor::addPlacement	( Sxmlelement elt, Sguidoelement& tag)
    {
        string placement = elt->getAttributeValue("placement");

        if (placement.size()) {

            stringstream s;
            s << "position=\"" << placement << "\"";
            tag->add (guidoparam::create(s.str(), false));
        }
    }

}

<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdoparser_rdo.cpp
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_activity_i.h"
#include "simulator/compiler/parser/rdoparser_rdo.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdosmr.h"
#include "simulator/compiler/parser/rdorss.h"
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdofun.h"
#include "simulator/compiler/parser/rdosmr.h"
#include "simulator/compiler/parser/rdopat.h"
#include "simulator/runtime/rdo_pattern.h"
#include "utils/rdostream.h"
#include "kernel/rdokernel.h"
#include "repository/rdorepository.h"
#include "simulator/runtime/calc/calc_pattern.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOParserRDOItem
// --------------------------------------------------------------------------------
RDOParserRDOItem::RDOParserRDOItem(rdoModelObjects::RDOFileType type, t_bison_parse_fun parser_fun, t_bison_error_fun error_fun, t_flex_lexer_fun lexer_fun, StreamFrom from)
	: RDOParserItem(type, parser_fun, error_fun, lexer_fun, from)
	, m_pLexer(NULL)
{}

RDOParserRDOItem::~RDOParserRDOItem()
{
	if (m_pLexer)
	{
		delete m_pLexer;
		m_pLexer = NULL;
	}
}

void RDOParserRDOItem::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	rdo::binarystream in_stream;
	switch (m_from)
	{
		case sf_repository:
		{
			rdoRepository::RDOThreadRepository::FileData fileData(m_type, in_stream);
			kernel->sendMessage(kernel->repository(), RDOThread::RT_REPOSITORY_LOAD, &fileData);
			break;
		}
		case sf_editor:
		{
			rdoRepository::RDOThreadRepository::FileData fileData(m_type, in_stream);
			kernel->sendMessage(kernel->studio(), RDOThread::RT_STUDIO_MODEL_GET_TEXT, &fileData);
			break;
		}
	}
	if (in_stream.good())
	{
		parse(pParser, in_stream);
	}
}

void RDOParserRDOItem::parse(CREF(LPRDOParser) pParser, REF(std::istream) in_stream)
{
	ASSERT(pParser);

	if (m_pLexer)
		delete m_pLexer;

	std::ostringstream out_stream;
	m_pLexer = getLexer(pParser, &in_stream, &out_stream);

	if (m_pLexer && m_parser_fun)
		m_parser_fun(m_pLexer);
}

PTR(RDOLexer) RDOParserRDOItem::getLexer(CREF(LPRDOParser) pParser, PTR(std::istream) in_stream, PTR(std::ostream) out_stream)
{
	ASSERT(pParser);
	return new RDOLexer(pParser, in_stream, out_stream);
}

ruint RDOParserRDOItem::lexer_loc_line()
{
	if (m_pLexer)
	{
		return m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_line : m_pLexer->lineno();
	}
	else
	{
		return ruint(rdoRuntime::RDOSrcInfo::Position::UNDEFINE_LINE);
	}
}

ruint RDOParserRDOItem::lexer_loc_pos()
{
	return m_pLexer && m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_pos : 0;
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserRSS
// --------------------------------------------------------------------------------
RDOParserRSS::RDOParserRSS(StreamFrom from)
	: RDOParserRDOItem(rdoModelObjects::RSS, rssparse, rsserror, rsslex, from)
{}

void RDOParserRSS::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);
	pParser->setHaveKWResources   (false);
	pParser->setHaveKWResourcesEnd(false);
	RDOParserRDOItem::parse(pParser);
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserRSSPost
// --------------------------------------------------------------------------------
void RDOParserRSSPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!            ,        RSS
#ifdef RDOSIM_COMPATIBLE
	STL_FOR_ALL_CONST(pParser->getRTPResType(), rtp_it)
	{
#endif
		STL_FOR_ALL_CONST(pParser->getRSSResources(), rss_it)
		{
#ifdef RDOSIM_COMPATIBLE
			if ((*rss_it)->getType() == *rtp_it)
			{
#endif
				rdoRuntime::LPRDOCalc calc = (*rss_it)->createCalc();
				pParser->runtime()->addInitCalc(calc);
#ifdef RDOSIM_COMPATIBLE
			}
#endif
		}
#ifdef RDOSIM_COMPATIBLE
	}
#endif
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserSMRPost
// --------------------------------------------------------------------------------
RDOParserSMRPost::RDOParserSMRPost()
	: RDOParserItem(rdoModelObjects::SMR, NULL, NULL, NULL)
{}

void RDOParserSMRPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!  ,   SMR
	STL_FOR_ALL_CONST(pParser->getEvents(), eventIt)
	{
		LPRDOEvent pEvent = *eventIt;
		ASSERT(pEvent);

		rdoRuntime::LPRDOCalc pInitCalc = pEvent->getInitCalc();
		if (pInitCalc)
		{
			pParser->runtime()->addInitCalc(pInitCalc);
		}
	}
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserEVNPost
// --------------------------------------------------------------------------------
void RDOParserEVNPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!
	STL_FOR_ALL_CONST(pParser->getEvents(), eventIt)
	{
		LPRDOEvent pEvent = *eventIt;

		LPRDOPATPattern pPattern = pParser->findPATPattern(pEvent->name());
		if (!pPattern)
		{
			STL_FOR_ALL_CONST(pEvent->getCalcList(), calcIt)
			{
				pParser->error().push_only((*calcIt)->src_info(), rdo::format(_T("   : %s"), pEvent->name().c_str()));
			}
			pParser->error().push_done();
		}
		if (pPattern->getType() != RDOPATPattern::PT_Event)
		{
			STL_FOR_ALL_CONST(pEvent->getCalcList(), calcIt)
			{
				pParser->error().push_only((*calcIt)->src_info(), rdo::format(_T(" %s   : %s"), pEvent->name().c_str()));
			}
			pParser->error().push_done();
		}

		if (pEvent->getRegular())
		{
			LPIBaseOperation pRuntimeEvent = pPattern->getPatRuntime<rdoRuntime::RDOPatternEvent>()->createActivity(pParser->runtime()->m_pMetaLogic, pParser->runtime(), pEvent->name());
			ASSERT(pRuntimeEvent);
			pEvent->setRuntimeEvent(pRuntimeEvent);

			STL_FOR_ALL(pEvent->getCalcList(), calcIt)
			{
				(*calcIt)->setEvent(pRuntimeEvent);
			}

			LPIActivity pActivity = pRuntimeEvent;
			ASSERT(pActivity);
			STL_FOR_ALL_CONST(pEvent->getParamList()->getContainer(), paramIt)
			{
				LPRDOFUNArithm pParam = *paramIt;
				ASSERT(pParam);
				if (m_currParam < pPattern->m_paramList.size())
				{
					rdoRuntime::LPRDOCalc pSetParamCalc;
					LPRDOParam pPatternParam = pPattern->m_paramList[m_currParam];
					ASSERT(pPatternParam);
					if (pParam->typeInfo()->src_info().src_text() == _T("*"))
					{
						if (!pPatternParam->getDefault()->defined())
						{
							RDOParser::s_parser()->error().push_only(pPatternParam->src_info(), rdo::format(_T("  -   '%s'"), pPatternParam->src_text().c_str()));
							RDOParser::s_parser()->error().push_only(pPatternParam->src_info(), rdo::format(_T(".  '%s',  '%s'"), pPatternParam->src_text().c_str(), pPatternParam->getTypeInfo()->src_info().src_text().c_str()));
							RDOParser::s_parser()->error().push_done();
						}
						rdoRuntime::RDOValue val = pPatternParam->getDefault()->value();
						ASSERT(val);
						pSetParamCalc = rdo::Factory<rdoRuntime::RDOSetPatternParamCalc>::create(
							m_currParam,
							rdo::Factory<rdoRuntime::RDOCalcConst>::create(val)
						);
					}
					else
					{
						LPTypeInfo pTypeInfo = pPatternParam->getTypeInfo();
						ASSERT(pTypeInfo);
						rdoRuntime::LPRDOCalc pParamValueCalc = pParam->createCalc(pTypeInfo);
						ASSERT(pParamValueCalc);
						pSetParamCalc = rdo::Factory<rdoRuntime::RDOSetPatternParamCalc>::create(
							m_currParam,
							pParamValueCalc
						);
					}
					ASSERT(pSetParamCalc);
					pActivity->addParamCalc(pSetParamCalc);
					++m_currParam;
				}
				else
				{
					RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T("     '%s'    '%s'"), pEvent->name().c_str(), pEvent->name().c_str()));
					RDOParser::s_parser()->error().push_done();
				}
			}
			m_currParam = 0;
		}
		else
		{
			NEVER_REACH_HERE; //
		}
	}
}

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - удалим лексер сразу после использования<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdoparser_rdo.cpp
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_activity_i.h"
#include "simulator/compiler/parser/rdoparser_rdo.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdosmr.h"
#include "simulator/compiler/parser/rdorss.h"
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdofun.h"
#include "simulator/compiler/parser/rdosmr.h"
#include "simulator/compiler/parser/rdopat.h"
#include "simulator/runtime/rdo_pattern.h"
#include "utils/rdostream.h"
#include "kernel/rdokernel.h"
#include "repository/rdorepository.h"
#include "simulator/runtime/calc/calc_pattern.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOParserRDOItem
// --------------------------------------------------------------------------------
RDOParserRDOItem::RDOParserRDOItem(rdoModelObjects::RDOFileType type, t_bison_parse_fun parser_fun, t_bison_error_fun error_fun, t_flex_lexer_fun lexer_fun, StreamFrom from)
	: RDOParserItem(type, parser_fun, error_fun, lexer_fun, from)
	, m_pLexer(NULL)
{}

RDOParserRDOItem::~RDOParserRDOItem()
{
	if (m_pLexer)
	{
		delete m_pLexer;
		m_pLexer = NULL;
	}
}

void RDOParserRDOItem::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	rdo::binarystream in_stream;
	switch (m_from)
	{
		case sf_repository:
		{
			rdoRepository::RDOThreadRepository::FileData fileData(m_type, in_stream);
			kernel->sendMessage(kernel->repository(), RDOThread::RT_REPOSITORY_LOAD, &fileData);
			break;
		}
		case sf_editor:
		{
			rdoRepository::RDOThreadRepository::FileData fileData(m_type, in_stream);
			kernel->sendMessage(kernel->studio(), RDOThread::RT_STUDIO_MODEL_GET_TEXT, &fileData);
			break;
		}
	}
	if (in_stream.good())
	{
		parse(pParser, in_stream);
	}
}

void RDOParserRDOItem::parse(CREF(LPRDOParser) pParser, REF(std::istream) in_stream)
{
	ASSERT(pParser  );
	ASSERT(!m_pLexer);

	std::ostringstream out_stream;
	m_pLexer = getLexer(pParser, &in_stream, &out_stream);

	if (m_pLexer)
	{
		if (m_parser_fun)
		{
			m_parser_fun(m_pLexer);
		}
		delete m_pLexer;
		m_pLexer = NULL;
	}
}

PTR(RDOLexer) RDOParserRDOItem::getLexer(CREF(LPRDOParser) pParser, PTR(std::istream) in_stream, PTR(std::ostream) out_stream)
{
	ASSERT(pParser);
	return new RDOLexer(pParser, in_stream, out_stream);
}

ruint RDOParserRDOItem::lexer_loc_line()
{
	if (m_pLexer)
	{
		return m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_line : m_pLexer->lineno();
	}
	else
	{
		return ruint(rdoRuntime::RDOSrcInfo::Position::UNDEFINE_LINE);
	}
}

ruint RDOParserRDOItem::lexer_loc_pos()
{
	return m_pLexer && m_pLexer->m_lploc ? m_pLexer->m_lploc->m_first_pos : 0;
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserRSS
// --------------------------------------------------------------------------------
RDOParserRSS::RDOParserRSS(StreamFrom from)
	: RDOParserRDOItem(rdoModelObjects::RSS, rssparse, rsserror, rsslex, from)
{}

void RDOParserRSS::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);
	pParser->setHaveKWResources   (false);
	pParser->setHaveKWResourcesEnd(false);
	RDOParserRDOItem::parse(pParser);
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserRSSPost
// --------------------------------------------------------------------------------
void RDOParserRSSPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!            ,        RSS
#ifdef RDOSIM_COMPATIBLE
	STL_FOR_ALL_CONST(pParser->getRTPResType(), rtp_it)
	{
#endif
		STL_FOR_ALL_CONST(pParser->getRSSResources(), rss_it)
		{
#ifdef RDOSIM_COMPATIBLE
			if ((*rss_it)->getType() == *rtp_it)
			{
#endif
				rdoRuntime::LPRDOCalc calc = (*rss_it)->createCalc();
				pParser->runtime()->addInitCalc(calc);
#ifdef RDOSIM_COMPATIBLE
			}
#endif
		}
#ifdef RDOSIM_COMPATIBLE
	}
#endif
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserSMRPost
// --------------------------------------------------------------------------------
RDOParserSMRPost::RDOParserSMRPost()
	: RDOParserItem(rdoModelObjects::SMR, NULL, NULL, NULL)
{}

void RDOParserSMRPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!  ,   SMR
	STL_FOR_ALL_CONST(pParser->getEvents(), eventIt)
	{
		LPRDOEvent pEvent = *eventIt;
		ASSERT(pEvent);

		rdoRuntime::LPRDOCalc pInitCalc = pEvent->getInitCalc();
		if (pInitCalc)
		{
			pParser->runtime()->addInitCalc(pInitCalc);
		}
	}
}

// --------------------------------------------------------------------------------
// -------------------- RDOParserEVNPost
// --------------------------------------------------------------------------------
void RDOParserEVNPost::parse(CREF(LPRDOParser) pParser)
{
	ASSERT(pParser);

	//!
	STL_FOR_ALL_CONST(pParser->getEvents(), eventIt)
	{
		LPRDOEvent pEvent = *eventIt;

		LPRDOPATPattern pPattern = pParser->findPATPattern(pEvent->name());
		if (!pPattern)
		{
			STL_FOR_ALL_CONST(pEvent->getCalcList(), calcIt)
			{
				pParser->error().push_only((*calcIt)->src_info(), rdo::format(_T("   : %s"), pEvent->name().c_str()));
			}
			pParser->error().push_done();
		}
		if (pPattern->getType() != RDOPATPattern::PT_Event)
		{
			STL_FOR_ALL_CONST(pEvent->getCalcList(), calcIt)
			{
				pParser->error().push_only((*calcIt)->src_info(), rdo::format(_T(" %s   : %s"), pEvent->name().c_str()));
			}
			pParser->error().push_done();
		}

		if (pEvent->getRegular())
		{
			LPIBaseOperation pRuntimeEvent = pPattern->getPatRuntime<rdoRuntime::RDOPatternEvent>()->createActivity(pParser->runtime()->m_pMetaLogic, pParser->runtime(), pEvent->name());
			ASSERT(pRuntimeEvent);
			pEvent->setRuntimeEvent(pRuntimeEvent);

			STL_FOR_ALL(pEvent->getCalcList(), calcIt)
			{
				(*calcIt)->setEvent(pRuntimeEvent);
			}

			LPIActivity pActivity = pRuntimeEvent;
			ASSERT(pActivity);
			STL_FOR_ALL_CONST(pEvent->getParamList()->getContainer(), paramIt)
			{
				LPRDOFUNArithm pParam = *paramIt;
				ASSERT(pParam);
				if (m_currParam < pPattern->m_paramList.size())
				{
					rdoRuntime::LPRDOCalc pSetParamCalc;
					LPRDOParam pPatternParam = pPattern->m_paramList[m_currParam];
					ASSERT(pPatternParam);
					if (pParam->typeInfo()->src_info().src_text() == _T("*"))
					{
						if (!pPatternParam->getDefault()->defined())
						{
							RDOParser::s_parser()->error().push_only(pPatternParam->src_info(), rdo::format(_T("  -   '%s'"), pPatternParam->src_text().c_str()));
							RDOParser::s_parser()->error().push_only(pPatternParam->src_info(), rdo::format(_T(".  '%s',  '%s'"), pPatternParam->src_text().c_str(), pPatternParam->getTypeInfo()->src_info().src_text().c_str()));
							RDOParser::s_parser()->error().push_done();
						}
						rdoRuntime::RDOValue val = pPatternParam->getDefault()->value();
						ASSERT(val);
						pSetParamCalc = rdo::Factory<rdoRuntime::RDOSetPatternParamCalc>::create(
							m_currParam,
							rdo::Factory<rdoRuntime::RDOCalcConst>::create(val)
						);
					}
					else
					{
						LPTypeInfo pTypeInfo = pPatternParam->getTypeInfo();
						ASSERT(pTypeInfo);
						rdoRuntime::LPRDOCalc pParamValueCalc = pParam->createCalc(pTypeInfo);
						ASSERT(pParamValueCalc);
						pSetParamCalc = rdo::Factory<rdoRuntime::RDOSetPatternParamCalc>::create(
							m_currParam,
							pParamValueCalc
						);
					}
					ASSERT(pSetParamCalc);
					pActivity->addParamCalc(pSetParamCalc);
					++m_currParam;
				}
				else
				{
					RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T("     '%s'    '%s'"), pEvent->name().c_str(), pEvent->name().c_str()));
					RDOParser::s_parser()->error().push_done();
				}
			}
			m_currParam = 0;
		}
		else
		{
			NEVER_REACH_HERE; //
		}
	}
}

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>// Time:  O(nlogn)
// Space: O(n)

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        deque<int64_t> window;
        multiset<int64_t> bst;
        for (int i = 0; i < nums.size(); ++i) {
            // Only keep at most k elements.
            if (bst.size() > k) {
                int num = window.front();
                window.pop_front();
                bst.erase(bst.find(num));
            }
            // Every search costs time: O(logn).
            const auto it = bst.lower_bound(nums[i] - t);
            if (it == bst.cend() || (*it - nums[i]) > t) {
                // Not found.
                window.emplace_back(nums[i]);
                bst.emplace(nums[i]);
            } else {
                return true;
            }
        }
        return false;
    }
};
<commit_msg>Update contains-duplicate-iii.cpp<commit_after>// Time:  O(nlogn)
// Space: O(n)

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        queue<int64_t> window;
        multiset<int64_t> bst;
        for (int i = 0; i < nums.size(); ++i) {
            // Only keep at most k elements.
            if (bst.size() > k) {
                int num = window.front();
                window.pop();
                bst.erase(bst.find(num));
            }
            // Every search costs time: O(logn).
            const auto it = bst.lower_bound(nums[i] - t);
            if (it == bst.cend() || (*it - nums[i]) > t) {
                // Not found.
                window.emplace(nums[i]);
                bst.emplace(nums[i]);
            } else {
                return true;
            }
        }
        return false;
    }
};
<|endoftext|>


<commit_before>// Time:  O(m * n * (logm + logn))
// Space: O(m * n)

// BFS with priority queue (min heap), refactored version.
class Solution {
public:
    struct Cell {
        int i;
        int j;
        int height;
    };

    struct Compare {
        bool operator()(const Cell& a, const Cell& b) {
            return a.height > b.height;
        }
    };

    /**
     * @param heights: a matrix of integers
     * @return: an integer
     */
    int trapRainWater(vector<vector<int>> &heights) {
        // Init m_, n_, is_visited_.
        m_ = heights.size();
        n_ = heights[0].size();
        is_visited_ = vector<vector<bool>>(m_, vector<bool>(n_, false));

        int trap = 0;

        // Put the cells on the border into min heap.
        for (int i = 0; i < m_; ++i) {
            heap_.emplace(Cell{i, 0, heights[i][0]});
            heap_.emplace(Cell{i, n_ - 1, heights[i][n_ - 1]});
        }
        for (int j = 0; j < n_; ++j) {
            heap_.emplace(Cell{0, j, heights[0][j]});
            heap_.emplace(Cell{m_ - 1, j, heights[m_ - 1][j]});
        }

        // BFS with priority queue (min heap)
        while (!heap_.empty()) {
            Cell c = heap_.top();
            heap_.pop();
            is_visited_[c.i][c.j] = true;

            trap += fill(heights, c.i + 1, c.j, c.height); // Up
            trap += fill(heights, c.i - 1, c.j, c.height); // Down
            trap += fill(heights, c.i, c.j + 1, c.height); // Right
            trap += fill(heights, c.i, c.j - 1, c.height); // Left
        }

        return trap;
    }

private:
    int fill(const vector<vector<int>>& heights, int i, int j, int height) {
        // Out of border.
        if ( i < 0 || i >= m_ || j < 0 || j >= n_) {
            return 0;
        }

        // Fill unvisited cell.
        if (!is_visited_[i][j]) {
            is_visited_[i][j] = true; // Marked as visited.
            heap_.emplace(Cell{i, j, max(height, heights[i][j])});
            return max(0, height - heights[i][j]); // Fill in the gap.
        }

        return 0;
    }

    int m_;
    int n_;
    vector<vector<bool>> is_visited_;
    priority_queue<Cell ,vector<Cell>, Compare> heap_; // Use min heap to get the lowerest cell.
};

// Time:  O(m * n * (logm + logn))
// Space: O(m * n)
// BFS with priority queue (min heap)
class Solution2 {
public:
    struct Cell {
        int i;
        int j;
        int height;
    };

    /**
     * @param heights: a matrix of integers
     * @return: an integer
     */
    int trapRainWater(vector<vector<int>> &heights) {
        const int m = heights.size();
        const int n = heights[0].size();
        int trap = 0;
        vector<vector<bool>> is_visited(m, vector<bool>(n, false));

        // Use min heap to get the lowerest Cell.
        auto comp = [](const Cell& a, const Cell& b ) { return a.height > b.height; };
        priority_queue<Cell , vector<Cell>, decltype(comp)> heap(comp);

        // Put the Cells on the border into min heap.
        for (int i = 0; i < m; ++i) {
            heap.emplace(Cell{i, 0, heights[i][0]});
            heap.emplace(Cell{i, n - 1, heights[i][n - 1]});
        }
        for (int j = 0; j < n; ++j) {
            heap.emplace(Cell{0, j, heights[0][j]});
            heap.emplace(Cell{m - 1, j, heights[m - 1][j]});
        }

        // BFS with priority queue (min heap)
        while (!heap.empty()) {
            // Get the lowest Cell.
            Cell c = heap.top();
            heap.pop();
            is_visited[c.i][c.j] = true;

            // Up
            if (c.i + 1 < m && !is_visited[c.i + 1][c.j]) {
                is_visited[c.i + 1][c.j] = true;
                trap += max(0, c.height - heights[c.i + 1][c.j]); // Fill in the gap.
                heap.emplace(Cell{c.i + 1, c.j, max(c.height,
                                                    heights[c.i + 1][c.j])});
            }
            // Down
            if (c.i - 1 >= 0 && !is_visited[c.i - 1][c.j]) {
                is_visited[c.i - 1][c.j] = true;
                trap += max(0, c.height - heights[c.i - 1][c.j]); // Fill in the gap.
                heap.emplace(Cell{c.i - 1, c.j, max(c.height,
                                                    heights[c.i - 1][c.j])});
            }
            // Right
            if (c.j + 1 < n && !is_visited[c.i][c.j + 1]) {
                is_visited[c.i][c.j + 1] = true;
                trap += max(0, c.height - heights[c.i][c.j + 1]); // Fill in the gap.
                heap.emplace(Cell{c.i, c.j + 1, max(c.height,
                                                    heights[c.i][c.j + 1])});
            }
            // Left
            if (c.j - 1 >= 0 && !is_visited[c.i][c.j - 1]) {
                is_visited[c.i][c.j - 1] = true;
                trap += max(0, c.height - heights[c.i][c.j - 1]); // Fill in the gap.
                heap.emplace(Cell{c.i, c.j - 1, max(c.height,
                                                    heights[c.i][c.j - 1])});
            }
        }

        return trap;
    }
};
<commit_msg>Update trapping-rain-water-ii.cpp<commit_after>// Time:  O(m * n * log(m + n) ~ O(m * n * (log(m * n)))
// Space: O(m * n)

// BFS with priority queue (min heap), refactored version.
class Solution {
public:
    /**
     * @param heights: a matrix of integers
     * @return: an integer
     */
    int trapRainWater(vector<vector<int>> &heights) {
        // Init m_, n_, is_visited_.
        m_ = heights.size();
        n_ = heights[0].size();
        is_visited_ = vector<vector<bool>>(m_, vector<bool>(n_, false));

        int trap = 0;

        // Put the cells on the border into min heap.
        for (int i = 0; i < m_; ++i) {
            heap_.emplace(Cell{i, 0, heights[i][0]});
            heap_.emplace(Cell{i, n_ - 1, heights[i][n_ - 1]});
        }
        for (int j = 0; j < n_; ++j) {
            heap_.emplace(Cell{0, j, heights[0][j]});
            heap_.emplace(Cell{m_ - 1, j, heights[m_ - 1][j]});
        }
        const vector<pair<int, int>> directions{{0, -1}, {0, 1},
                                                {-1, 0}, {1, 0}};
        // BFS with priority queue (min heap)
        while (!heap_.empty()) {
            Cell c = heap_.top();
            heap_.pop();
            is_visited_[c.i][c.j] = true;

	        for (const auto& d : directions) {
                trap += fill(heights, c.i + d.first, c.j + d.second, c.height);
	        }
        }

        return trap;
    }

private:
    int fill(const vector<vector<int>>& heights, int i, int j, int height) {
        // Out of border.
        if ( i < 0 || i >= m_ || j < 0 || j >= n_) {
            return 0;
        }

        // Fill unvisited cell.
        if (!is_visited_[i][j]) {
            is_visited_[i][j] = true; // Marked as visited.
            heap_.emplace(Cell{i, j, max(height, heights[i][j])});
            return max(0, height - heights[i][j]); // Fill in the gap.
        }

        return 0;
    }

    struct Cell {
        int i;
        int j;
        int height;
    };

    struct Compare {
        bool operator()(const Cell& a, const Cell& b) {
            return a.height > b.height;
        }
    };

    int m_;
    int n_;
    vector<vector<bool>> is_visited_;
    priority_queue<Cell ,vector<Cell>, Compare> heap_; // Use min heap to get the lowerest cell.
};
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;

int sum (int num){
  if (num==0)
    return 0;
  return (sum(num-1)+(num));
}

int main(){
  int num;
  cout << "Enter a number" << endl;
  cin >> num;
  cout << sum(num) << endl;
}
<commit_msg>Update S5_Sum.cpp<commit_after>//
//  Program Name - S5_Sum.cpp
//  Series: GetOnToC++ Step: 5
//
//  Purpose: This program uses recursion to fine the sum of a number and all the numbers before it
//
//  Compile: g++ S5_Sum.cpp -o S5_Sum
//  Execute: ./S5_Sum
//
//  Created by Narayan Mahadevan on 18/08/13.
//
#include <iostream>
using namespace std;

int sum (int num){
  if (num==0)
    return 0;
  return (sum(num-1)+(num));
}

int main(){
  int num;
  cout << "Enter a number" << endl;
  cin >> num;
  cout << sum(num) << endl;
}
<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "kcm-telepathy-accounts.h"

#include "ui_main-widget.h"

#include "accounts-list-model.h"
#include "add-account-assistant.h"
#include "edit-account-dialog.h"
#include "accounts-list-delegate.h"

#include <QLabel>

#include <KGenericFactory>
#include <KIcon>
#include <KLocale>
#include <KMessageBox>
#include <KAboutData>

#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountFactory>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Types>

K_PLUGIN_FACTORY(KCMTelepathyAccountsFactory, registerPlugin<KCMTelepathyAccounts>();)
K_EXPORT_PLUGIN(KCMTelepathyAccountsFactory("telepathy_accounts", "kcm_telepathy_accounts"))

KCMTelepathyAccounts::KCMTelepathyAccounts(QWidget *parent, const QVariantList& args)
 : KCModule(KCMTelepathyAccountsFactory::componentData(), parent, args),
   m_accountsListModel(0)
{
    kDebug();

    //set up component data.
    KAboutData *aboutData = new KAboutData(I18N_NOOP("telepathy_accounts"), 0, ki18n("Instant Messaging and VOIP Accounts"), 0, KLocalizedString(), KAboutData::License_GPL);

    aboutData->addAuthor(ki18n("George Goldberg"), ki18n("Developer"),"grundleborg@googlemail.com");
    aboutData->addAuthor(ki18n("David Edmundson"), ki18n("Developer"), "david@davidedmundson.co.uk");
    aboutData->addAuthor(ki18n("Dominik Schmidt"), ki18n("Developer"), "kde@dominik-schmidt.de");
    aboutData->addAuthor(ki18n("Thomas Richard"), ki18n("Developer"), "thomas.richard@proan.be");
    aboutData->addAuthor(ki18n("Florian Reinhard"), ki18n("Developer"), "florian.reinhard@googlemail.com");

    setAboutData(aboutData);

    // The first thing we must do is register Telepathy DBus Types.
    Tp::registerTypes();

    // Start setting up the Telepathy AccountManager.
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureAvatar
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    m_accountManager = Tp::AccountManager::create(accountFactory);

    connect(m_accountManager->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));

    // Set up the UI stuff.
    m_ui = new Ui::MainWidget;
    m_ui->setupUi(this);

    m_accountsListModel = new AccountsListModel(this);
    m_ui->accountsListView->setModel(m_accountsListModel);

    m_ui->addAccountButton->setIcon(KIcon("list-add"));
    m_ui->editAccountButton->setIcon(KIcon("configure"));
    m_ui->removeAccountButton->setIcon(KIcon("edit-delete"));

    AccountsListDelegate* delegate = new AccountsListDelegate(m_ui->accountsListView, this);
    m_ui->accountsListView->setItemDelegate(delegate);

    connect(delegate,
            SIGNAL(itemChecked(QModelIndex, bool)),
            SLOT(onAccountEnabledChanged(QModelIndex, bool)));
    connect(m_ui->addAccountButton,
            SIGNAL(clicked()),
            SLOT(onAddAccountClicked()));
    connect(m_ui->editAccountButton,
            SIGNAL(clicked()),
            SLOT(onEditAccountClicked()));
    connect(m_ui->removeAccountButton,
            SIGNAL(clicked()),
            SLOT(onRemoveAccountClicked()));
    connect(m_ui->accountsListView->selectionModel(),
            SIGNAL(currentChanged(QModelIndex, QModelIndex)),
            SLOT(onSelectedItemChanged()));
}

KCMTelepathyAccounts::~KCMTelepathyAccounts()
{
    kDebug();

    delete m_ui;
}

void KCMTelepathyAccounts::load()
{
    kDebug();

    // This slot is called whenever the configuration data in this KCM should
    // be reloaded from the store. We will not actually do anything here since
    // all changes that are made in this KCM are, at the moment, saved
    // immediately and cannot be reverted programatically.
    return;
}

void KCMTelepathyAccounts::onAccountEnabledChanged(const QModelIndex &index, bool enabled)
{
    QVariant value;
    if (enabled) {
        value = QVariant(Qt::Checked);
    }
    else {
        value = QVariant(Qt::Unchecked);
    }
    m_accountsListModel->setData(index, value, Qt::CheckStateRole);
}

void KCMTelepathyAccounts::onAccountManagerReady(Tp::PendingOperation *op)
{
    kDebug();

    // Check the pending operation completed successfully.
    if (op->isError()) {
        kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
        new ErrorOverlay(this, op->errorMessage(), this);
        return;
    }

    // Add all the accounts to the Accounts Model.
    QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();
    foreach (Tp::AccountPtr account, accounts) {
        m_accountsListModel->addAccount(account);
    }

    connect(m_accountManager.data(),
            SIGNAL(newAccount (Tp::AccountPtr)),
            SLOT(onAccountCreated(Tp::AccountPtr)));
}

void KCMTelepathyAccounts::onAccountCreated(const Tp::AccountPtr &account)
{
    m_accountsListModel->addAccount(account);
}

void KCMTelepathyAccounts::onSelectedItemChanged()
{
    bool isAccount = m_ui->accountsListView->currentIndex().isValid();
    m_ui->removeAccountButton->setEnabled(isAccount);
    m_ui->editAccountButton->setEnabled(isAccount);
}

void KCMTelepathyAccounts::onAddAccountClicked()
{
    kDebug();

    // Wizard only works if the AccountManager is ready.
    if (!m_accountManager->isReady()) {
        return;
    }

    // ...and finally exec it.
    AddAccountAssistant assistant(m_accountManager, this);
    assistant.exec();
}

void KCMTelepathyAccounts::onEditAccountClicked()
{
    kDebug();

    // Editing accounts is only possible if the Account Manager is ready.
    if (!m_accountManager->isReady()) {
        return;
    }

    QModelIndex index = m_ui->accountsListView->currentIndex();
    AccountItem *item = m_accountsListModel->itemForIndex(index);

    if (!item)
        return;

    // Item is OK. Edit the item.
    EditAccountDialog dialog(item, this);
    dialog.exec();
}

void KCMTelepathyAccounts::onRemoveAccountClicked()
{
    kDebug();
    QModelIndex index = m_ui->accountsListView->currentIndex();

     if ( KMessageBox::warningContinueCancel(this, i18n("Are you sure you want to remove the account \"%1\"?", m_accountsListModel->data(index, Qt::DisplayRole).toString()),
                                        i18n("Remove Account"), KGuiItem(i18n("Remove Account"), "edit-delete"), KStandardGuiItem::cancel(),
                                        QString(), KMessageBox::Notify | KMessageBox::Dangerous) == KMessageBox::Continue)
    {
        m_accountsListModel->removeAccount(index);
    }
}

/////

ErrorOverlay::ErrorOverlay(QWidget *baseWidget, const QString &details, QWidget *parent) :
    QWidget(parent ? parent : baseWidget->window()),
    m_BaseWidget(baseWidget)
{
    // Build the UI
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setSpacing(10);

    QLabel *pixmap = new QLabel();
    pixmap->setPixmap(KIcon("dialog-error").pixmap(64));

    QLabel *message = new QLabel(i18n("Something went terribly wrong and the IM system could not be initialized.\n"
                                      "It is likely your system is missing Telepathy Mission Control package.\n"
                                      "Please install it and restart this module."));

    pixmap->setAlignment(Qt::AlignHCenter);
    message->setAlignment(Qt::AlignHCenter);

    layout->addStretch();
    layout->addWidget(pixmap);
    layout->addWidget(message);
    layout->addStretch();

    setLayout(layout);

    // Draw the transparent overlay background
    QPalette p = palette();
    p.setColor(backgroundRole(), QColor(0, 0, 0, 128));
    p.setColor(foregroundRole(), Qt::white);
    setPalette(p);
    setAutoFillBackground(true);

    m_BaseWidget->installEventFilter(this);

    reposition();
}

ErrorOverlay::~ErrorOverlay()
{
}

void ErrorOverlay::reposition()
{
    if (!m_BaseWidget) {
        return;
    }

    // reparent to the current top level widget of the base widget if needed
    // needed eg. in dock widgets
    if (parentWidget() != m_BaseWidget->window()) {
        setParent(m_BaseWidget->window());
    }

    // follow base widget visibility
    // needed eg. in tab widgets
    if (!m_BaseWidget->isVisible()) {
        hide();
        return;
    }

    show();

    // follow position changes
    const QPoint topLevelPos = m_BaseWidget->mapTo(window(), QPoint(0, 0));
    const QPoint parentPos = parentWidget()->mapFrom(window(), topLevelPos);
    move(parentPos);

    // follow size changes
    // TODO: hide/scale icon if we don't have enough space
    resize(m_BaseWidget->size());
}

bool ErrorOverlay::eventFilter(QObject * object, QEvent * event)
{
    if (object == m_BaseWidget &&
        (event->type() == QEvent::Move || event->type() == QEvent::Resize ||
        event->type() == QEvent::Show || event->type() == QEvent::Hide ||
        event->type() == QEvent::ParentChange)) {
        reposition();
    }
    return QWidget::eventFilter(object, event);
}

#include "kcm-telepathy-accounts.moc"
<commit_msg>Connect automatically when an account is enabled.<commit_after>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "kcm-telepathy-accounts.h"

#include "ui_main-widget.h"

#include "accounts-list-model.h"
#include "add-account-assistant.h"
#include "edit-account-dialog.h"
#include "accounts-list-delegate.h"

#include <QLabel>

#include <KGenericFactory>
#include <KIcon>
#include <KLocale>
#include <KMessageBox>
#include <KAboutData>

#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountFactory>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Types>

K_PLUGIN_FACTORY(KCMTelepathyAccountsFactory, registerPlugin<KCMTelepathyAccounts>();)
K_EXPORT_PLUGIN(KCMTelepathyAccountsFactory("telepathy_accounts", "kcm_telepathy_accounts"))

KCMTelepathyAccounts::KCMTelepathyAccounts(QWidget *parent, const QVariantList& args)
 : KCModule(KCMTelepathyAccountsFactory::componentData(), parent, args),
   m_accountsListModel(0)
{
    kDebug();

    //set up component data.
    KAboutData *aboutData = new KAboutData(I18N_NOOP("telepathy_accounts"), 0, ki18n("Instant Messaging and VOIP Accounts"), 0, KLocalizedString(), KAboutData::License_GPL);

    aboutData->addAuthor(ki18n("George Goldberg"), ki18n("Developer"),"grundleborg@googlemail.com");
    aboutData->addAuthor(ki18n("David Edmundson"), ki18n("Developer"), "david@davidedmundson.co.uk");
    aboutData->addAuthor(ki18n("Dominik Schmidt"), ki18n("Developer"), "kde@dominik-schmidt.de");
    aboutData->addAuthor(ki18n("Thomas Richard"), ki18n("Developer"), "thomas.richard@proan.be");
    aboutData->addAuthor(ki18n("Florian Reinhard"), ki18n("Developer"), "florian.reinhard@googlemail.com");

    setAboutData(aboutData);

    // The first thing we must do is register Telepathy DBus Types.
    Tp::registerTypes();

    // Start setting up the Telepathy AccountManager.
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureAvatar
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    m_accountManager = Tp::AccountManager::create(accountFactory);

    connect(m_accountManager->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));

    // Set up the UI stuff.
    m_ui = new Ui::MainWidget;
    m_ui->setupUi(this);

    m_accountsListModel = new AccountsListModel(this);
    m_ui->accountsListView->setModel(m_accountsListModel);

    m_ui->addAccountButton->setIcon(KIcon("list-add"));
    m_ui->editAccountButton->setIcon(KIcon("configure"));
    m_ui->removeAccountButton->setIcon(KIcon("edit-delete"));

    AccountsListDelegate* delegate = new AccountsListDelegate(m_ui->accountsListView, this);
    m_ui->accountsListView->setItemDelegate(delegate);

    connect(delegate,
            SIGNAL(itemChecked(QModelIndex, bool)),
            SLOT(onAccountEnabledChanged(QModelIndex, bool)));
    connect(m_ui->addAccountButton,
            SIGNAL(clicked()),
            SLOT(onAddAccountClicked()));
    connect(m_ui->editAccountButton,
            SIGNAL(clicked()),
            SLOT(onEditAccountClicked()));
    connect(m_ui->removeAccountButton,
            SIGNAL(clicked()),
            SLOT(onRemoveAccountClicked()));
    connect(m_ui->accountsListView->selectionModel(),
            SIGNAL(currentChanged(QModelIndex, QModelIndex)),
            SLOT(onSelectedItemChanged()));
}

KCMTelepathyAccounts::~KCMTelepathyAccounts()
{
    kDebug();

    delete m_ui;
}

void KCMTelepathyAccounts::load()
{
    kDebug();

    // This slot is called whenever the configuration data in this KCM should
    // be reloaded from the store. We will not actually do anything here since
    // all changes that are made in this KCM are, at the moment, saved
    // immediately and cannot be reverted programatically.
    return;
}

void KCMTelepathyAccounts::onAccountEnabledChanged(const QModelIndex &index, bool enabled)
{
    QVariant value;
    if (enabled) {
        value = QVariant(Qt::Checked);
    }
    else {
        value = QVariant(Qt::Unchecked);
    }
    m_accountsListModel->setData(index, value, Qt::CheckStateRole);

    if (enabled) {
        // connect the account
        AccountItem *item = m_accountsListModel->itemForIndex(index);
        if (item) {
            item->account()->setRequestedPresence(Tp::Presence::available(QString("Online")));
        }
    }
}

void KCMTelepathyAccounts::onAccountManagerReady(Tp::PendingOperation *op)
{
    kDebug();

    // Check the pending operation completed successfully.
    if (op->isError()) {
        kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
        new ErrorOverlay(this, op->errorMessage(), this);
        return;
    }

    // Add all the accounts to the Accounts Model.
    QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();
    foreach (Tp::AccountPtr account, accounts) {
        m_accountsListModel->addAccount(account);
    }

    connect(m_accountManager.data(),
            SIGNAL(newAccount (Tp::AccountPtr)),
            SLOT(onAccountCreated(Tp::AccountPtr)));
}

void KCMTelepathyAccounts::onAccountCreated(const Tp::AccountPtr &account)
{
    m_accountsListModel->addAccount(account);
}

void KCMTelepathyAccounts::onSelectedItemChanged()
{
    bool isAccount = m_ui->accountsListView->currentIndex().isValid();
    m_ui->removeAccountButton->setEnabled(isAccount);
    m_ui->editAccountButton->setEnabled(isAccount);
}

void KCMTelepathyAccounts::onAddAccountClicked()
{
    kDebug();

    // Wizard only works if the AccountManager is ready.
    if (!m_accountManager->isReady()) {
        return;
    }

    // ...and finally exec it.
    AddAccountAssistant assistant(m_accountManager, this);
    assistant.exec();
}

void KCMTelepathyAccounts::onEditAccountClicked()
{
    kDebug();

    // Editing accounts is only possible if the Account Manager is ready.
    if (!m_accountManager->isReady()) {
        return;
    }

    QModelIndex index = m_ui->accountsListView->currentIndex();
    AccountItem *item = m_accountsListModel->itemForIndex(index);

    if (!item)
        return;

    // Item is OK. Edit the item.
    EditAccountDialog dialog(item, this);
    dialog.exec();
}

void KCMTelepathyAccounts::onRemoveAccountClicked()
{
    kDebug();
    QModelIndex index = m_ui->accountsListView->currentIndex();

     if ( KMessageBox::warningContinueCancel(this, i18n("Are you sure you want to remove the account \"%1\"?", m_accountsListModel->data(index, Qt::DisplayRole).toString()),
                                        i18n("Remove Account"), KGuiItem(i18n("Remove Account"), "edit-delete"), KStandardGuiItem::cancel(),
                                        QString(), KMessageBox::Notify | KMessageBox::Dangerous) == KMessageBox::Continue)
    {
        m_accountsListModel->removeAccount(index);
    }
}

/////

ErrorOverlay::ErrorOverlay(QWidget *baseWidget, const QString &details, QWidget *parent) :
    QWidget(parent ? parent : baseWidget->window()),
    m_BaseWidget(baseWidget)
{
    // Build the UI
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setSpacing(10);

    QLabel *pixmap = new QLabel();
    pixmap->setPixmap(KIcon("dialog-error").pixmap(64));

    QLabel *message = new QLabel(i18n("Something went terribly wrong and the IM system could not be initialized.\n"
                                      "It is likely your system is missing Telepathy Mission Control package.\n"
                                      "Please install it and restart this module."));

    pixmap->setAlignment(Qt::AlignHCenter);
    message->setAlignment(Qt::AlignHCenter);

    layout->addStretch();
    layout->addWidget(pixmap);
    layout->addWidget(message);
    layout->addStretch();

    setLayout(layout);

    // Draw the transparent overlay background
    QPalette p = palette();
    p.setColor(backgroundRole(), QColor(0, 0, 0, 128));
    p.setColor(foregroundRole(), Qt::white);
    setPalette(p);
    setAutoFillBackground(true);

    m_BaseWidget->installEventFilter(this);

    reposition();
}

ErrorOverlay::~ErrorOverlay()
{
}

void ErrorOverlay::reposition()
{
    if (!m_BaseWidget) {
        return;
    }

    // reparent to the current top level widget of the base widget if needed
    // needed eg. in dock widgets
    if (parentWidget() != m_BaseWidget->window()) {
        setParent(m_BaseWidget->window());
    }

    // follow base widget visibility
    // needed eg. in tab widgets
    if (!m_BaseWidget->isVisible()) {
        hide();
        return;
    }

    show();

    // follow position changes
    const QPoint topLevelPos = m_BaseWidget->mapTo(window(), QPoint(0, 0));
    const QPoint parentPos = parentWidget()->mapFrom(window(), topLevelPos);
    move(parentPos);

    // follow size changes
    // TODO: hide/scale icon if we don't have enough space
    resize(m_BaseWidget->size());
}

bool ErrorOverlay::eventFilter(QObject * object, QEvent * event)
{
    if (object == m_BaseWidget &&
        (event->type() == QEvent::Move || event->type() == QEvent::Resize ||
        event->type() == QEvent::Show || event->type() == QEvent::Hide ||
        event->type() == QEvent::ParentChange)) {
        reposition();
    }
    return QWidget::eventFilter(object, event);
}

#include "kcm-telepathy-accounts.moc"
<|endoftext|>


<commit_before><commit_msg>Gtk: Fix file selector moving up one dir each time you use it.<commit_after><|endoftext|>


<commit_before><commit_msg>Set infobar height on a different widget.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <easylogging++.h>
#include <Controller.h>

INITIALIZE_EASYLOGGINGPP

using namespace std;
using namespace con;

void setStack(rlim_t stackSize) {
    struct rlimit rl;
    if (getrlimit(RLIMIT_STACK, &rl) == 0) {
        if (rl.rlim_cur < stackSize) {
            rl.rlim_cur = stackSize;
            if (setrlimit(RLIMIT_STACK, &rl) != 0) {
                CLOG(DEBUG, "exception");
                throw std::logic_error("Cannot set resource info.");
            }
        }
    } else {
        CLOG(DEBUG, "exception");
        throw std::logic_error("Cannot get resource info.");
    }
}

int main(int argc, char *argv[]) {
    START_EASYLOGGINGPP(argc, argv);
    el::Logger *parserLogger = el::Loggers::getLogger("parser");
    el::Logger *exceptionLogger = el::Loggers::getLogger("exception");
    el::Loggers::reconfigureAllLoggers(el::ConfigurationType::ToFile, "false");
    el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format,
                                       "[%logger] %msg [%fbase:%line]");

    setStack(16 * 1024 * 1024);   // 16MB

    sf::RenderWindow drawingBoard(sf::VideoMode(1300, 1300), "Drawing Board"),
            textWindow(sf::VideoMode(1100, 800), "Shell");

    drawingBoard.setPosition(sf::Vector2i{1100, 0});
    textWindow.setPosition(sf::Vector2i{0, 0});

    drawingBoard.setVerticalSyncEnabled(true);
    textWindow.setVerticalSyncEnabled(true);

    Controller controller{textWindow, drawingBoard};

    while (textWindow.isOpen() && drawingBoard.isOpen()) {
        sf::Event event;

        while (textWindow.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                textWindow.close();
            } else if (event.type == sf::Event::KeyPressed && event.key.system) {
                if (event.key.code == sf::Keyboard::E) {
                    controller.clearScreen();
                } else if (event.key.code == sf::Keyboard::R) {
                    controller.execute();
                }
            } else if (event.type == sf::Event::TextEntered) {
                controller.appendChar(static_cast<char>(event.text.unicode));
            } else if (event.type == sf::Event::MouseWheelScrolled) {
                controller.moveScreen(event.mouseWheelScroll.delta * 5);
            }
        }

        while (drawingBoard.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                textWindow.close();
            }
        }

        controller.drawToWindows();
        textWindow.display();
        drawingBoard.display();
    }
    return 0;
}

<commit_msg>增加 linux 需要的头文件<commit_after>#include <iostream>
#include <vector>
#include <sys/time.h>
#include <sys/resource.h>
#include <SFML/Graphics.hpp>
#include <easylogging++.h>
#include <Controller.h>

INITIALIZE_EASYLOGGINGPP

using namespace std;
using namespace con;

void setStack(rlim_t stackSize) {
    struct rlimit rl;
    if (getrlimit(RLIMIT_STACK, &rl) == 0) {
        if (rl.rlim_cur < stackSize) {
            rl.rlim_cur = stackSize;
            if (setrlimit(RLIMIT_STACK, &rl) != 0) {
                CLOG(DEBUG, "exception");
                throw std::logic_error("Cannot set resource info.");
            }
        }
    } else {
        CLOG(DEBUG, "exception");
        throw std::logic_error("Cannot get resource info.");
    }
}

int main(int argc, char *argv[]) {
    START_EASYLOGGINGPP(argc, argv);
    el::Logger *parserLogger = el::Loggers::getLogger("parser");
    el::Logger *exceptionLogger = el::Loggers::getLogger("exception");
    el::Loggers::reconfigureAllLoggers(el::ConfigurationType::ToFile, "false");
    el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format,
                                       "[%logger] %msg [%fbase:%line]");

    setStack(16 * 1024 * 1024);   // 16MB

    sf::RenderWindow drawingBoard(sf::VideoMode(1300, 1300), "Drawing Board"),
            textWindow(sf::VideoMode(1100, 800), "Shell");

    drawingBoard.setPosition(sf::Vector2i{1100, 0});
    textWindow.setPosition(sf::Vector2i{0, 0});

    drawingBoard.setVerticalSyncEnabled(true);
    textWindow.setVerticalSyncEnabled(true);

    Controller controller{textWindow, drawingBoard};

    while (textWindow.isOpen() && drawingBoard.isOpen()) {
        sf::Event event;

        while (textWindow.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                textWindow.close();
            } else if (event.type == sf::Event::KeyPressed && event.key.system) {
                if (event.key.code == sf::Keyboard::E) {
                    controller.clearScreen();
                } else if (event.key.code == sf::Keyboard::R) {
                    controller.execute();
                }
            } else if (event.type == sf::Event::TextEntered) {
                controller.appendChar(static_cast<char>(event.text.unicode));
            } else if (event.type == sf::Event::MouseWheelScrolled) {
                controller.moveScreen(event.mouseWheelScroll.delta * 5);
            }
        }

        while (drawingBoard.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                textWindow.close();
            }
        }

        controller.drawToWindows();
        textWindow.display();
        drawingBoard.display();
    }
    return 0;
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------

#include <iostream>
#include <vector>
#include <string>

#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/HeaderSearchOptions.h"

#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/UserInterface/UserInterface.h"

//------------------------------------------------------------------------------
// Let the show begin
//------------------------------------------------------------------------------
int main( int argc, char **argv )
{

   llvm::llvm_shutdown_obj shutdownTrigger;

   //llvm::sys::PrintStackTraceOnErrorSignal();
   //llvm::PrettyStackTraceProgram X(argc, argv);

   //---------------------------------------------------------------------------
   // Set up the interpreter
   //---------------------------------------------------------------------------
   cling::Interpreter interpreter(argc, argv);
   if (interpreter.getOptions().Help) {
      return 0;
   }

   clang::CompilerInstance* CI = interpreter.getCI();
  interpreter.AddIncludePath(".");

  for (size_t I = 0, N = interpreter.getOptions().LibsToLoad.size();
       I < N; ++I) {
    interpreter.loadFile(interpreter.getOptions().LibsToLoad[I]);
  }

   bool ret = true;
   const std::vector<std::pair<clang::InputKind, std::string> >& Inputs
     = CI->getInvocation().getFrontendOpts().Inputs;

   // Interactive means no input (or one input that's "-")
   bool Interactive = Inputs.empty()
     || (Inputs.size() == 1 && Inputs[0].second == "-");
   if (!Interactive) {
     //---------------------------------------------------------------------------
     // We're supposed to parse files
     //---------------------------------------------------------------------------
      for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
        ret = interpreter.executeFile(Inputs[I].second);
      }
   }
   //----------------------------------------------------------------------------
   // We're interactive
   //----------------------------------------------------------------------------
   else {
      cling::UserInterface ui(interpreter);
      ui.runInteractively(interpreter.getOptions().NoLogo);
   }

   return ret ? 0 : 1;
}
<commit_msg>Use new FrontendInputFile class for inputs - fixes build with trunk.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------

#include <iostream>
#include <vector>
#include <string>

#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/HeaderSearchOptions.h"

#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/UserInterface/UserInterface.h"

//------------------------------------------------------------------------------
// Let the show begin
//------------------------------------------------------------------------------
int main( int argc, char **argv )
{

   llvm::llvm_shutdown_obj shutdownTrigger;

   //llvm::sys::PrintStackTraceOnErrorSignal();
   //llvm::PrettyStackTraceProgram X(argc, argv);

   //---------------------------------------------------------------------------
   // Set up the interpreter
   //---------------------------------------------------------------------------
   cling::Interpreter interpreter(argc, argv);
   if (interpreter.getOptions().Help) {
      return 0;
   }

   clang::CompilerInstance* CI = interpreter.getCI();
  interpreter.AddIncludePath(".");

  for (size_t I = 0, N = interpreter.getOptions().LibsToLoad.size();
       I < N; ++I) {
    interpreter.loadFile(interpreter.getOptions().LibsToLoad[I]);
  }

   bool ret = true;
   const std::vector<clang::FrontendInputFile>& Inputs
     = CI->getInvocation().getFrontendOpts().Inputs;

   // Interactive means no input (or one input that's "-")
   bool Interactive = Inputs.empty()
     || (Inputs.size() == 1 && Inputs[0].File == "-");
   if (!Interactive) {
     //---------------------------------------------------------------------------
     // We're supposed to parse files
     //---------------------------------------------------------------------------
      for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
        ret = interpreter.executeFile(Inputs[I].File);
      }
   }
   //----------------------------------------------------------------------------
   // We're interactive
   //----------------------------------------------------------------------------
   else {
      cling::UserInterface ui(interpreter);
      ui.runInteractively(interpreter.getOptions().NoLogo);
   }

   return ret ? 0 : 1;
}
<|endoftext|>


<commit_before>// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $

// Include files----------------------------------------------------------------
#include "Reflex/Reflex.h"
#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "../dir_manip.h"
#include <cstdlib>

#include <set>
#include <ctime>
#include <cerrno>
#include <fstream>
#include <iostream>
#include <exception>

using namespace std;
using namespace ROOT::Reflex;

class mapGenerator {
   fstream m_out;
   string m_lib;

public:
   mapGenerator(const string& file, const string& lib):
      m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc),
      m_lib(lib) {}

   bool
   good() const { return m_out.good(); }

   void genHeader();
   void genFactory(const string& name,
                   const string& type);
   void genTrailer();
};

static string
currpath(string lib) {
   char buff[PATH_MAX];
   ::getcwd(buff, sizeof(buff));
   string tmp = buff;
   tmp += "/" + lib;
   return tmp;
}

static int
help(const char* cmd) {
   cout << cmd << ":  Allowed options" << endl
        << "  -help            produce this help message" << endl
        << "  -debug           increase verbosity level" << endl
        << "  -input-library   library to extract the plugins" << endl
        << "  -output-file     output file. default <input-library>.rootmap" << endl;
   return 1;
}

//--- Command main program------------------------------------------------------
int
main(int argc,
     char** argv) {
   struct stat buf;
   bool deb = false;
   string rootmap, lib, err, out;
   string::size_type idx;

   for (int i = 1; i < argc; ++i) {
      const char* opt = argv[i], * val = 0;

      if (*opt == '/' || *opt == '-') {
         if (*++opt == '/' || *opt == '-') {
            ++opt;
         }
         val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2;

         switch (::toupper(opt[0])) {
         case 'D':
            deb = true;
            --i;
            break;
         case 'I':
            lib = val;
            break;
         case 'O':
            rootmap = val;
            break;
         default:
            return help(argv[0]);
         }
      }
   }

   if (lib.empty()) {
      cout << "ERROR occurred: input library required" << endl;
      return help(argv[0]);
   }

   if (rootmap.empty()) {
      string flib = lib;

      while ((idx = flib.find("\\")) != string::npos)
         flib.replace(idx, 1, "/");
#ifdef _WIN32

      if (flib[1] != ':' && flib[0] != '/') {
#else

      if (!(flib[0] == '/' || flib.find('/') != string::npos)) {
#endif
         flib = currpath(flib);
      }
      rootmap = ::dirnameEx(flib);
      rootmap += "/";
      string tmp = ::basenameEx(lib);

      if (tmp.rfind('.') == std::string::npos) {
         rootmap += tmp + ".rootmap";
      } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) {
         rootmap += tmp + ".rootmap";
      } else {
         rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap";
      }
   }

   if (deb) {
      cout << "Input Library: '" << lib << "'" << endl;
      cout << "ROOT Map file: '" << rootmap << "'" << endl;
   }

   if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) {
      string dir = ::dirnameEx(rootmap);

      if (deb) {
         cout << "Output directory:" << dir << "'" << endl;
      }

      if (!dir.empty() && ::stat(dir.c_str(), &buf) == -1 && errno == ENOENT) {
         if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) {
            cout << "ERR0R: error creating directory: '" << dir << "'" << endl;
            return 1;
         }
      }
   }
   out = rootmap;

   //--- Load the library -------------------------------------------------
   SharedLibrary sl(lib);

   if (!sl.Load()) {
      cout << "ERR0R: error loading library: '" << lib << "'" << endl
           << sl.Error() << endl;
      return 1;
   }

   mapGenerator map_gen(rootmap.c_str(), lib);

   if (!map_gen.good()) {
      cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl
           << sl.Error() << endl;
      return 1;
   }
   //--- Iterate over component factories ---------------------------------------
   Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS);

   if (factories) {
      map_gen.genHeader();
      set<string> used_names;

      try {
         for (Member_Iterator it = factories.FunctionMember_Begin();
              it != factories.FunctionMember_End(); ++it) {
            //string cname = it->Properties().PropertyAsString("name");
            string cname = it->Name();

            if (used_names.insert(cname).second) {
               map_gen.genFactory(cname, "");
            }
         }
         map_gen.genTrailer();
         return 0;
      }
      catch (std::exception& e) {
         cerr << "GENMAP: error creating map " << rootmap << ": "
              << e.what() << endl;
      }
      return 1;
   }
   cout << "library does not contain plugin factories" << endl;
   return 0;
} // main

//------------------------------------------------------------------------------
void
mapGenerator::genHeader() {
//------------------------------------------------------------------------------
   time_t rawtime;
   time(&rawtime);
   m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genFactory(const string& name,
                         const string& /* type */) {
//------------------------------------------------------------------------------
   string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name);

   //  for ( string::const_iterator i = name.begin(); i != name.end(); i++) {
   //   switch(*i) {
   //     case ':': { newname += '@'; break; }
   //     case ' ': { break; }
   //     default:  { newname += *i; break; }
   //   }
   //  }
   m_out << "Library." << mapname << ": " << m_lib << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genTrailer() {
//------------------------------------------------------------------------------
}
<commit_msg>Ubuntu warns about unchecked return.<commit_after>// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $

// Include files----------------------------------------------------------------
#include "Reflex/Reflex.h"
#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "../dir_manip.h"
#include <cstdlib>

#include <set>
#include <ctime>
#include <cerrno>
#include <fstream>
#include <iostream>
#include <exception>

using namespace std;
using namespace ROOT::Reflex;

class mapGenerator {
   fstream m_out;
   string m_lib;

public:
   mapGenerator(const string& file, const string& lib):
      m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc),
      m_lib(lib) {}

   bool
   good() const { return m_out.good(); }

   void genHeader();
   void genFactory(const string& name,
                   const string& type);
   void genTrailer();
};

static string
currpath(string lib) {
   char buff[PATH_MAX];
   if (!::getcwd(buff, sizeof(buff))) {
      strcpy(buff, ".");
   }
   string tmp = buff;
   tmp += "/" + lib;
   return tmp;
}

static int
help(const char* cmd) {
   cout << cmd << ":  Allowed options" << endl
        << "  -help            produce this help message" << endl
        << "  -debug           increase verbosity level" << endl
        << "  -input-library   library to extract the plugins" << endl
        << "  -output-file     output file. default <input-library>.rootmap" << endl;
   return 1;
}

//--- Command main program------------------------------------------------------
int
main(int argc,
     char** argv) {
   struct stat buf;
   bool deb = false;
   string rootmap, lib, err, out;
   string::size_type idx;

   for (int i = 1; i < argc; ++i) {
      const char* opt = argv[i], * val = 0;

      if (*opt == '/' || *opt == '-') {
         if (*++opt == '/' || *opt == '-') {
            ++opt;
         }
         val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2;

         switch (::toupper(opt[0])) {
         case 'D':
            deb = true;
            --i;
            break;
         case 'I':
            lib = val;
            break;
         case 'O':
            rootmap = val;
            break;
         default:
            return help(argv[0]);
         }
      }
   }

   if (lib.empty()) {
      cout << "ERROR occurred: input library required" << endl;
      return help(argv[0]);
   }

   if (rootmap.empty()) {
      string flib = lib;

      while ((idx = flib.find("\\")) != string::npos)
         flib.replace(idx, 1, "/");
#ifdef _WIN32

      if (flib[1] != ':' && flib[0] != '/') {
#else

      if (!(flib[0] == '/' || flib.find('/') != string::npos)) {
#endif
         flib = currpath(flib);
      }
      rootmap = ::dirnameEx(flib);
      rootmap += "/";
      string tmp = ::basenameEx(lib);

      if (tmp.rfind('.') == std::string::npos) {
         rootmap += tmp + ".rootmap";
      } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) {
         rootmap += tmp + ".rootmap";
      } else {
         rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap";
      }
   }

   if (deb) {
      cout << "Input Library: '" << lib << "'" << endl;
      cout << "ROOT Map file: '" << rootmap << "'" << endl;
   }

   if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) {
      string dir = ::dirnameEx(rootmap);

      if (deb) {
         cout << "Output directory:" << dir << "'" << endl;
      }

      if (!dir.empty() && ::stat(dir.c_str(), &buf) == -1 && errno == ENOENT) {
         if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) {
            cout << "ERR0R: error creating directory: '" << dir << "'" << endl;
            return 1;
         }
      }
   }
   out = rootmap;

   //--- Load the library -------------------------------------------------
   SharedLibrary sl(lib);

   if (!sl.Load()) {
      cout << "ERR0R: error loading library: '" << lib << "'" << endl
           << sl.Error() << endl;
      return 1;
   }

   mapGenerator map_gen(rootmap.c_str(), lib);

   if (!map_gen.good()) {
      cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl
           << sl.Error() << endl;
      return 1;
   }
   //--- Iterate over component factories ---------------------------------------
   Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS);

   if (factories) {
      map_gen.genHeader();
      set<string> used_names;

      try {
         for (Member_Iterator it = factories.FunctionMember_Begin();
              it != factories.FunctionMember_End(); ++it) {
            //string cname = it->Properties().PropertyAsString("name");
            string cname = it->Name();

            if (used_names.insert(cname).second) {
               map_gen.genFactory(cname, "");
            }
         }
         map_gen.genTrailer();
         return 0;
      }
      catch (std::exception& e) {
         cerr << "GENMAP: error creating map " << rootmap << ": "
              << e.what() << endl;
      }
      return 1;
   }
   cout << "library does not contain plugin factories" << endl;
   return 0;
} // main

//------------------------------------------------------------------------------
void
mapGenerator::genHeader() {
//------------------------------------------------------------------------------
   time_t rawtime;
   time(&rawtime);
   m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genFactory(const string& name,
                         const string& /* type */) {
//------------------------------------------------------------------------------
   string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name);

   //  for ( string::const_iterator i = name.begin(); i != name.end(); i++) {
   //   switch(*i) {
   //     case ':': { newname += '@'; break; }
   //     case ' ': { break; }
   //     default:  { newname += *i; break; }
   //   }
   //  }
   m_out << "Library." << mapname << ": " << m_lib << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genTrailer() {
//------------------------------------------------------------------------------
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>

App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //start watching ~/Dropbox folder
  BDirectory dir("/boot/home/Dropbox");
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }
}

void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
run_script(char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
      (void) printf("RAWR%s", buf);
  (void) pclose(ptr);
  return 0;
}

int
main(void)
{
  //Haiku make window code
  App *app = new App();

  //run some Dropbox code
  run_script("python db_ls.py");
  app->Run();
  delete app;
  return 0;
}
<commit_msg>moved python script call into message handler<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>

App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //start watching ~/Dropbox folder
  BDirectory dir("/boot/home/Dropbox");
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }
}

int
run_script(char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
      (void) printf("RAWR%s", buf);
  (void) pclose(ptr);
  return 0;
}

void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            run_script("python db_ls.py");
            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
main(void)
{
  //Haiku make window code
  App *app = new App();

  app->Run();
  delete app;
  return 0;
}
<|endoftext|>