コード例 #1
0
ファイル: scriptdef_module.cpp プロジェクト: Weooh/kbengine
//-------------------------------------------------------------------------------------
void ScriptDefModule::autoMatchCompOwn()
{
	/*
		entity存在某部分(cell, base, client)的判定规则

		1: entitydef文件中存在实体某部分的方法或者属性,同时也必须也存在py脚本
		2: 用户在entities.xml明确声明存在某实体部分(为了unity3d或者html5类的前端无法加载py的环境考虑)
			entities.xml, <Spaces hasCell="true" hasClient="false", hasBase="true"></Spaces>
	*/

	std::string entitiesFile = Resmgr::getSingleton().getPyUserScriptsPath() + "entities.xml";

	// 打开这个entities.xml文件
	SmartPointer<XML> xml(new XML());
	if(!xml->openSection(entitiesFile.c_str()) || !xml->isGood())
		return;
	
	// 获得entities.xml根节点, 如果没有定义一个entity那么直接返回true
	TiXmlNode* node = xml->getRootNode();
	if(node == NULL)
		return;

	int assertionHasClient = -1;
	int assertionHasBase = -1;
	int assertionHasCell = -1;

	// 开始遍历所有的entity节点
	XML_FOR_BEGIN(node)
	{
		std::string moduleName = xml.get()->getKey(node);
		if(name_ == moduleName)
		{
			const char* val = node->ToElement()->Attribute("hasClient");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasClient = 1;
				else
					assertionHasClient = 0;
			}

			EntityDef::md5().append((void*)&assertionHasClient, sizeof(int));

			val = node->ToElement()->Attribute("hasCell");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasCell = 1;
				else
					assertionHasCell = 0;
			}

			EntityDef::md5().append((void*)&assertionHasCell, sizeof(int));

			val = node->ToElement()->Attribute("hasBase");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasBase = 1;
				else
					assertionHasBase = 0;
			}

			EntityDef::md5().append((void*)&assertionHasBase, sizeof(int));
			break;
		}
	}
	XML_FOR_END(node);

	std::string fmodule = "scripts/client/" + name_ + ".py";
	std::string fmodule_pyc = fmodule + "c";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		if (assertionHasClient < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在客户端属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setClient(true);
		}
		else
		{
			// 用户明确声明并进行了设定
			setClient(assertionHasClient == 1);
		}
	}
	else
	{
		if(assertionHasClient < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在客户端属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setClient(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setClient(assertionHasClient == 1);
		}
	}

	if(g_componentType == CLIENT_TYPE)
	{
		setBase(true);
		setCell(true);
		return;
	}

	fmodule = "scripts/base/" + name_ + ".py";
	fmodule_pyc = fmodule + "c";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		if (assertionHasBase < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在base属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setBase(true);
		}
		else
		{
			// 用户明确声明并进行了设定
			setBase(assertionHasBase == 1);
		}
	}
	else
	{
		if(assertionHasBase < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在base属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setBase(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setBase(assertionHasBase == 1);
		}
	}

	fmodule = "scripts/cell/" + name_ + ".py";
	fmodule_pyc = fmodule + "c";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		if (assertionHasCell < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在cell属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setCell(true);
		}
		else
		{
			// 用户明确声明并进行了设定
			setCell(assertionHasCell == 1);
		}
	}
	else
	{
		if(assertionHasCell < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在cell属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setCell(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setCell(assertionHasCell == 1);
		}
	}
}
コード例 #2
0
int main( int argc, char** argv )
{
  if(argc != 3)
  {
    printf("Usage: %s <robot_xml> <controller_xml>\n",argv[0]);
    exit(-1);
  }
  printf("robot file:: %s, controller file:: %s\n",argv[1],argv[2]);


  /*********** Create the robot model ****************/
  mechanism::Robot *robot_model = new mechanism::Robot;
  controller::BaseControllerNode bc;
  HardwareInterface hw(0);
  robot_model->hw_ = &hw;


  /*********** Initialize ROS  ****************/
  ros::init(argc,argv);
  ros::node *node = new ros::node("test_base_controller"); 


  /*********** Load the robot model and state file ************/
  char *xml_robot_file = argv[1];
  TiXmlDocument xml(xml_robot_file);   // Load robot description
  xml.LoadFile();
  TiXmlElement *root = xml.FirstChildElement("robot");
  urdf::normalizeXml(root);
  robot_model->initXml(root);
  mechanism::RobotState *robot_state = new mechanism::RobotState(robot_model, &hw);


  /*********** Load the controller file ************/
  char *xml_control_file = argv[2];
  TiXmlDocument xml_control(xml_control_file);   // Load robot description
  xml_control.LoadFile();
  TiXmlElement *root_control = xml_control.FirstChildElement("controllers");
  TiXmlElement *root_controller = root_control->FirstChildElement("controller");  
  bc.initXml(robot_state,root_controller);


  /************ Testing the odometry calculations themselves ******************/
/*  NEWMAT::Matrix A(16,3);

  A.Row(1) << 10 << 8.95 << 0.05;
  A.Row(2) << 0 <<  -2 << 0;
  A.Row(3) << 1 << -0.1 << 0.01;
  A.Row(4) << 2 << 1.1 << 0;

  A.Row(5) << 3 << 2 << -0.05;
  A.Row(6) << 4 << 3 << 0.01;
  A.Row(7) << 5 << 4.1 << 0.05;
  A.Row(8) << -1 << -2 << 0.025;

  A.Row(9) << 6.15 << 5.05 << 0.01;
  A.Row(10) << 6.985 << 6.02 << 0.01;
  A.Row(11) << 8.01 << 8.05 << -0.05;
  A.Row(12) << 9.03 << 8.1 << -0.01;

  A.Row(13) << -8.03 << -9.1 << 0.01;
  A.Row(14) << -10.03 << -13.1 << 0.05;
  A.Row(15) << -15.03 << -16.1 << -0.015;
  A.Row(16) << -16.03 << -17.1 << -0.01;

  NEWMAT::Matrix B(16,1);
  B << 1.1 << 1 << 1.1 << 1.15 << 0.95 << 0.99 << 0.98 << 0.95 << 1.05 << 1.1 << 1.05 << 1 << 1.13 << 0.995 << 1.035 << 1.08;
  NEWMAT::Matrix xfit(3,1);

  xfit = bc.c_->iterativeLeastSquares(A,B,"Gaussian",10);
  cout << "done" << xfit << endl;
*/  
  ros::fini();
  delete robot_model;
  delete robot_state;
}
コード例 #3
0
ファイル: libmusicxml.cpp プロジェクト: iloveican/AscoGraph
static Sxmlelement		__releaseElt  (TElement elt)					{ Sxmlelement xml(elt); elt->removeReference(); return xml; }
コード例 #4
0
ファイル: downloader.cpp プロジェクト: SpliFF/springlobby
PlasmaResourceInfo PlasmaInterface::ParseResourceInfoData( const int buffer_index )
{
    PlasmaResourceInfo info;
    wxString wxbuf = m_buffers[buffer_index];

    wxString t_begin = _T("<soap:Envelope");
    wxString t_end = _T("</soap:Envelope>");
    wxString xml_section = wxbuf.Mid( wxbuf.Find( t_begin ) );//first char after t_begin to one before t_end

    wxStringInputStream str_input( xml_section );
    wxXmlDocument xml( str_input );
	ASSERT_EXCEPTION( xml.GetRoot(), _T("Plasma: XMLparser: no root") );
    wxXmlNode *node = xml.GetRoot()->GetChildren();
	ASSERT_EXCEPTION( node , _T("Plasma: XMLparser: no first node") );
    wxString resourceType ( _T("unknown") );
    node = node->GetChildren();
	ASSERT_EXCEPTION( node , _T("Plasma: XMLparser: no node") );
    while ( node ) {
        wxString node_name = node->GetName();
        if ( node_name == _T("DownloadFileResponse") ) {
            wxXmlNode* downloadFileResult = node->GetChildren();
			ASSERT_EXCEPTION( downloadFileResult, _T("Plasma: XMLparser: no result section") );
            wxString result = downloadFileResult->GetNodeContent();
            //check result
            wxXmlNode* links = downloadFileResult->GetNext();
			ASSERT_EXCEPTION( links, _T("Plasma: XMLparser: no webseed section") );
            wxXmlNode* url = links->GetChildren();
            while ( url ) {
				wxString seed_url = url->GetNodeContent();
				seed_url.Replace(_T(" "),_T("%20"));
				info.m_webseeds.Add( seed_url );
                url = url->GetNext();
            }
            wxXmlNode* next = links->GetNext();
            while ( next ) {
                wxString next_name = next->GetName();
                if ( next_name == _T("torrentFileName") ) {
                    info.m_torrent_filename = next->GetNodeContent();
                }
                else if ( next_name == _T("dependencies") ) {
                    wxXmlNode* deps = next->GetChildren();
                    while ( deps ) {
                        info.m_dependencies.Add( deps->GetNodeContent() );
                        deps = deps->GetNext();
                    }
                }
                else if ( next_name == _T("resourceType") ) {
                    resourceType = next->GetNodeContent();
                    if ( resourceType == _T("Mod") )
                        info.m_type = PlasmaResourceInfo::mod;
                    else if ( resourceType == _T("Map") )
                        info.m_type = PlasmaResourceInfo::map;
                    else
						info.m_type = PlasmaResourceInfo::unknown;
                }
                next = next->GetNext();
            }
            break;
        } // end section <DownloadFileResponse/>
        node = node->GetNext();
    }
    wxString seeds;
    for ( size_t i = 0; i < info.m_webseeds.Count(); ++i )
        seeds += info.m_webseeds[i] + _T("\n");

    return info;
}
コード例 #5
0
ファイル: WinImplBase.cpp プロジェクト: shantj/duilib
LRESULT WindowImplBase::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
	styleValue &= ~WS_CAPTION;
	::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
	RECT rcClient;
	::GetClientRect(*this, &rcClient);
	::SetWindowPos(*this, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, \
		rcClient.bottom - rcClient.top, SWP_FRAMECHANGED);

	m_PaintManager.Init(m_hWnd);
	m_PaintManager.AddPreMessageFilter(this);

	CDialogBuilder builder;
	CDuiString strResourcePath=m_PaintManager.GetResourcePath();
	if (strResourcePath.IsEmpty())
	{
		strResourcePath=m_PaintManager.GetInstancePath();
		strResourcePath+=GetSkinFolder().GetData();
	}
	m_PaintManager.SetResourcePath(strResourcePath.GetData());

	switch(GetResourceType())
	{
	case UILIB_ZIP:
		m_PaintManager.SetResourceZip(GetZIPFileName().GetData(), true);
		break;
	case UILIB_ZIPRESOURCE:
		{
			HRSRC hResource = ::FindResource(m_PaintManager.GetResourceDll(), GetResourceID(), _T("ZIPRES"));
			if( hResource == NULL )
				return 0L;
			DWORD dwSize = 0;
			HGLOBAL hGlobal = ::LoadResource(m_PaintManager.GetResourceDll(), hResource);
			if( hGlobal == NULL ) 
			{
#if defined(WIN32) && !defined(UNDER_CE)
				::FreeResource(hResource);
#endif
				return 0L;
			}
			dwSize = ::SizeofResource(m_PaintManager.GetResourceDll(), hResource);
			if( dwSize == 0 )
				return 0L;
			m_lpResourceZIPBuffer = new BYTE[ dwSize ];
			if (m_lpResourceZIPBuffer != NULL)
			{
				::CopyMemory(m_lpResourceZIPBuffer, (LPBYTE)::LockResource(hGlobal), dwSize);
			}
#if defined(WIN32) && !defined(UNDER_CE)
			::FreeResource(hResource);
#endif
			m_PaintManager.SetResourceZip(m_lpResourceZIPBuffer, dwSize);
		}
		break;
	}

	CControlUI* pRoot=NULL;
	if (GetResourceType()==UILIB_RESOURCE)
	{
		STRINGorID xml(_ttoi(GetSkinFile().GetData()));
		pRoot = builder.Create(xml, _T("xml"), this, &m_PaintManager);
	}
	else
		pRoot = builder.Create(GetSkinFile().GetData(), (UINT)0, this, &m_PaintManager);
	ASSERT(pRoot);
	if (pRoot==NULL)
	{
		MessageBox(NULL,_T("加载资源文件失败"),_T("Duilib"),MB_OK|MB_ICONERROR);
		ExitProcess(1);
		return 0;
	}
	m_PaintManager.AttachDialog(pRoot);
	m_PaintManager.AddNotifier(this);

	InitWindow();
	return 0;
}
コード例 #6
0
/////////////////////////////////////////////////////////////////////////////
// CMaxMaterialCollection
STDMETHODIMP CMaxMaterialCollection::FinalConstruct()
{
	HRESULT hr = E_FAIL, hr2 = E_FAIL;
	//simply make a reference to the scene material collection
	MtlBaseLib* pMtlLib = GetCOREInterface()->GetSceneMtls();
	mLastSceneMtlLibSize = 0;

#ifdef PERSIST_SCRATCH
	mpScratchMtlLib = NULL;
#endif

	assert(pMtlLib);

	//RK: 10/21/04 -- this forces ACT toolkit to initialize at startup and avoids delays during material assignment.
	CComDispatchDriver act;
	/*
		FIXME: Use the .NET wrappers directly instead of this;
		act.CoCreateInstance( L"Autodesk.Act.Core.ContentSerializer" );

		For some reason, the prog ID above is not being registered with the version
		we now install with Max 9, and I've had to resort to using the CLSID directly.

		Either we have the wrong version, or the new DLL just doesn't register its
		prog ID.  (more likely it's the former)
	*/
	CLSID clsidCore;
	hr = CLSIDFromString(L"{978C551B-5919-42F7-81AB-690D66AB7B78}", &clsidCore);

	if( SUCCEEDED(hr) )
		hr = act.CoCreateInstance( clsidCore );

	if (SUCCEEDED(hr))
	{
		CComVariant xml(L"<Material><StandardMtl name=\"Test\" /></Material>");
		CComPtr<IUnknown> mtl;
		hr2 = mtl.CoCreateInstance( L"Autodesk.Act.Content.Material");
		hr2 = act.Invoke1( L"DeserializeString", &xml );
	}
	if ( FAILED(hr) || FAILED(hr2) )
	{
		if (GetCOREInterface()->GetQuietMode())
			GetCOREInterface()->Log()->LogEntry(SYSLOG_ERROR,NO_DIALOG, TSTR(GetString(IDS_PROJNAME)), TSTR(GetString(IDS_ACT_REGISTRATION_FAILED)));
		else
			MaxMsgBox( GetCOREInterface()->GetMAXHWnd(), TSTR(GetString(IDS_ACT_REGISTRATION_FAILED)), TSTR(GetString(IDS_PROJNAME)), MB_OK );
	}
	assert(SUCCEEDED(hr) && SUCCEEDED(hr2));

	//RK: This forces XMlmtl to initialize at startup.
	CComPtr<IVIZPointerClient> pPointerClient;
	hr = GetXMLImpExp(&pPointerClient);
	assert(SUCCEEDED(hr));

#ifdef RECYCLE_MATS
#endif

	RegisterNotification(NotifyProc, this, NOTIFY_FILE_PRE_OPEN);
	RegisterNotification(NotifyProc, this, NOTIFY_FILE_POST_OPEN);
    RegisterNotification(NotifyProc, this, NOTIFY_FILE_OPEN_FAILED);
	RegisterNotification(NotifyProc, this, NOTIFY_FILE_PRE_MERGE);
	RegisterNotification(NotifyProc, this, NOTIFY_FILE_POST_MERGE);
	RegisterNotification(NotifyProc, this, NOTIFY_FILE_PRE_SAVE);
	RegisterNotification(NotifyProc, this, NOTIFY_FILE_POST_SAVE);
	RegisterNotification(NotifyProc, this, NOTIFY_PRE_IMPORT);
	RegisterNotification(NotifyProc, this, NOTIFY_POST_IMPORT);
	RegisterNotification(NotifyProc, this, NOTIFY_SYSTEM_PRE_NEW);
	RegisterNotification(NotifyProc, this, NOTIFY_SYSTEM_POST_NEW);
	RegisterNotification(NotifyProc, this, NOTIFY_SYSTEM_PRE_RESET);
	RegisterNotification(NotifyProc, this, NOTIFY_SYSTEM_POST_RESET);
	RegisterNotification(NotifyProc, this, NOTIFY_SCENE_UNDO);
	RegisterNotification(NotifyProc, this, NOTIFY_SCENE_REDO);
#ifdef SUSPEND_UNDO
	RegisterNotification(NotifyProc, this, NOTIFY_SCENE_PRE_UNDO);
	RegisterNotification(NotifyProc, this, NOTIFY_SCENE_PRE_REDO);
#endif

	RegisterNotification(NotifyProc, (void *)this, NOTIFY_MEDIT_SHOW);

#ifdef TP_SUSPEND_FOR_FILELINK
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_PRE_BIND		);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_POST_BIND	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_PRE_DETACH	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_POST_DETACH	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_PRE_RELOAD	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_POST_RELOAD	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_PRE_ATTACH	);
	RegisterNotification(NotifyProc, this, NOTIFY_FILELINK_POST_ATTACH	);
#endif

	//and finally a mechanism for other parts of the system to actively suspend TP
	RegisterNotification(NotifyProc, this, NOTIFY_TOOLPALETTE_MTL_SUSPEND	);
	RegisterNotification(NotifyProc, this, NOTIFY_TOOLPALETTE_MTL_RESUME	);

	//for DID 642266, pre and post cloning 
	RegisterNotification(NotifyProc, this, NOTIFY_PRE_NODES_CLONED	);
	RegisterNotification(NotifyProc, this, NOTIFY_POST_NODES_CLONED	);
	


	RefResult res = ReplaceReference(SCENE_MTLLIB_REFNUM, (RefTargetHandle) pMtlLib);
#ifdef PERSIST_SCRATCH
	res = ReplaceReference(SCRATCH_MTLLIB_REFNUM, (RefTargetHandle) &theScratchMtlLib);
#endif

	Resume();
	if(res == REF_SUCCEED)
		hr = S_OK;
	return hr;
}
コード例 #7
0
ファイル: EventCanvas.cpp プロジェクト: ViktorNova/los
QMimeData* EventCanvas::getTextDrag()
{
    //---------------------------------------------------
    //   generate event list from selected events
    //---------------------------------------------------

    EventList el;
    unsigned startTick = MAXINT;
    for (iCItem i = _items.begin(); i != _items.end(); ++i)
    {
        if (!i->second->isSelected())
            continue;
        ///NEvent* ne = (NEvent*)(i->second);
        CItem* ne = i->second;
        Event e = ne->event();
        if (startTick == MAXINT)
            startTick = e.tick();
        el.add(e);
    }

    //---------------------------------------------------
    //    write events as XML into tmp file
    //---------------------------------------------------

    FILE* tmp = tmpfile();
    if (tmp == 0)
    {
        fprintf(stderr, "EventCanvas::getTextDrag() fopen failed: %s\n",
                strerror(errno));
        return 0;
    }
    Xml xml(tmp);

    int level = 0;
    xml.tag(level++, "eventlist");
    for (ciEvent e = el.begin(); e != el.end(); ++e)
        e->second.write(level, xml, -startTick);
    xml.etag(--level, "eventlist");

    //---------------------------------------------------
    //    read tmp file into drag Object
    //---------------------------------------------------

    fflush(tmp);
    struct stat f_stat;
    if (fstat(fileno(tmp), &f_stat) == -1)
    {
        fprintf(stderr, "PianorollCanvas::copy() fstat failes:<%s>\n",
                strerror(errno));
        fclose(tmp);
        return 0;
    }
    int n = f_stat.st_size;
    char* fbuf = (char*) mmap(0, n + 1, PROT_READ | PROT_WRITE,
                              MAP_PRIVATE, fileno(tmp), 0);
    fbuf[n] = 0;

    QByteArray data(fbuf);
    QMimeData* md = new QMimeData();
    //QDrag* drag = new QDrag(parent);

    md->setData("text/x-los-eventlist", data);
    //drag->setMimeData(md);

    munmap(fbuf, n);
    fclose(tmp);

    //return drag;
    return md;
}
コード例 #8
0
TEST(AudioCDReaderHelper, getIntValueForKey) {
  XmlDocument doc("<dict><key>foo</key><value>123</value></dict>");
  scoped_ptr<XmlElement> xml(doc.getDocumentElement());
  EXPECT_EQ(getIntValueForKey(*xml, "bar"), -1);
  EXPECT_EQ(getIntValueForKey(*xml, "foo"), 123);
}
コード例 #9
0
void DACCalibration::readCalibrationFile(){

    QString l_strFilename="ICMCalibration.xml";

    QFile *xmlFile= new QFile(l_strFilename);
            if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
                 qDebug()<<"calibration file read error";
            }
            if(!xmlFile->exists()){
                for(int x=0;x<5;x++){           m_nXVoltage[x]=0.0; m_nYVoltage[x]=0.0;
                    for(int y=0;y<9;y++){
                        for(int z=0;z<5;z++){   XVoltage[x][y][z]=0.0;YVoltage[x][y][z]=0.0;
                        } } }


                for(int x=0;x<5;x++){
                       for(int y=0;y<9;y++){       m_nSlope[x][y]=1.0; m_nConstant[x][y]=0.0;
                           for(int z=0;z<5;z++){
                           } } }
            }

            QXmlStreamReader xml(xmlFile);
            short int index=0,RIndex=0,LIndex=0,CIndex=0;
            while(!xml.atEnd() &&  !xml.hasError())
            {
                QXmlStreamReader::TokenType token = xml.readNext();
                QXmlStreamAttributes attributes = xml.attributes();

                if(token == QXmlStreamReader::StartDocument)
                {
                    continue;
                }
                if(xml.isStartElement())
                {

                    if(xml.name()=="ICM-R"){
                                        m_nSlope[0][RIndex]=xml.attributes().value("Slope").toString().toDouble();
                                        m_nConstant[0][RIndex]=xml.attributes().value("Constant").toString().toDouble();

                                        xml.readNextStartElement();
                                        if(xml.isStartElement())
                                        {
                                            if(xml.name()=="range"){
                                                XVoltage[0][RIndex][0]=xml.attributes().value("X1Value").toString().toDouble();
                                                YVoltage[0][RIndex][0]=xml.attributes().value("Y1Value").toString().toDouble();
                                                XVoltage[0][RIndex][1]=xml.attributes().value("X2Value").toString().toDouble();
                                                YVoltage[0][RIndex][1]=xml.attributes().value("Y2Value").toString().toDouble();

                                            }
                                        }

                                        RIndex++;

                                   }
                    if(xml.name()=="ICM-L"){
                                        m_nSlope[1][LIndex]=xml.attributes().value("Slope").toString().toDouble();
                                        m_nConstant[1][LIndex]=xml.attributes().value("Constant").toString().toDouble();
                                        xml.readNextStartElement();
                                        if(xml.isStartElement())
                                        {
                                            if(xml.name()=="range"){
                                                XVoltage[1][LIndex][0]=xml.attributes().value("X1Value").toString().toDouble();
                                                YVoltage[1][LIndex][0]=xml.attributes().value("Y1Value").toString().toDouble();
                                                XVoltage[1][LIndex][1]=xml.attributes().value("X2Value").toString().toDouble();
                                                YVoltage[1][LIndex][1]=xml.attributes().value("Y2Value").toString().toDouble();
                                            }
                                        }
                                        LIndex++;

                                   }
                    if(xml.name()=="ICM-C"){
                                        m_nSlope[2][CIndex]=xml.attributes().value("Slope").toString().toDouble();
                                        m_nConstant[2][CIndex]=xml.attributes().value("Constant").toString().toDouble();
                                        xml.readNextStartElement();
                                        if(xml.isStartElement())
                                        {
                                            if(xml.name()=="range"){
                                                XVoltage[2][CIndex][0]=xml.attributes().value("X1Value").toString().toDouble();
                                                YVoltage[2][CIndex][0]=xml.attributes().value("Y1Value").toString().toDouble();
                                                XVoltage[2][CIndex][1]=xml.attributes().value("X2Value").toString().toDouble();
                                                YVoltage[2][CIndex][1]=xml.attributes().value("Y2Value").toString().toDouble();
                                            }
                                        }
                                        CIndex++;
                                   }

                }
            }
    if(xml.hasError())
            qDebug()<<"xmlFile.xml Parse Error";

    xml.clear();
    xmlFile->close();

    for(int x=0;x<6;x++){
            qDebug()<<"m_nSlope"<<m_nSlope[0][x];
            qDebug()<<"m_nConstant"<<m_nConstant[0][x];
            for(int y=0;y<2;y++){
                qDebug()<<"XVoltage"<<XVoltage[0][x][y];
                qDebug()<<"YVoltage"<<YVoltage[0][x][y];
            }
    }
    for(int x=0;x<7;x++){
            qDebug()<<"m_nSlope"<<m_nSlope[1][x];
            qDebug()<<"m_nConstant"<<m_nConstant[1][x];
            for(int y=0;y<2;y++){
                qDebug()<<"XVoltage"<<XVoltage[1][x][y];
                qDebug()<<"YVoltage"<<YVoltage[1][x][y];
            }
    }
    for(int x=0;x<9;x++){
            qDebug()<<"m_nSlope"<<m_nSlope[2][x];
            qDebug()<<"m_nConstant"<<m_nConstant[2][x];
            for(int y=0;y<2;y++){
                qDebug()<<"XVoltage"<<XVoltage[2][x][y];
                qDebug()<<"YVoltage"<<YVoltage[2][x][y];
            }
    }


}
コード例 #10
0
ファイル: coord_xml_t.cpp プロジェクト: aivarszo/mapper
void CoordXmlTest::readHumanReadableStream()
{
	namespace literal = XmlStreamLiteral;
	
	QFETCH(int, num_coords);
	MapCoordVector coords(num_coords, proto_coord);
	
	buffer.buffer().truncate(0);
	QBuffer header;
	{
		QXmlStreamWriter xml(&header);
		
		header.open(QBuffer::ReadWrite);
		xml.setAutoFormatting(false);
		xml.writeStartDocument();
		xml.writeStartElement("root");
		xml.writeCharacters(""); // flush root start element
		
		buffer.open(QBuffer::ReadWrite);
		xml.setDevice(&buffer);
		xml.writeStartElement("coords");
		// Using the more efficient string implementation.
		writeHumanReadableString_implementation(coords, xml);
		xml.writeEndElement();
		
		xml.setDevice(NULL);
		
		buffer.close();
		header.close();
	}
	
	header.open(QBuffer::ReadOnly);
	buffer.open(QBuffer::ReadOnly);
	QXmlStreamReader xml;
	xml.addData(header.buffer());
	xml.readNextStartElement();
	QCOMPARE(xml.name().toString(), QString("root"));
	
	bool failed = false;
	QBENCHMARK
	{
		// benchmark iteration overhead
		coords.clear();
		xml.addData(buffer.data());
		
		xml.readNextStartElement();
		if (xml.name() != "coords")
		{
			failed = true;
			break;
		}
		
		for( xml.readNext();
		     xml.tokenType() != QXmlStreamReader::EndElement;
		     xml.readNext() )
		{
			if (xml.error())
			{
				qDebug() << xml.errorString();
				failed = true;
				break;
			}
			
			const QXmlStreamReader::TokenType token = xml.tokenType();
			if (token == QXmlStreamReader::EndDocument)
			{
				failed = true;
				break;
			}
			
			if (token == QXmlStreamReader::Characters && !xml.isWhitespace())
			{
				QStringRef text = xml.text();
				QString data = QString::fromRawData(text.constData(), text.length());
				QTextStream stream(&data, QIODevice::ReadOnly);
				stream.setIntegerBase(10);
				while (!stream.atEnd())
				{
					qint32 x, y;
					int flags = 0;
					char separator;
					stream >> x >> y >> separator;
					if (separator != ';')
					{
						stream >> flags >> separator;
					}
					coords.push_back(MapCoord::fromNative(x, y, flags));
				}
				if (stream.status() == QTextStream::ReadCorruptData)
				{
					failed = true;
					break;
				}
			}
			// otherwise: ignore element
		}
コード例 #11
0
/**
 * Method to get the result for a network request.
 * @param aOperation The type of operation to be requested
 * @param aTransportResult The result of transport operation
 * @param aResponse The QByteArray instance containing the network response.
 * The plugins should delete this instance once they have read the 
 * data from it.
 * @param aResult [out] An output parameter to the plugin manager.If the 
 * return value is SmfSendRequestAgain, QVariant will be of type 
 * SmfPluginRequestData.
 * For SmfGalleryPlugin: If last operation was pictures(), aResult will 
 * be of type QList<SmfPicture>. If last operation was description(), 
 * aResult will be of type QString. If last operation was upload() or 
 * postComment(), aResult will be of type bool.
 * @param aRetType [out] SmfPluginRetType
 * @param aPageResult [out] The SmfResultPage structure variable
 */
SmfPluginError FlickrContactFetcherPlugin::responseAvailable( 
		const SmfRequestTypeID aOperation,
		const SmfTransportResult &aTransportResult, 
		QByteArray *aResponse, 
		QVariant* aResult, 
		SmfPluginRetType &aRetType,
		SmfResultPage &aPageResult )
	{
	Q_UNUSED(aPageResult)
	qDebug()<<"Inside FlickrContactFetcherPlugin::responseAvailable()";
	
	SmfPluginError error = SmfPluginErrNetworkError;
	
	if( !aResponse || (0 == aResponse->size()) )
		{
		qDebug()<<"Response is NULL or empty";
		aRetType = SmfRequestError;
		return error;
		}
	
	QByteArray response(*aResponse);
	delete aResponse;
	
	QFile respFile("c://data//SmfPluginFlickrContactResponse.txt");
	if(!respFile.open(QIODevice::WriteOnly))
		{
		qDebug()<<"File to write the response could not be opened, so writing to this file";
		qDebug()<<"Flickr response = "<<QString(response);
		}
	else
		{
		respFile.write(response);
		respFile.close();
		qDebug()<<"Writing FB response to a file named 'SmfPluginFlickrContactResponse.txt'";
		}
	qDebug()<<"FB response size = "<<response.size();
	
	if(SmfTransportOpNoError == aTransportResult)
		{
		qDebug()<<"No transport error";
		
#ifndef TESTINGTHISFUNCTION	
		if(SmfContactGetFriends == aOperation)
#else
		if(SmfContactGetFriends == aOperation ||aOperation == SmfContactGetFollowers||aOperation== SmfContactSearch ||aOperation ==SmfContactSearchNear||aOperation ==SmfContactSearchInGroup)
#endif
			{
			qDebug()<<"For getting friends response";
			
			QList<SmfContact> list;
			
#ifdef SMF_XMLPARSING // Xml parsing
			// For getting contacts from xml response
			QXmlStreamReader xml(response);
			while (!xml.atEnd())
				{
				xml.readNext();
				if (xml.tokenType() == QXmlStreamReader::StartElement)
					{
					// If the tag is contact
					if (xml.name() == "contact")
						{
						qDebug()<<"Contact tag found";
						SmfContact contact;
						QStringRef str;
						QContactName contactname;
						QString username = xml.attributes().value("username").toString();
						qDebug()<<"Username = "******"Name",namevar1);
						list.append(contact);
						}
					}
				}
#else
			// To remove the "jsonFlickrApi(" and also remove the last ")" from the response,
			// as these gives a Json parsing error
			response.remove(0, 14);
			response.chop(1);
			
			// For getting contacts from json response
			bool ok;
			SmfPluginUtil util;
			QVariantMap result = util.parse(response, &ok).toMap();
			if (!ok) {
				qDebug()<<"An error occurred during json parsing";
				aResult->setValue(list);
				aRetType = SmfRequestError;
				return SmfPluginErrParsingFailed;
			}
			
			QVariantMap map1 = result["contacts"].toMap();
			qDebug()<<"page = "<<map1["page"].toString();
			qDebug()<<"pages = "<<map1["pages"].toString();
			qDebug()<<"per_page = "<<map1["per_page"].toString();
			qDebug()<<"perpage = "<<map1["perpage"].toString();
			qDebug()<<"total = "<<map1["perpage"].toString();
			
			QList<QVariant> list1 = map1["contact"].toList();
			
			QListIterator<QVariant> i(list1);
			while(i.hasNext())
				{
				SmfContact contact;
				QVariantMap map2 = i.next().toMap();
				qDebug()<<"nsid = "<<map2["nsid"].toString();
				qDebug()<<"username = "******"username"].toString();
				qDebug()<<"iconserver = "<<map2["iconserver"].toString();
				qDebug()<<"iconfarm = "<<map2["iconfarm"].toString();
				qDebug()<<"ignored = "<<map2["ignored"].toString();
				qDebug()<<"realname = "<<map2["realname"].toString();
				qDebug()<<"friend = "<<map2["friend"].toString();
				qDebug()<<"family = "<<map2["family"].toString();
				qDebug()<<"path_alias = "<<map2["path_alias"].toString();
				qDebug()<<"location = "<<map2["location"].toString();
				
				// Contact Name
				QContactName contactname;
				QString username = map2["username"].toString();
				qDebug()<<"Username = "******"Name",nameVar);
				
				// Contact's Flickr Specific ID to QContactGuid
				QContactGuid guid;
				guid.setGuid(map2["nsid"].toString());
				QVariant guidVar = QVariant::fromValue(guid);
				contact.setValue("Guid",guidVar);
					
				// Contact's profile image url
				QUrl url;
				if((0 == map2["iconfarm"].toInt()) && (0 == map2["iconserver"].toInt()))
					url = QString("http://www.flickr.com/images/buddyicon.jpg");
				else
					{
					QString str("http://farm");
					str.append(map2["iconfarm"].toString());
					str.append(".static.flickr.com/");
					str.append(map2["iconserver"].toString());
					str.append("/buddyicons/");
					str.append(map2["nsid"].toString());
					str.append(".jpg");
					url = str;
					}
				QContactAvatar avatar;
				qDebug()<<"Profile image URL = "<<url.toString();
				avatar.setImageUrl(url);
				QVariant avatarVar = QVariant::fromValue(avatar);
				contact.setValue("Avatar",avatarVar);
				
				
				list.append(contact);
				}
#endif
			
			qDebug()<<"list count = "<<list.count();
			aResult->setValue(list);
			aRetType = SmfRequestComplete;
			error = SmfPluginErrNone;
			}
		else if(aOperation==SmfContactGetGroups)
			{
		        response.remove(0, 14);
				response.chop(1);
			
			    bool ok;
				qDebug()<<"Before Parser--";

				SmfPluginUtil util;
				QVariant result = util.parse(response, &ok);
				if (!ok) 
				{
				    qDebug()<<"An error occurred during json parsing";
					aRetType = SmfRequestError;
					return SmfPluginErrParsingFailed;
								 //return 0;
				}
							
				QVariantMap map1 = result.toMap();
		        QList<SmfGroup> list;
				QVariantMap map2 = map1["groups"].toMap();
				int page = map2["page"].toInt(&ok);
				qDebug()<<"PAGE = "<<map2["page"].toString();
				QList<QVariant> list1 = map2["group"].toList();
				QListIterator<QVariant> iter(list1);
						
				//Getting the group list from QJson Parser 
				 while(iter.hasNext())
				 {
					QVariantMap map2 = iter.next().toMap();
					qDebug()<<"name = "<<map2["name"].toString();
					qDebug()<<"id = "<<map2["id"].toString();
					SmfGroup group;
					QString id(map2["id"].toString());
					group.setId(id);
					QString grpname(map2["name"].toString());
					group.setName(grpname);
						   
					list.append(group);
						   
				 }//end While
				 qDebug()<<"list count = "<<QString::number(list.count(),10);
				aResult->setValue(list);
			}
		else
			{
			qDebug()<<"Service unsupported, currently only SmfContactGetFriends !!!";
			aRetType = SmfRequestError;
			error = SmfPluginErrServiceNotSupported;
			}
		}

	else if(SmfTransportOpOperationCanceledError == aTransportResult)
		{
		qDebug()<<"Operation Cancelled !!!";
		error = SmfPluginErrCancelComplete;
		aRetType = SmfRequestComplete;
		}

	else
		{
		qDebug()<<"Transport Error !!!";
		error = SmfPluginErrNetworkError;
		aRetType = SmfRequestError;
		}
	
	return error;
	}
コード例 #12
0
ファイル: coord_xml_t.cpp プロジェクト: aivarszo/mapper
void CoordXmlTest::readXml()
{
	QFETCH(int, num_coords);
	MapCoordVector coords(num_coords, proto_coord);
	
	buffer.buffer().truncate(0);
	QBuffer header;
	{
		QXmlStreamWriter xml(&header);
		
		header.open(QBuffer::ReadWrite);
		xml.setAutoFormatting(false);
		xml.writeStartDocument();
		xml.writeStartElement("root");
		xml.writeCharacters(" "); // flush root start element
		
		buffer.open(QBuffer::ReadWrite);
		xml.setDevice(&buffer);
		xml.writeStartElement("coords");
		writeXml_implementation(coords, xml);
		xml.writeEndElement(/* coords */);
		
		xml.setDevice(NULL);
		
		buffer.close();
		header.close();
	}
	
	header.open(QBuffer::ReadOnly);
	buffer.open(QBuffer::ReadOnly);
	QXmlStreamReader xml;
	xml.addData(header.buffer());
	xml.readNextStartElement();
	QCOMPARE(xml.name().toString(), QString("root"));
	
	bool failed = false;
	QBENCHMARK
	{
		// benchmark iteration overhead
		coords.clear();
		xml.addData(buffer.data());
		
		xml.readNextStartElement();
		if (xml.name() != "coords")
		{
			failed = true;
			break;
		}
		
		while(xml.readNextStartElement())
		{
			if (xml.name() != XmlStreamLiteral::coord)
			{
				failed = true;
				break;
			}
			
			XmlElementReader element(xml);
			auto x = element.attribute<qint32>(literal::x);
			auto y = element.attribute<qint32>(literal::y);
			auto flags = element.attribute<int>(literal::flags);
			coords.push_back(MapCoord::fromNative(x, y, flags));
		}
	}
	
	QVERIFY(!failed);
	QCOMPARE((int)coords.size(), num_coords);
	QVERIFY(compare_all(coords, proto_coord));
	
	header.close();
	buffer.close();
}
コード例 #13
0
ファイル: plug_push.cpp プロジェクト: jaromrax/plucqisition
  /**********************************************
   * client to                  ZDENEK HONS SERVER
   *              cat runx.dat |  nc -l -p 9302
   *                         this is a client that connects to a server...
   */
int* PLUG(int* par, int* par2){
 


  concurrent_queue<int> *buffer=(concurrent_queue<int>*)par;

   char ch[200];
   //   if(XTERM!=NULL)fprintf(XTERM,"PUSH RS push-remote (network)  par==%d; pointer==%d\n", par,(int)buffer );
   sprintf(ch,"%s","PUSHNET:  entered..." );table_log(0,ch);

      Long64_t cnt=0;

   char ipaddress[100];
   int port;


   //-------- here I will control with    control.mmap    file------   
    if ((mmapfd = open("control.mmap", O_RDWR, 0)) == -1) err(1, "open");
    mmap_file=(char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfd, 0);
    if (mmap_file == MAP_FAILED) errx(1, "either mmap");
    char mmap_result[100];
   //-------- here I will control with    control.mmap    file------   
  char  acqxml2[100];
  TokenGet( "file=" , mmap_file , acqxml2 ); // takes a value from mmap



      TSmallish_xml xml(    acqxml2   );
      xml.DisplayTele( xml.mainnode, 0, "plugins","pusher","ip" );
      sprintf( ipaddress,"%s", xml.output  );
      xml.DisplayTele( xml.mainnode, 0, "plugins","pusher","port" );
      port=atoi(xml.output  );



      //original  char strbuf[2000000];// 20MB
  char strbuf[4000000];// 2MB 711kB; 4MB 1700kB
  int *buffer4p;
  buffer4p=(int*)&strbuf[0];
  int d,i,ii;
  int maxtrans=2000000;
  TSocket *socket;

  double   resrun=1.0; 
  //  int downtimef;//, downtime;

  int trials=10; //10 seconds of timeouts

  
  while (resrun>0.0){// ----- - -- READ ALL REPEATING CONNECTIONS --- -  -- -- - --   - - -

    //  DRUHA STRANA LISTENS !!!!!!!!!!!!!!!!!!!!!!!!!!

    resrun=TokenGet(  "run=", mmap_file , mmap_result ); // if run==0 => KILL HERE
    if (resrun<1.0){ break;}


    Cat Blbka;
    Blbka.Print();

   socket=Blbka.GetSocket( ipaddress, port ) ;
 
   if ( Blbka.WasTimeOut()!=0 ) {
     sprintf(ch,"P %s\n", "After TSocket - fTimeOut==1"); table_log(0,ch);
     break;
   }
   int ii_init;
   trials=10; //GOOD TO BE DEFINED IN XML  as also select timeout
   ii_init=0;// offset if data%4 != 0


    resrun=TokenGet(  "run=", mmap_file , mmap_result ); // if run==0 => KILL HERE
    if (resrun<1.0){ break;}


   while ( (socket)&&(resrun>0.0) ){// ----- - -- READ ONE CONNECTION -------


     //DANGER THAT I MISS 3/10 of EVENTS..... MAYBE THIS IS TO TUNE:
     //3000:50 ==1.6%
     // i==0 => TIMEOUT...... ??
     //  FINALY  2sec timeout, 10x repeat, 50ms wait (TO BE TESTED)
     
     if (PUSHDEBUG!=0){sprintf(ch,"PUSH-net    waiting result=%d ", i ); table_log(0,ch);}
     i=(int)socket->Select(TSocket::kRead, 2000);//timeout 1sec, repeat 5x 
     if (PUSHDEBUG!=0){sprintf(ch,"PUSH-net    Select result i=%d ", i ); table_log(0,ch);}
     
     
     //d=0;//nevim jestli to tu nedela binec
     if (i>0) {//####CASE i>0 ####
       //--  sprintf(ch,"P %s\n", "before recvraw"); table_log(0,ch);
       
       d=(int)socket->RecvRaw( &strbuf[ii_init], maxtrans, kDontBlock  ); // read small buffer
       
       if (PUSHDEBUG!=0){ sprintf(ch,"PUSH-netw socket got %d bytes; init=%d ", d, ii_init ); table_log(0,ch);}
       //     ii=0;
       
       int sizenow;
       //---------------------------------------
       for (ii=0;4*ii<d-(d%4)+ii_init;ii++){
	 //     while( (ii*4<d)&&(d>=4) ){
	 buffer->push( buffer4p[ii] ); 
	 //this helps	 if ( i %10 == 0 ){usleep(1); }
	 /*
	   sizenow= buffer->size();
	 while (sizenow>5000){
	   usleep(100000); 
	   sizenow=buffer->size();
	 }
	 */
	 //  usleep(100000);
	 if (PUSHDEBUG!=0){ sprintf(ch,"%4lld ii= %4d  %08x   %4d",cnt,ii,  buffer4p[ii],d ); table_log(0,ch);}
	 //	ii++;
	 if ((cnt%25000)==0){
	    sizenow= buffer->size();
	   sprintf(ch,"P %7.1f MB : %d",4.*cnt/1000000, sizenow ); table_log(0,ch);    
	   resrun=TokenGet(  "run=", mmap_file , mmap_result ); // if run==0 => KILL HERE
	 
	   if (resrun<1.0){ break;}
	   // if (wait==0) {break;}
	   usleep(100000);
	 }
	 cnt++;
       }//for loop  xwhile - push
       
       
       if (PUSHDEBUG!=0){ sprintf(ch,"PUSH-net  modulo %4d  buf4pii=%08x ",((d+ii_init)%4) , buffer4p[ii] ); table_log(0,ch);}

       
       // I assume thAT D IS even
       if (( (d+ii_init)%4)==0){  ii_init=0;}else{
	 memcpy(&strbuf[0],&strbuf[4*(ii)], 2);
	 memcpy(&strbuf[2],&strbuf[4*(ii)], 2);
	 //       memcpy(&strbuf[0],&strbuf[4*(ii)], d%4);
	 ii_init=2;
       }
       
       if (PUSHDEBUG!=0){ sprintf(ch,"PUSH-net  offset %4d  buf4p0 =%08x ", ii_init , buffer4p[0] ); table_log(0,ch);}
     }//#### if i>0
     
     
 
     resrun=TokenGet(  "run=", mmap_file , mmap_result ); // if run==0 => KILL HERE

     if (resrun<1.0){ 
       sprintf(ch,"PUSH got BROADCAST SIGNAL... %s\n", "" );table_log(0,ch);
       socket->Close(); 
       sprintf(ch,"PUSH socket closed... %s\n", "" );table_log(0,ch);
     }//if wait ==0
     



     if (resrun>0.0){
       
       if (i<0){ //####CASE i<0 ####
	 sprintf(ch,"PUSH SOCKET LOST...%s; iii*4=%d, d=%d\n", ipaddress,ii*4,d );table_log(0,ch);
	 usleep(2000*1000);    
	 //============this helped to have  nice STOP THREAD ============
	 	 if (PUSHDEBUG!=0){sprintf(ch,"PUSH-net    closing,breakin=%d ", i ); table_log(0,ch);}
	 	 socket->Close(); // i dont know // delete socket;
	 	 if (PUSHDEBUG!=0){sprintf(ch,"PUSH-net    closed ,breaked=%d ", i ); table_log(0,ch);}
        break; // i removed this to have easy thread stop // 
       }//####CASE i<0 #### 
       


       if (i==0){ //####CASE i==0  ####
	 trials--;
	 sprintf(ch,"PUSH (ZERO)..%s;d=%d (%d)\n",ipaddress,d, trials);table_log(0,ch);
	 if (trials<=0){
	   sprintf(ch,"PUSH I RELEASE SOCKET(ZERO)..%s; iii*4==%d, d=%d",ipaddress,ii*4,d);table_log(0,ch);
	   socket->Close(); break; 
	 }//trials
       }//####     if  i==0
       
       
       
      //     if (resrun<1.0){break;}
     }//  if resrun >0.0
     if (resrun<1.0){socket->Close(); break;} // this must be
     if (PUSHDEBUG!=0){sprintf(ch,"PUSH-net    end of whil socket %d", i ); table_log(0,ch);}
     
   }// if sock and resrun>0.0
    //    if (wait==0){break;}
  }// while   resrun>0.0   ::::   wait!=0   1==1       WHILE read all the time - ONE CONNECTION


  sprintf(ch,"PUSH deleting socket..%s; iii*4==%d, d=%d",ipaddress,ii*4,d);table_log(0,ch);
  //  socket->Delete();
  delete socket;
  sprintf(ch,"PUSH socket deleted..%s; iii*4==%d, d=%d",ipaddress,ii*4,d);table_log(0,ch);
  

  //  if (wait!=0){ wait=MyCond.TimedWaitRelative( 5000  ) ; }else{ break;}
  //  if (wait==0)break;
  //       usleep(1000*300);
  //if(XTERM!=NULL)fprintf(XTERM,"S%s","" );
  
  //}// 0==0----- - -- READ ALL REPEATING CONNECTIONS --- -  -- -- - --   - - -
  
  
  
  // socket must be already closed here....socket->Close();
  //      if(XTERM!=NULL)fprintf(XTERM,"PUSH RS push-file call finished....%s: PUSHER FINISHED\n", ipaddress );
  sprintf(ch,"PUSH call finished....%s:%d\n", ipaddress,port );table_log(0,ch);
}/*****************************end of function ***********************/
コード例 #14
0
void DVRServer::updateCamerasReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply)
        return;

    qDebug() << "DVRServer: Received cameras list reply";

    reply->deleteLater();

    if (reply->error() != QNetworkReply::NoError)
    {
        /* TODO: Handle this well */
        qWarning() << "DVRServer: Error from updating cameras:" << reply->errorString();
        return;
    }

    QByteArray data = reply->readAll();
    QXmlStreamReader xml(data);

    QSet<int> idSet;
    bool hasDevicesElement = false;
    bool wasEmpty = m_visibleCameras.isEmpty();

    while (xml.readNextStartElement())
    {
        if (xml.name() == QLatin1String("devices"))
        {
            hasDevicesElement = true;

            while (xml.readNext() != QXmlStreamReader::Invalid)
            {
                if (xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == QLatin1String("devices"))
                    break;
                else if (xml.tokenType() != QXmlStreamReader::StartElement)
                    continue;

                if (xml.name() == QLatin1String("device"))
                {
                    bool ok = false;
                    QString idv = xml.attributes().value(QLatin1String("id")).toString();
                    if (idv.isNull())
                        continue;
                    int deviceId = (int)idv.toUInt(&ok);
                    if (!ok)
                    {
                        xml.raiseError(QLatin1String("Invalid device ID"));
                        continue;
                    }

                    idSet.insert(deviceId);
                    DVRCamera *camera = getCamera(deviceId);

                    if (camera)
                    {
                        camera->setOnline(true);
                        
                        DVRCameraXMLReader xmlReader;
                        if (!xmlReader.readCamera(camera, xml))
                        {
                            if (!xml.hasError())
                                xml.raiseError(QLatin1String("Device parsing failed"));
                            continue;
                        }
                        else
                        {
                            DVRCameraSettingsWriter settingsWriter;
                            settingsWriter.writeCamera(camera);
                        }
                    }

                    if (!m_visibleCameras.contains(camera))
                    {
                        m_visibleCameras.append(camera);
                        emit cameraAdded(camera);
                    }
                }
            }
            break;
        }
        else
            xml.skipCurrentElement();
    }

    if (!hasDevicesElement)
        xml.raiseError(QLatin1String("Invalid format: no devices element"));

    if (xml.hasError())
    {
        qWarning() << "DVRServer: Error while parsing camera list:" << xml.errorString();
        return;
    }

    for (int i = 0; i < m_visibleCameras.size(); ++i)
    {
        if (!idSet.contains(m_visibleCameras[i]->data().id()))
        {
            DVRCamera *c = m_visibleCameras[i];
            m_visibleCameras.removeAt(i);
            m_camerasMap.remove(c->data().id());
            qDebug("DVRServer: camera %d removed", c->data().id());
            emit cameraRemoved(c);
            --i;

            delete c;
        }
    }

    if (!m_devicesLoaded || (wasEmpty && !m_visibleCameras.isEmpty()))
    {
        m_devicesLoaded = true;
        emit devicesReady();
    }
}
コード例 #15
0
QMap<QString, QVariant> UBMetadataDcSubsetAdaptor::load(QString pPath)
{

    QMap<QString, QVariant> metadata;

    QString fileName = pPath + "/" + metadataFilename;

    qDebug() << "loading metadata from file : " << fileName;


    QFile file(fileName);

    bool sizeFound = false;
    bool updatedAtFound = false;
    QString date;

    if (file.exists())
    {
        if (!file.open(QIODevice::ReadOnly))
        {
            qWarning() << "Cannot open file " << fileName << " for reading ...";
            return metadata;
        }

        QString docVersion = "4.1"; // untagged doc version 4.1
        metadata.insert(UBSettings::documentVersion, docVersion);

        QXmlStreamReader xml(&file);

        while (!xml.atEnd())
        {
            xml.readNext();

            if (xml.isStartElement())
            {

                if (xml.name() == "title")
                {
                    metadata.insert(UBSettings::documentName, xml.readElementText());
                }
                else if (xml.name() == "type")
                {
                    metadata.insert(UBSettings::documentGroupName, xml.readElementText());
                }
                else if (xml.name() == "date")
                {
                    date = xml.readElementText();
                }
                else if (xml.name() == "identifier") // introduced in UB 4.2
                {
                        metadata.insert(UBSettings::documentIdentifer, xml.readElementText());
                }
                else if (xml.name() == "version" // introduced in UB 4.2
                        && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                        docVersion = xml.readElementText();
                        metadata.insert(UBSettings::documentVersion, docVersion);
                }
                else if (xml.name() == "size" // introduced in UB 4.2
                        && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    QString size = xml.readElementText();
                    QStringList sizeParts = size.split("x");
                    bool ok = false;
                    int width, height;
                    if (sizeParts.count() >= 2)
                    {
                        bool widthOK, heightOK;
                        width = sizeParts.at(0).toInt(&widthOK);
                        height = sizeParts.at(1).toInt(&heightOK);
                        ok = widthOK && heightOK;

                        QSize docSize(width, height);

                        if (width == 1024 && height == 768) // move from 1024/768 to 1280/960
                        {
                            docSize = UBSettings::settings()->pageSize->get().toSize();
                        }

                        metadata.insert(UBSettings::documentSize, QVariant(docSize));
                    }
                    if (!ok)
                    {
                        qWarning() << "Invalid document size:" << size;
                    }

                    sizeFound = true;

                }
                else if (xml.name() == "updated-at" // introduced in UB 4.4
                        && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::documentUpdatedAt, xml.readElementText());
                    updatedAtFound = true;
                }
                else if (xml.name() == UBSettings::sessionTitle // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionTitle, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionAuthors // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionAuthors, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionObjectives // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionObjectives, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionKeywords // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionKeywords, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionGradeLevel // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionGradeLevel, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionSubjects // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionSubjects, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionType // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionType, xml.readElementText());
                }
                else if (xml.name() == UBSettings::sessionLicence // introduced in OpenSankore 1.40.00
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::sessionLicence, xml.readElementText());
                }
                // Issue 1684 - ALTI/AOU - 20131210
                else if (xml.name() == UBSettings::documentDefaultBackgroundImage
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::documentDefaultBackgroundImage, xml.readElementText());
                }
                else if (xml.name() == UBSettings::documentDefaultBackgroundImageDisposition
                         && xml.namespaceUri() == UBSettings::uniboardDocumentNamespaceUri)
                {
                    metadata.insert(UBSettings::documentDefaultBackgroundImageDisposition, xml.readElementText());
                }
                // Fin Issue 1684 - ALTI/AOU - 20131210
            }

            if (xml.hasError())
            {
                qWarning() << "error parsing sankore metadata.rdf file " << xml.errorString();
            }
        }

        file.close();
    }

    if (!sizeFound)
    {
        QDesktopWidget* dw = qApp->desktop();
        int controlScreenIndex = dw->primaryScreen();

        QSize docSize = dw->screenGeometry(controlScreenIndex).size();
        docSize.setHeight(docSize.height() - 70); // 70 = toolbar height

        qWarning() << "Document size not found, using default view size" << docSize;

        metadata.insert(UBSettings::documentSize, QVariant(docSize));
    }

    // this is necessary to update the old files date
    QString dateString = metadata.value(UBSettings::documentDate).toString();
    if(dateString.length() < 10){
        metadata.remove(UBSettings::documentDate);
        metadata.insert(UBSettings::documentDate,dateString+"T00:00:00Z");
    }

    if (!updatedAtFound) {
        metadata.insert(UBSettings::documentUpdatedAt, dateString);
    }

    metadata.insert(UBSettings::documentDate, QVariant(date));


    return metadata;
}
コード例 #16
0
ファイル: test.cpp プロジェクト: smontsaroff/KeyRemap4MacBook
TEST(pqrs_xml_compiler_filter_vector, filter_vector)
{
  pqrs::xml_compiler::symbol_map s;
  s.add("ApplicationType", "APP1", 1);
  s.add("ApplicationType", "APP2", 2);
  s.add("ApplicationType", "APP3", 3);
  s.add("DeviceVendor", "VENDOR1", 10);
  s.add("DeviceVendor", "VENDOR2", 20);
  s.add("DeviceVendor", "VENDOR3", 30);
  s.add("DeviceProduct", "PRODUCT1", 100);
  s.add("DeviceProduct", "PRODUCT2", 200);
  s.add("DeviceProduct", "PRODUCT3", 300);
  s.add("ConfigIndex", "config1", 1000);
  s.add("ConfigIndex", "config2", 2000);
  s.add("ConfigIndex", "config3", 3000);
  s.add("ModifierFlag", "MOD1", 0x1000);
  s.add("ModifierFlag", "MOD2", 0x2000);
  s.add("ModifierFlag", "MOD3", 0x4000);

  std::string xml("<?xml version=\"1.0\"?>"
                  "<item>"
                  "  <only>APP1,APP3</only>"
                  "  <not><!-- XXX --->APP2</not>"
                  "  <identifier>sample</identifier>"
                  "  <device_only>DeviceVendor::VENDOR1, DeviceProduct::PRODUCT1, </device_only>"
                  "  <device_not>"
                  "    DeviceVendor::VENDOR3,,,,"
                  "    DeviceProduct::PRODUCT3,"
                  "  </device_not>"
                  "  <config_only>config1,config2</config_only>"
                  "  <config_not>config3</config_not>"
                  "  <modifier_only>ModifierFlag::MOD1 ||| ModifierFlag::MOD3</modifier_only>"
                  "  <modifier_not> ModifierFlag::MOD2 </modifier_not>"
                  "</item>");
  std::stringstream istream(xml, std::stringstream::in);

  int flags = boost::property_tree::xml_parser::no_comments;
  boost::property_tree::ptree pt;
  boost::property_tree::read_xml(istream, pt, flags);

  for (auto& it : pt) {
    pqrs::xml_compiler::filter_vector fv(s, it.second);

    std::vector<uint32_t> expected;

    // <only>APP1,APP3</only>
    expected.push_back(3); // count
    expected.push_back(BRIDGE_FILTERTYPE_APPLICATION_ONLY);
    expected.push_back(1); // APP1
    expected.push_back(3); // APP3

    // <not>APP2</not>
    expected.push_back(2); // count
    expected.push_back(BRIDGE_FILTERTYPE_APPLICATION_NOT);
    expected.push_back(2); // APP2

    // <device_only>DeviceVendor::VENDOR1, DeviceProduct::PRODUCT1, </device_only>
    expected.push_back(3); // count
    expected.push_back(BRIDGE_FILTERTYPE_DEVICE_ONLY);
    expected.push_back(10);
    expected.push_back(100);

    // <device_not>DeviceVendor::VENDOR3, DeviceProduct::PRODUCT3, </device_not>
    expected.push_back(3); // count
    expected.push_back(BRIDGE_FILTERTYPE_DEVICE_NOT);
    expected.push_back(30);
    expected.push_back(300);

    // <config_only>config1,config2</config_only>
    expected.push_back(3); // count
    expected.push_back(BRIDGE_FILTERTYPE_CONFIG_ONLY);
    expected.push_back(1000);
    expected.push_back(2000);

    // <config_not>config3</config_not>
    expected.push_back(2); // count
    expected.push_back(BRIDGE_FILTERTYPE_CONFIG_NOT);
    expected.push_back(3000);

    // <modifier_only>ModifierFlag::MOD1 ||| ModifierFlag::MOD3</modifier_only>
    expected.push_back(2);
    expected.push_back(BRIDGE_FILTERTYPE_MODIFIER_ONLY);
    expected.push_back(0x1000 | 0x4000);

    // <modifier_not> ModifierFlag::MOD2 </modifier_not>
    expected.push_back(2);
    expected.push_back(BRIDGE_FILTERTYPE_MODIFIER_NOT);
    expected.push_back(0x2000);

    EXPECT_EQ(expected, fv.get());
  }
}
コード例 #17
0
int main (int argc, char* argv[])
{
	LOGOG_INITIALIZE();
	logog::Cout* logog_cout (new logog::Cout);
	BaseLib::LogogSimpleFormatter *custom_format (new BaseLib::LogogSimpleFormatter);
	logog_cout->SetFormatter(*custom_format);

	TCLAP::CmdLine cmd("Add EMI data as a scalar cell array to a 2d mesh.", ' ', "0.1");

	// I/O params
	TCLAP::ValueArg<std::string> poly_out("o", "polydata-output-file",
	                                      "the name of the file the data will be written to", true,
	                                      "", "file name of polydata file");
	cmd.add(poly_out);
	TCLAP::ValueArg<std::string> csv_in("i", "csv-input-file",
	                                    "csv-file containing EMI data", true,
	                                    "", "name of the csv input file");
	cmd.add(csv_in);
	TCLAP::ValueArg<std::string> dem_in("s", "DEM-file",
	                                    "Surface DEM for mapping ERT data", false,
	                                    "", "file name of the Surface DEM");
	cmd.add(dem_in);
	cmd.parse(argc, argv);

	MeshLib::Mesh* mesh (nullptr);
	if (dem_in.isSet())
	{
		mesh = FileIO::VtuInterface::readVTUFile(dem_in.getValue());
		if (mesh == nullptr)
		{
			ERR ("Error reading mesh file.");
			return -2;
		}

		if (mesh->getDimension() != 2)
		{
			ERR ("This utility can handle only 2d meshes at this point.");
			delete mesh;
			return -3;
		}
		INFO("Surface mesh read: %d nodes, %d elements.", mesh->getNNodes(), mesh->getNElements());
	}

	GeoLib::GEOObjects geo_objects;
	FileIO::XmlGmlInterface xml(geo_objects);
	//std::vector<GeoLib::Polyline*> *lines = new std::vector<GeoLib::Polyline*>;
	std::array<char, 2> dipol = {{ 'H', 'V' }};
	std::array<char,3> const regions = {{'A', 'B', 'C'}};
	for (std::size_t j=0; j<dipol.size(); ++j)
	{
		std::vector<GeoLib::Point*> *points   = new std::vector<GeoLib::Point*>;
		for (std::size_t i=0; i<regions.size(); ++i)
		{
			//std::size_t const start_idx (points->size());
			getPointsFromFile(*points, csv_in.getValue(), dipol[j], regions[i]);
			//std::size_t const end_idx (points->size());
			//GeoLib::Polyline* line = new GeoLib::Polyline(*points);
			//for (std::size_t j=start_idx; j<end_idx; ++j)
			//	line->addPoint(j);
			//lines->push_back(line);
		}
		std::string geo_name (std::string("EMI Data ").append(1,dipol[j]));
		geo_objects.addPointVec(points, geo_name);
		//geo_objects.addPolylineVec(lines, geo_name);

		if (mesh != nullptr)
		{
			GeoMapper mapper(geo_objects, geo_name);
			mapper.mapOnMesh(mesh);
		}
		
		xml.setNameForExport(geo_name);
		std::string const output_name = poly_out.getValue() + "_" + dipol[j] + ".gml";
		xml.writeToFile(output_name);
		
		std::vector<double> emi;
		for (std::size_t i=0; i<regions.size(); ++i)
			getMeasurements(emi, csv_in.getValue(), dipol[j], regions[i]);
		writeMeasurementsToFile(emi, poly_out.getValue(), dipol[j]);
		std::for_each(points->begin(), points->end(), std::default_delete<GeoLib::Point>());
		delete points;
	}
	
	delete mesh;
	delete custom_format;
	delete logog_cout;
	LOGOG_SHUTDOWN();

	return 0;
}
コード例 #18
0
int main (int argc, char* argv[])
{
	LOGOG_INITIALIZE();
	logog::Cout* logog_cout (new logog::Cout);
	BaseLib::LogogSimpleFormatter *custom_format (new BaseLib::LogogSimpleFormatter);
	logog_cout->SetFormatter(*custom_format);

	TCLAP::CmdLine cmd("Append line elements into a mesh.", ' ', "0.1");
	TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file",
	                                     "the name of the file containing the input mesh", true,
	                                     "", "file name of input mesh");
	cmd.add(mesh_in);
	TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file",
	                                      "the name of the file the mesh will be written to", true,
	                                      "", "file name of output mesh");
	cmd.add(mesh_out);
	TCLAP::ValueArg<std::string> geoFileArg("g", "geo-file",
	                                      "the name of the geometry file which contains polylines", true, "", "the name of the geometry file");
	cmd.add(geoFileArg);

	// parse arguments
	cmd.parse(argc, argv);

	// read GEO objects
	GeoLib::GEOObjects geo_objs;
	FileIO::BoostXmlGmlInterface xml(geo_objs);
	xml.readFile(geoFileArg.getValue());

	std::vector<std::string> geo_names;
	geo_objs.getGeometryNames (geo_names);
	if (geo_names.empty ())
	{
		std::cout << "no geometries found" << std::endl;
		return -1;
	}
	const GeoLib::PolylineVec* ply_vec (geo_objs.getPolylineVecObj(geo_names[0]));
	if (!ply_vec)
	{
		std::cout << "could not found polylines" << std::endl;
		return -1;
	}

	// read a mesh
	MeshLib::Mesh const*const mesh (FileIO::readMeshFromFile(mesh_in.getValue()));
	if (!mesh)
	{
		ERR("Mesh file %s not found", mesh_in.getValue().c_str());
		return 1;
	}
	INFO("Mesh read: %d nodes, %d elements.", mesh->getNNodes(), mesh->getNElements());

	// add line elements
	std::unique_ptr<MeshLib::Mesh> new_mesh =
	    MeshGeoToolsLib::appendLinesAlongPolylines(*mesh, *ply_vec);
	INFO("Mesh created: %d nodes, %d elements.", new_mesh->getNNodes(), new_mesh->getNElements());

	// write into a file
	FileIO::Legacy::MeshIO meshIO;
	meshIO.setMesh(new_mesh.get());
	meshIO.writeToFile(mesh_out.getValue());

	delete custom_format;
	delete logog_cout;
	LOGOG_SHUTDOWN();

	return 1;
}
コード例 #19
0
static IOResult ImportLibrary(ILoad* iload, MtlBaseLib& lib)
{
	// Get the VIZ Importer/Exporter
	CComPtr<IVIZPointerClient> pPointerClient;
	HRESULT hr = CMaxMaterialCollection::GetXMLImpExp(&pPointerClient);
	if(hr != S_OK)
		return IO_ERROR;

	// Get the export interface
	CComQIPtr<IXmlMaterial> pIMtl = pPointerClient;
	ATLASSERT(pIMtl);
	if(!pIMtl)
		return IO_ERROR;

	// Create an XML document
	CComPtr<IXMLDOMDocument> doc;
	hr = doc.CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER);
	if (hr != S_OK || doc == NULL)
		return IO_ERROR;

	char* xmlStr = NULL;
	IOResult res = iload->ReadCStringChunk(&xmlStr);
	if (res != IO_OK)
		return res;
	if (xmlStr == NULL)
		return IO_OK;
	_bstr_t xml(xmlStr);

	VARIANT_BOOL result;
	hr = doc->loadXML(xml.GetBSTR(), &result);
	if (hr != S_OK || result == 0)
		return IO_ERROR;

	CComBSTR query = "./Materials/Material";
	CComPtr<IXMLDOMNodeList> list;
	hr = doc->selectNodes(query, &list);
	if (hr != S_OK || list == NULL)
		return IO_ERROR;

	long i, len = 0;
	hr = list->get_length(&len);
	if (hr != S_OK)
		return IO_ERROR;

	long failed = 0;
	for (i = 0; i < len ; ++i) {
		CComPtr<IXMLDOMNode> node;
		hr = list->get_item(i, &node);
		if (hr == S_OK && node != NULL) {
			VARIANT vResult;
			vResult.vt = VT_BYREF;
			vResult.byref = NULL;
			hr = pIMtl->ImportMaterial(node, &vResult);
			if(SUCCEEDED(hr) && vResult.vt == VT_BYREF && vResult.byref != NULL)
			{
				lib.Add(static_cast<Mtl*>(vResult.byref));
			}
			else
				++failed;
		}
	}
	
	return failed == 0 ? IO_OK : IO_ERROR;
}
コード例 #20
0
ファイル: config.cpp プロジェクト: 0jpq0/kbengine
//-------------------------------------------------------------------------------------
bool Config::loadConfig(std::string fileName)
{
	fileName_ = fileName;
	TiXmlNode* rootNode = NULL;
	SmartPointer<XML> xml(new XML(Resmgr::getSingleton().matchRes(fileName_).c_str()));

	if(!xml->isGood())
	{
		ERROR_MSG(fmt::format("Config::loadConfig: load {} is failed!\n",
			fileName.c_str()));

		return false;
	}
	
	if(xml->getRootNode() == NULL)
	{
		// root节点下没有子节点了
		return true;
	}

	rootNode = xml->getRootNode("packetAlwaysContainLength");
	if(rootNode != NULL){
		Network::g_packetAlwaysContainLength = xml->getValInt(rootNode) != 0;
	}

	rootNode = xml->getRootNode("trace_packet");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "debug_type");
		if(childnode)
			Network::g_trace_packet = xml->getValInt(childnode);

		if(Network::g_trace_packet > 3)
			Network::g_trace_packet = 0;

		childnode = xml->enterNode(rootNode, "use_logfile");
		if(childnode)
			Network::g_trace_packet_use_logfile = (xml->getValStr(childnode) == "true");

		childnode = xml->enterNode(rootNode, "disables");
		if(childnode)
		{
			do
			{
				if(childnode->FirstChild() != NULL)
				{
					std::string c = childnode->FirstChild()->Value();
					c = strutil::kbe_trim(c);
					if(c.size() > 0)
					{
						Network::g_trace_packet_disables.push_back(c);
					}
				}
			}while((childnode = childnode->NextSibling()));
		}
	}

	rootNode = xml->getRootNode("debugEntity");
	if(rootNode != NULL)
	{
		g_debugEntity = xml->getValInt(rootNode) > 0;
	}
	
	rootNode = xml->getRootNode("publish");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "state");
		if(childnode)
		{
			g_appPublish = xml->getValInt(childnode);
		}

		childnode = xml->enterNode(rootNode, "script_version");
		if(childnode)
		{
			KBEVersion::setScriptVersion(xml->getValStr(childnode));
		}
	}

	rootNode = xml->getRootNode("channelCommon");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "timeout");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "internal");
			if(childnode1)
			{
				channelInternalTimeout_ = KBE_MAX(0.f, float(xml->getValFloat(childnode1)));
				Network::g_channelInternalTimeout = channelInternalTimeout_;
			}

			childnode1 = xml->enterNode(childnode, "external");
			if(childnode)
			{
				channelExternalTimeout_ = KBE_MAX(0.f, float(xml->getValFloat(childnode1)));
				Network::g_channelExternalTimeout = channelExternalTimeout_;
			}
		}

		childnode = xml->enterNode(rootNode, "resend");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "internal");
			if(childnode1)
			{
				TiXmlNode* childnode2 = xml->enterNode(childnode1, "interval");
				if(childnode2)
				{
					Network::g_intReSendInterval = uint32(xml->getValInt(childnode2));
				}

				childnode2 = xml->enterNode(childnode1, "retries");
				if(childnode2)
				{
					Network::g_intReSendRetries = uint32(xml->getValInt(childnode2));
				}
			}

			childnode1 = xml->enterNode(childnode, "external");
			if(childnode)
			{
				TiXmlNode* childnode2 = xml->enterNode(childnode1, "interval");
				if(childnode2)
				{
					Network::g_extReSendInterval = uint32(xml->getValInt(childnode2));
				}

				childnode2 = xml->enterNode(childnode1, "retries");
				if(childnode2)
				{
					Network::g_extReSendRetries = uint32(xml->getValInt(childnode2));
				}
			}
		}

		childnode = xml->enterNode(rootNode, "windowOverflow");
		if(childnode)
		{
			TiXmlNode* sendNode = xml->enterNode(childnode, "send");
			if(sendNode)
			{
				TiXmlNode* childnode1 = xml->enterNode(sendNode, "messages");
				if(childnode1)
				{
					TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
					if(childnode2)
						Network::g_intSendWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

					childnode2 = xml->enterNode(childnode1, "external");
					if(childnode2)
						Network::g_extSendWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

					childnode2 = xml->enterNode(childnode1, "critical");
					if(childnode2)
						Network::g_sendWindowMessagesOverflowCritical = KBE_MAX(0, xml->getValInt(childnode2));
				}

				childnode1 = xml->enterNode(sendNode, "bytes");
				if(childnode1)
				{
					TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
					if(childnode2)
						Network::g_intSendWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
				
					childnode2 = xml->enterNode(childnode1, "external");
					if(childnode2)
						Network::g_extSendWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
				}
			}

			TiXmlNode* recvNode = xml->enterNode(childnode, "receive");
			if(recvNode)
			{
				TiXmlNode* childnode1 = xml->enterNode(recvNode, "messages");
				if(childnode1)
				{
					TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
					if(childnode2)
						Network::g_intReceiveWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

					childnode2 = xml->enterNode(childnode1, "external");
					if(childnode2)
						Network::g_extReceiveWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

					childnode2 = xml->enterNode(childnode1, "critical");
					if(childnode2)
						Network::g_receiveWindowMessagesOverflowCritical = KBE_MAX(0, xml->getValInt(childnode2));
				}

				childnode1 = xml->enterNode(recvNode, "bytes");
				if(childnode1)
				{
					TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
					if(childnode2)
						Network::g_intReceiveWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
				
					childnode2 = xml->enterNode(childnode1, "external");
					if(childnode2)
						Network::g_extReceiveWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
				}
			}
		};

		childnode = xml->enterNode(rootNode, "encrypt_type");
		if(childnode)
		{
			Network::g_channelExternalEncryptType = xml->getValInt(childnode);
		}
	}

	rootNode = xml->getRootNode("telnet_service");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "port");
		if(childnode)
		{
			telnet_port = xml->getValInt(childnode);
		}

		childnode = xml->enterNode(rootNode, "password");
		if(childnode)
		{
			telnet_passwd = xml->getValStr(childnode);
		}

		childnode = xml->enterNode(rootNode, "default_layer");
		if(childnode)
		{
			telnet_deflayer = xml->getValStr(childnode);
		}
	}

	rootNode = xml->getRootNode("gameUpdateHertz");
	if(rootNode != NULL){
		gameUpdateHertz_ = xml->getValInt(rootNode);
	}

	rootNode = xml->getRootNode("ip");
	if(rootNode != NULL)
	{
		strcpy(ip_, xml->getValStr(rootNode).c_str());
	}

	rootNode = xml->getRootNode("port");
	if(rootNode != NULL){
		port_ = xml->getValInt(rootNode);
	}

	rootNode = xml->getRootNode("entryScriptFile");
	if(rootNode != NULL)
	{
		strcpy(entryScriptFile_, xml->getValStr(rootNode).c_str());
	}

	rootNode = xml->getRootNode("accountName");
	if(rootNode != NULL)
	{
		strcpy(accountName_, xml->getValStr(rootNode).c_str());
	}

	rootNode = xml->getRootNode("useLastAccountName");
	if(rootNode != NULL)
	{
		useLastAccountName_ = xml->getValStr(rootNode) != "false";
	}
	
	rootNode = xml->getRootNode("encrypt_login");
	if(rootNode != NULL)
	{
		encrypt_login_ = xml->getValInt(rootNode);
	}
	
	rootNode = xml->getRootNode("aliasEntityID");
	if(rootNode != NULL)
	{
		EntityDef::entityAliasID((xml->getValStr(rootNode) == "true"));
	}

	rootNode = xml->getRootNode("entitydefAliasID");
	if(rootNode != NULL){
		EntityDef::entitydefAliasID((xml->getValStr(rootNode) == "true"));
	}

	return true;
}
コード例 #21
0
ファイル: EventCanvas.cpp プロジェクト: ViktorNova/los
void EventCanvas::pasteAt(const QString& pt, int pos)
{
    QByteArray ba = pt.toLatin1();
    const char* p = ba.constData();
    Xml xml(p);
    for (;;)
    {
        Xml::Token token = xml.parse();
        const QString& tag = xml.s1();
        switch (token)
        {
        case Xml::Error:
        case Xml::End:
            return;
        case Xml::TagStart:
            if (tag == "eventlist")
            {
                song->startUndo();
                EventList* el = new EventList();
                el->read(xml, "eventlist");
                int modified = SC_EVENT_INSERTED;
                for (iEvent i = el->begin(); i != el->end(); ++i)
                {
                    Event e = i->second;
                    int tick = e.tick() + pos - _curPart->tick();
                    if (tick < 0)
                    {
                        printf("ERROR: trying to add event before current part!\n");
                        song->endUndo(SC_EVENT_INSERTED);
                        delete el;
                        return;
                    }

                    e.setTick(tick);
                    int diff = e.endTick() - _curPart->lenTick();
                    if (diff > 0)
                    {// too short part? extend it
                        Part* newPart = _curPart->clone();
                        newPart->setLenTick(newPart->lenTick() + diff);
                        // Indicate no undo, and do port controller values but not clone parts.
                        audio->msgChangePart(_curPart, newPart, false, true, false);
                        modified = modified | SC_PART_MODIFIED;
                        _curPart = newPart; // reassign
                    }
                    // Indicate no undo, and do not do port controller values and clone parts.
                    audio->msgAddEvent(e, _curPart, false, false, false);
                }
                song->endUndo(modified);
                delete el;
                return;
            }
            else
                xml.unknown("pasteAt");
            break;
            case Xml::Attribut:
            case Xml::TagEnd:
            default:
            break;
        }
    }
}
コード例 #22
0
ファイル: mainwindow.cpp プロジェクト: kolphi/QWeather
void MainWindow::replyFinished(QNetworkReply* response)
{

    bool locationFound = false;
    //set variable for request-type
    if(!requestWeather){

    QXmlStreamReader xml(response);
    if (!xml.hasError()) {
        QString address = "";
        while (!xml.atEnd() && !locationFound) {
            xml.readNextStartElement();
                if (xml.name() == "formatted_address") {
                    geoCodingSuccessfull = true;
                    address = *(new QString(address.append((xml.readElementText()))));
                    const QString address2 = address;
                    ui->le_pos->setText(address2);
                    locationFound = true;
                 //   ui->lb_main_date->setText(*address);
                }
        }

        ui->statusBar->showMessage(QString("Successfully received XML location data."));

    } else {
        ui->statusBar->showMessage(QString("Failed to parse XML location data."));
    }

    }else{
        QXmlStreamReader xml(response);
        QXmlStreamAttributes attributes;
        if (!xml.hasError()) {

            //initializing variables
            QString date = "";
            QString condition = "";
            QString cond1 = "";
            QString cond2 = "";
            QString cond3 = "";
            QString cond4 = "";
            QString temp = "";
            QString humidity = "";
            QString windCondition = "";
            QString high = "";
            QString low = "";
            QString day = "";

            QString degrees = " °F";

            //already added °F?
            bool added = false;
            bool cityNotFound = false;

            //setting counters to specify how often a variable was called
            //because variabels appear more often in the xml(4 days are displayed)
            // - for all others than condition: take the first, third and fourth day (second is the  same day as first)
            int condCounter = 0;
            int dayCounter = 0;
            int lowCounter = 0;
            int highCounter = 0;


            //parsing the xml
            while (!xml.atEnd()) {
                xml.readNextStartElement();

                if (xml.name() == "problem_cause") {
                    cityNotFound = true;
                }

                //setting date
                    if (xml.name() == "forecast_date") {
                        attributes = xml.attributes();
                        date = *(new QString(date.append(attributes.value("data"))));
                        const QString date2 = date;
                        ui->lb_main_date->setText(date2);

                    }

                    //parsing weather condition data
                    if (xml.name() == "condition") {

                        attributes = xml.attributes();
                        condition = *(new QString(condition.append(attributes.value("data"))));

                        //setting cond variables for the different times condition was found
                        if(condCounter == 0){
                            cond1 = condition;
                            const QString condition2 = condition;
                            ui->lb_main_condition->setText(condition2);
                            ui->img_main->setPixmap(QPixmap(getPictureString(condition)));


                        }else if(condCounter == 4){
                            cond2 = condition;
                          //  qDebug(getPictureString(condition));
                            ui->img_weather_fc_1->setPixmap(QPixmap(getPictureString(condition)));

                        }
                        else if(condCounter == 6){
                            cond3 = condition;
                       //     qDebug(getPictureString(condition));
                            ui->img_weather_fc_2->setPixmap(QPixmap(getPictureString(condition)));

                        }

                        else if(condCounter == 8){
                            cond4 = condition;
                      //      qDebug(getPictureString(condition));
                             ui->img_weather_fc_3->setPixmap(QPixmap(getPictureString(condition)));

                        }
                        condCounter++;
                        condition = "";
                    }

                    //parsing temp of today
                    if (xml.name() == "temp_f") {


                        attributes = xml.attributes();
                        temp = *(new QString(temp.append(attributes.value("data"))));

                        if(!added){
                           temp.append(degrees);
                           added = true;
                        }

                        const QString temp2 = temp;
                        ui->lb_main_temp->setText(temp2);

                    }
                    //parsing humidity data
                    if (xml.name() == "humidity") {
                        attributes = xml.attributes();
                        humidity = *(new QString(humidity.append(attributes.value("data"))));
                        const QString humidity2 = humidity;
                        ui->lb_main_humidity->setText(humidity2);

                    }

                    //parsing wind condition data
                    if (xml.name() == "wind_condition") {
                        attributes = xml.attributes();
                        windCondition = *(new QString(windCondition.append(attributes.value("data"))));
                        const QString wind2 = windCondition;
                        ui->lb_main_wind->setText(wind2);

                    }

                    //parsing high temp data of the xml
                    if (xml.name() == "high") {
                        attributes = xml.attributes();
                        high = *(new QString(high.append(attributes.value("data"))));

                        if(highCounter == 2){
                            const QString high2 = high;
                            ui->lb_temp_high_1->setText(high2);

                        }else if(highCounter == 4){
                            const QString high3 = high;
                            ui->lb_temp_high_2->setText(high3);;

                        }else if(highCounter == 6){
                            const QString high4 = high;
                            ui->lb_temp_high_3->setText(high4);
                        }

                        highCounter++;

                        high = "";

                    }

                    //parsing low temp data of the xml
                    if (xml.name() == "low") {
                        attributes = xml.attributes();
                        low = *(new QString(low.append(attributes.value("data"))));


                        if(lowCounter == 2){
                            const QString low2 = low;
                            ui->lb_temp_low_1->setText(low2);

                        }else if(lowCounter == 4){
                            const QString low3 = low;
                            ui->lb_temp_low_2->setText(low3);

                        }else if(lowCounter == 6){
                            const QString low4 = low;
                            ui->lb_temp_low_3->setText(low4);
                        }
                        low = "";
                        lowCounter++;

                    }


                    //parsing out day of week
                    if (xml.name() == "day_of_week") {
                        attributes = xml.attributes();
                        day = *(new QString(day.append(attributes.value("data"))));


                        if(dayCounter == 2){
                            const QString day2 = day;
                            ui->lb_date_fc_1->setText(day2);

                        }else if(dayCounter == 4){
                            const QString day3 = day;
                            ui->lb_date_fc_2->setText(day3);

                        }else if(dayCounter == 6){
                            const QString day4 = day;
                            ui->lb_date_fc_3->setText(day4);
                        }
                        day = "";
                        dayCounter++;

                     }//end-if

            }//end while


            //update the status bar

            //check if city was found
            if(cityNotFound){
                ui->statusBar->showMessage(QString("Address was not found. Please try again!"));
            }else{
                ui->statusBar->showMessage(QString("Successfully received XML weather data."));
            }

    }else{
         ui->statusBar->showMessage(QString("XML error while parsing."));
         }

    }//end if-request-weather

}
コード例 #23
0
ファイル: downloader.cpp プロジェクト: SpliFF/springlobby
void PlasmaInterface::ParseResourceListData( const wxString& buffer )
{
	//MUTEX !!
	wxString wxbuf = buffer;

    wxString t_begin = _T("<soap:Envelope");
    wxString t_end = _T("</soap:Envelope>");
    wxString xml_section = wxbuf.Mid( wxbuf.Find( t_begin ) );//first char after t_begin to one before t_end

    wxStringInputStream str_input( xml_section );
    wxXmlDocument xml( str_input );
    assert( xml.GetRoot() );
    wxXmlNode *node = xml.GetRoot()->GetChildren();
    assert( node );

    m_resource_list.clear();

    wxString resourceType ( _T("unknown") );
    node = node->GetChildren();
    assert( node );
    while ( node ) {
        wxString node_name = node->GetName();
        if ( node_name == _T("GetResourceListResponse") ) {
            wxXmlNode* resourceListResult = node->GetChildren();
            assert( resourceListResult );
            while ( resourceListResult ) {
                wxXmlNode* resourceData = resourceListResult->GetChildren();

                while ( resourceData ) {
                    wxXmlNode* resourceDataContent = resourceData->GetChildren();
                    PlasmaResourceInfo info;
                    while ( resourceDataContent ) {
                        wxString rc_node_name = resourceDataContent->GetName();
                        if ( rc_node_name == _T("Dependencies") ){
                            //! TODO
                        }
                        else if ( rc_node_name == _T("InternalName") ){
                            info.m_name = resourceDataContent->GetNodeContent();
                        }
                        else if ( rc_node_name == _T("ResourceType") ){
                            resourceType = resourceDataContent->GetNodeContent();
                            if ( resourceType == _T("Mod") )
                                info.m_type = PlasmaResourceInfo::mod;
                            else if ( resourceType == _T("Map") )
                                info.m_type = PlasmaResourceInfo::map;
                            else
								info.m_type = PlasmaResourceInfo::unknown;
                        }
                        else if ( rc_node_name == _T("SpringHashes") ){
                            //! TODO
                        }
                        resourceDataContent = resourceDataContent->GetNext();
                    }
                    m_resource_list.push_back( info );
                    resourceData = resourceData->GetNext();
                }
                resourceListResult = resourceListResult->GetNext();
            }
        } // end section <GetResourceListResponse/>
        node = node->GetNext();
    }
	PlasmaResourceInfo::VectorToFile( m_resource_list, _T("plasmaresourcelist.sl") );
}
コード例 #24
0
ファイル: playlist_parser.cpp プロジェクト: RavetcoFX/Yarock
/*******************************************************************************
    .xspf playlist read
*******************************************************************************/
QList<MEDIA::TrackPtr>  readXspfPlaylist(QIODevice* device, const QDir& playlist_dir )
{
    Debug::debug() << "[MEDIA] readXspfPlaylist";

    QList<MEDIA::TrackPtr>  list;

    QXmlStreamReader xml(device);

    MEDIA::TrackPtr mi = MEDIA::TrackPtr(0);

    
    
    while(!xml.atEnd() && !xml.hasError())
    {
       xml.readNext();
       if (xml.isStartElement() && xml.name() == "trackList")
         break;
    }
    

    while (!xml.atEnd() && !xml.hasError())
    {
       xml.readNext();
      
      if (xml.isStartElement() && xml.name() == "track")
      {
        //Debug::debug() << "---- readXspfPlaylist -> NEW Track ";
        mi = MEDIA::TrackPtr(new MEDIA::Track());
      }
      else if (xml.isStartElement() && xml.name() == "location")
      {
            QString file_path = QString(xml.readElementText());

            //Debug::debug() << "---- readXspfPlaylist -> Find the Track location" << file_path;
            if (!MEDIA::isLocal(file_path)) {
              QUrl url(file_path);
              if (url.isValid()) {

                //Debug::debug() << "---- readXspfPlaylist -> it's an url";
                if(mi) {
                  mi->setType(TYPE_STREAM);
                  mi->id          = -1;
                  mi->url         = file_path;
                  mi->name        = file_path;
                  mi->isFavorite  = false;
                  mi->isPlaying   = false;
                  mi->isBroken    = false;
                  mi->isPlayed    = false;
                  mi->isStopAfter = false;
                }
              }
            }
            else {
              //Debug::debug() << "---- readXspfPlaylist -> it's a local file";

              file_path = QDir::fromNativeSeparators(file_path);
              //Debug::debug() << "---- readXspfPlaylist -> file_path" << file_path;

              // Make the path absolute
              if (!QDir::isAbsolutePath(file_path))
                file_path = playlist_dir.absoluteFilePath(file_path);
              //Debug::debug() << "---- readXspfPlaylist -> file_path" << file_path;

              // Use the canonical path
              if (QFile::exists(file_path))
                file_path = QFileInfo(file_path).canonicalFilePath();
              //Debug::debug() << "---- readXspfPlaylist -> file_path" << file_path;

              if(mi) {
                mi->setType(TYPE_TRACK);
                mi->id          =  -1;
                mi->url         =  file_path;
                mi->isPlaying   =  false;
                mi->isBroken    =  !QFile::exists(file_path);
                mi->isPlayed    =  false;
                mi->isStopAfter =  false;
             }
           }
      } // end location
      else if (xml.isStartElement() && xml.name() == "title")
      {
          if(mi->type() == TYPE_TRACK)
            mi->title = QString(xml.readElementText());
          else
            mi->name = QString(xml.readElementText());
      }
      else if (xml.isStartElement() && xml.name() == "category")
      {
          if(mi->type() == TYPE_STREAM)
            mi->categorie = QString(xml.readElementText());
      }
      else if (xml.isEndElement() && xml.name() == "track")
      {
        //Debug::debug() << "---- readXspfPlaylist -> list.append(mi)" << mi;
        if(mi)
          list.append(mi);
        mi = MEDIA::TrackPtr(0);
      }
    }  // End while xml end

    //Debug::debug() << "readXspfPlaylist -> END OK";

    return list;
}
コード例 #25
0
ファイル: enrolldialog.cpp プロジェクト: jvillasante/linea10
bool EnrollDialog::parseXmlPersona(QString &response, QString &identifier, QString &rut, QString &name)
{
  QXmlStreamReader xml(response);

  QString idPer, rutStr, rutDv, nombre, apPaterno, apMaterno;

  while (!xml.atEnd() && !xml.hasError()) {
    QXmlStreamReader::TokenType token = xml.readNext();

    if (token == QXmlStreamReader::StartDocument) { continue; }

    if (token == QXmlStreamReader::StartElement) {
      if (xml.name() == "idPer") {
        token = xml.readNext();
        if(xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("idPer: %s", xml.text().toString().toStdString().c_str());
          idPer = xml.text().toString();
          continue;
        }
      }

      if (xml.name() == "rut") {
        token = xml.readNext();
        if (xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("rut: %s", xml.text().toString().toStdString().c_str());
          rutStr = xml.text().toString();
          continue;
        }
      }

      if (xml.name() == "rutDv") {
        token = xml.readNext();
        if (xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("rutDv: %s", xml.text().toString().toStdString().c_str());
          rutDv = xml.text().toString();
          continue;
        }
      }

      if (xml.name() == "nombre") {
        token = xml.readNext();
        if (xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("nombre: %s", xml.text().toString().toStdString().c_str());
          nombre = xml.text().toString();
          continue;
        }
      }

      if (xml.name() == "apPaterno") {
        token = xml.readNext();
        if (xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("apPaterno: %s", xml.text().toString().toStdString().c_str());
          apPaterno = xml.text().toString();
          continue;
        }
      }

      if (xml.name() == "apMaterno") {
        token = xml.readNext();
        if (xml.tokenType() == QXmlStreamReader::Characters) {
          DEBUG("apMaterno: %s", xml.text().toString().toStdString().c_str());
          apMaterno = xml.text().toString();
          continue;
        }
      }

      if (xml.hasError()) {
        DEBUG("XML Error: %s", xml.errorString().toStdString().c_str());
        xml.clear();
      }
    }
    continue;
  }

  identifier = idPer;
  rut = rutStr + "-" + rutDv;
  name = nombre + " " + apPaterno + " " + apMaterno;

  if (identifier.isEmpty() || rut.isEmpty() || name.isEmpty()) {
    DEBUG("WS Error. identifier: %s, rut: %s, name: %s", identifier.toStdString().c_str(), rut.toStdString().c_str(), name.toStdString().c_str());
    return false;
  }

  DEBUG("WS OK. identifier: %s, rut: %s, name: %s", identifier.toStdString().c_str(), rut.toStdString().c_str(), name.toStdString().c_str());
  return true;
}
コード例 #26
0
ファイル: filter.cpp プロジェクト: juaristi/filezilla
void CFilterManager::LoadFilters()
{
	if (m_loaded)
		return;

	m_loaded = true;

	CInterProcessMutex mutex(MUTEX_FILTERS);

	wxString file(wxGetApp().GetSettingsFile(_T("filters")));
	if (CLocalFileSystem::GetSize(file) < 1) {
		file = wxGetApp().GetResourceDir().GetPath() + _T("defaultfilters.xml");
	}

	CXmlFile xml(file);
	TiXmlElement* pDocument = xml.Load();
	if (!pDocument) {
		wxString msg = xml.GetError() + _T("\n\n") + _("Any changes made to the filters will not be saved.");
		wxMessageBoxEx(msg, _("Error loading xml file"), wxICON_ERROR);

		return;
	}

	TiXmlElement *pFilters = pDocument->FirstChildElement("Filters");

	if (!pFilters)
		return;

	TiXmlElement *pFilter = pFilters->FirstChildElement("Filter");
	while (pFilter) {
		CFilter filter;

		bool loaded = LoadFilter(pFilter, filter);

		if (loaded && !filter.name.empty() && !filter.filters.empty())
			m_globalFilters.push_back(filter);

		pFilter = pFilter->NextSiblingElement("Filter");
	}

	CompileRegexes();

	TiXmlElement* pSets = pDocument->FirstChildElement("Sets");
	if (!pSets)
		return;

	for (TiXmlElement* pSet = pSets->FirstChildElement("Set"); pSet; pSet = pSet->NextSiblingElement("Set")) {
		CFilterSet set;
		TiXmlElement* pItem = pSet->FirstChildElement("Item");
		while (pItem) {
			wxString local = GetTextElement(pItem, "Local");
			wxString remote = GetTextElement(pItem, "Remote");
			set.local.push_back(local == _T("1") ? true : false);
			set.remote.push_back(remote == _T("1") ? true : false);

			pItem = pItem->NextSiblingElement("Item");
		}

		if (!m_globalFilterSets.empty()) {
			set.name = GetTextElement(pSet, "Name");
			if (set.name.empty())
				continue;
		}

		if (set.local.size() == m_globalFilters.size())
			m_globalFilterSets.push_back(set);
	}

	wxString attribute = GetTextAttribute(pSets, "Current");
	unsigned long value;
	if (attribute.ToULong(&value)) {
		if (value < m_globalFilterSets.size())
			m_globalCurrentFilterSet = value;
	}
}
コード例 #27
0
StdMesh *StdMeshLoader::LoadMeshXml(const char* xml_data, size_t size, const StdMeshMatManager& manager, StdMeshSkeletonLoader& skel_loader, const char* filename)
{
	StdMeshXML xml(filename ? filename : "<unknown>", xml_data);

	std::unique_ptr<StdMesh> mesh(new StdMesh);

	TiXmlElement* mesh_elem = xml.RequireFirstChild(NULL, "mesh");

	// Load shared geometry, if any
	TiXmlElement* sharedgeometry_elem = mesh_elem->FirstChildElement("sharedgeometry");
	if(sharedgeometry_elem != NULL)
		xml.LoadGeometry(*mesh, mesh->SharedVertices, sharedgeometry_elem);

	TiXmlElement* submeshes_elem = xml.RequireFirstChild(mesh_elem, "submeshes");

	TiXmlElement* submesh_elem_base = xml.RequireFirstChild(submeshes_elem, "submesh");
	for (TiXmlElement* submesh_elem = submesh_elem_base; submesh_elem != NULL; submesh_elem = submesh_elem->NextSiblingElement("submesh"))
	{
		mesh->SubMeshes.push_back(StdSubMesh());
		StdSubMesh& submesh = mesh->SubMeshes.back();

		const char* material = xml.RequireStrAttribute(submesh_elem, "material");
		submesh.Material = manager.GetMaterial(material);
		if (!submesh.Material)
			xml.Error(FormatString("There is no such material named '%s'", material), submesh_elem);

		const char* usesharedvertices = submesh_elem->Attribute("usesharedvertices");
		const std::vector<StdMesh::Vertex>* vertices;
		if(!usesharedvertices || strcmp(usesharedvertices, "true") != 0)
		{
			TiXmlElement* geometry_elem = xml.RequireFirstChild(submesh_elem, "geometry");
			xml.LoadGeometry(*mesh, submesh.Vertices, geometry_elem);
			vertices = &submesh.Vertices;
		}
		else
		{
			if(mesh->SharedVertices.empty())
				xml.Error(StdCopyStrBuf("Submesh specifies to use shared vertices but there is no shared geometry"), submesh_elem);
			vertices = &mesh->SharedVertices;
		}

		TiXmlElement* faces_elem = xml.RequireFirstChild(submesh_elem, "faces");
		int FaceCount = xml.RequireIntAttribute(faces_elem, "count");
		submesh.Faces.resize(FaceCount);

		unsigned int i = 0;
		for (TiXmlElement* face_elem = faces_elem->FirstChildElement("face"); face_elem != NULL && i < submesh.Faces.size(); face_elem = face_elem->NextSiblingElement("face"), ++i)
		{
			int v[3];

			v[0] = xml.RequireIntAttribute(face_elem, "v1");
			v[1] = xml.RequireIntAttribute(face_elem, "v2");
			v[2] = xml.RequireIntAttribute(face_elem, "v3");

			for (unsigned int j = 0; j < 3; ++j)
			{
				if (v[j] < 0 || static_cast<unsigned int>(v[j]) >= vertices->size())
					xml.Error(FormatString("Vertex index v%u (%d) is out of range", j+1, v[j]), face_elem);
				submesh.Faces[i].Vertices[j] = v[j];
			}
		}
	}

	// We allow bounding box to be empty if it's only due to Z direction since
	// this is what goes inside the screen in Clonk.
	if(mesh->BoundingBox.x1 == mesh->BoundingBox.x2 || mesh->BoundingBox.y1 == mesh->BoundingBox.y2)
		xml.Error(StdCopyStrBuf("Bounding box is empty"), mesh_elem);

	// Read skeleton, if any
	TiXmlElement* skeletonlink_elem = mesh_elem->FirstChildElement("skeletonlink");
	if (skeletonlink_elem)
	{
		const char* name = xml.RequireStrAttribute(skeletonlink_elem, "name");
		StdCopyStrBuf xml_filename(name); xml_filename.Append(".xml");

		StdCopyStrBuf skeleton_filename;
		StdMeshSkeletonLoader::MakeFullSkeletonPath(skeleton_filename, filename, xml_filename.getData());

		mesh->Skeleton = skel_loader.GetSkeletonByName(skeleton_filename);
		if (!mesh->Skeleton) xml.Error(FormatString("Failed to load '%s'", skeleton_filename.getData()), skeletonlink_elem);

		// Vertex<->Bone assignments for shared geometry
		if (sharedgeometry_elem)
		{
			TiXmlElement* boneassignments_elem = xml.RequireFirstChild(mesh_elem, "boneassignments");
			xml.LoadBoneAssignments(*mesh, mesh->SharedVertices, boneassignments_elem);
		}

		// Vertex<->Bone assignments for all vertices (need to go through SubMeshes again...)
		unsigned int submesh_index = 0;
		for (TiXmlElement* submesh_elem = submesh_elem_base; submesh_elem != NULL; submesh_elem = submesh_elem->NextSiblingElement("submesh"), ++submesh_index)
		{
			StdSubMesh& submesh = mesh->SubMeshes[submesh_index];
			if (!submesh.Vertices.empty())
			{
				TiXmlElement* boneassignments_elem = xml.RequireFirstChild(submesh_elem, "boneassignments");
				xml.LoadBoneAssignments(*mesh, submesh.Vertices, boneassignments_elem);
			}
		}
	}
	else
	{
		// Mesh has no skeleton
		// Bone assignements do not make sense then, as the
		// actual bones are defined in the skeleton file.
		for (TiXmlElement* submesh_elem = submesh_elem_base; submesh_elem != NULL; submesh_elem = submesh_elem->NextSiblingElement("submesh"))
		{
			TiXmlElement* boneassignments_elem = submesh_elem->FirstChildElement("boneassignments");
			if (boneassignments_elem)
				xml.Error(StdStrBuf("Mesh has bone assignments, but no skeleton"), boneassignments_elem);
		}

		TiXmlElement* boneassignments_elem = mesh_elem->FirstChildElement("boneassignments");
		if (boneassignments_elem)
			xml.Error(StdStrBuf("Mesh has bone assignments, but no skeleton"), boneassignments_elem);
	}

	return mesh.release();
}
コード例 #28
0
ファイル: bsod.cpp プロジェクト: trunca/novale-viejo
void bsodFatal(const char *component)
{
	/* show no more than one bsod while shutting down/crashing */
	if (bsodhandled) return;
	bsodhandled = true;

	std::string lines = getLogBuffer();

		/* find python-tracebacks, and extract "  File "-strings */
	size_t start = 0;

	std::string crash_emailaddr = CRASH_EMAILADDR;
	std::string crash_component = "enigma2";

	if (component)
		crash_component = component;
	else
	{
		while ((start = lines.find("\n  File \"", start)) != std::string::npos)
		{
			start += 9;
			size_t end = lines.find("\"", start);
			if (end == std::string::npos)
				break;
			end = lines.rfind("/", end);
				/* skip a potential prefix to the path */
			unsigned int path_prefix = lines.find("/usr/", start);
			if (path_prefix != std::string::npos && path_prefix < end)
				start = path_prefix;

			if (end == std::string::npos)
				break;

			std::string filename(lines.substr(start, end - start) + INFOFILE);
			std::ifstream in(filename.c_str());
			if (in.good()) {
				std::getline(in, crash_emailaddr) && std::getline(in, crash_component);
				in.close();
			}
		}
	}

	FILE *f;
	const char* crashlog_name;
	std::ostringstream os;
	os << "/media/hdd/enigma2_crash_";
	os << time(0);
	os << ".log";
	crashlog_name = os.str().c_str();
	f = fopen(crashlog_name, "wb");

	if (f == NULL)
	{
		/* No hardisk. If there is a crash log in /home/root, leave it
		 * alone because we may be in a crash loop and writing this file
		 * all night long may damage the flash. Also, usually the first
		 * crash log is the most interesting one. */
		crashlog_name = "/home/root/enigma2_crash.log";
		if ((access(crashlog_name, F_OK) == 0) ||
		    ((f = fopen(crashlog_name, "wb")) == NULL))
		{
			/* Re-write the same file in /tmp/ because it's expected to
			 * be in RAM. So the first crash log will end up in /home
			 * and the last in /tmp */
			crashlog_name = "/tmp/enigma2_crash.log";
			f = fopen(crashlog_name, "wb");
		}
	}

	if (f)
	{
		time_t t = time(0);
		struct tm tm;
		char tm_str[32];

		localtime_r(&t, &tm);
		strftime(tm_str, sizeof(tm_str), "%a %b %_d %T %Y", &tm);

		XmlGenerator xml(f);

		xml.open("sfteam");

		xml.open("enigma2");
		xml.string("crashdate", tm_str);
		xml.string("compiledate", __DATE__);
		xml.string("contactemail", crash_emailaddr);
		xml.comment("Please email this crashlog to above address");

		xml.string("skin", getConfigString("config.skin.primary_skin", "Default Skin"));
		xml.string("sourcedate", enigma2_date);
		xml.string("branch", enigma2_branch);
		xml.string("rev", enigma2_rev);
		xml.string("version", PACKAGE_VERSION);
		xml.close();

		xml.open("image");
		if(access("/proc/stb/info/boxtype", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/boxtype");
		}
		else if (access("/proc/stb/info/vumodel", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/vumodel");
		}
		else if (access("/proc/stb/info/model", F_OK) != -1) {
			xml.stringFromFile("stbmodel", "/proc/stb/info/model");
		}
		xml.cDataFromCmd("kernelversion", "uname -a");
		xml.stringFromFile("kernelcmdline", "/proc/cmdline");
		xml.stringFromFile("nimsockets", "/proc/bus/nim_sockets");
		xml.cDataFromFile("imageversion", "/etc/image-version");
		xml.cDataFromFile("imageissue", "/etc/issue.net");
		xml.close();

		xml.open("crashlogs");
		xml.cDataFromString("enigma2crashlog", getLogBuffer());
		xml.close();

		xml.close();

		fclose(f);
	}

	ePtr<gMainDC> my_dc;
	gMainDC::getInstance(my_dc);

	gPainter p(my_dc);
	p.resetOffset();
	p.resetClip(eRect(ePoint(0, 0), my_dc->size()));
	p.setBackgroundColor(gRGB(0x008000));
	p.setForegroundColor(gRGB(0xFFFFFF));

	int hd =  my_dc->size().width() == 1920;
	ePtr<gFont> font = new gFont("Regular", hd ? 30 : 20);
	p.setFont(font);
	p.clear();

	eRect usable_area = eRect(hd ? 30 : 100, hd ? 30 : 70, my_dc->size().width() - (hd ? 60 : 150), hd ? 150 : 100);

	os.str("");
	os.clear();
	os << "We are really sorry. Your STB encountered "
		"a software problem, and needs to be restarted.\n"
		"Please send the logfile " << crashlog_name << " to " << crash_emailaddr << ".\n"
		"Your STB restarts in 10 seconds!\n"
		"Component: " << crash_component;

	p.renderText(usable_area, os.str().c_str(), gPainter::RT_WRAP|gPainter::RT_HALIGN_LEFT);

	usable_area = eRect(hd ? 30 : 100, hd ? 180 : 170, my_dc->size().width() - (hd ? 60 : 180), my_dc->size().height() - (hd ? 30 : 20));

	int i;

	start = std::string::npos + 1;
	for (i=0; i<20; ++i)
	{
		start = lines.rfind('\n', start - 1);
		if (start == std::string::npos)
		{
			start = 0;
			break;
		}
	}

	font = new gFont("Regular", hd ? 21 : 14);
	p.setFont(font);

	p.renderText(usable_area,
		lines.substr(start), gPainter::RT_HALIGN_LEFT);
	sleep(10);

	/*
	 * When 'component' is NULL, we are called because of a python exception.
	 * In that case, we'd prefer to to a clean shutdown of the C++ objects,
	 * and this should be safe, because the crash did not occur in the
	 * C++ part.
	 * However, when we got here for some other reason, a segfault probably,
	 * we prefer to stop immediately instead of performing a clean shutdown.
	 * We'd risk destroying things with every additional instruction we're
	 * executing here.
	 */
	if (component) raise(SIGKILL);
}
コード例 #29
0
ファイル: libmusicxml.cpp プロジェクト: iloveican/AscoGraph
static Sxmlattribute	__releaseAttr (TAttribute attr)					{ Sxmlattribute xml(attr); attr->removeReference(); return xml; }
コード例 #30
0
int main(int argc, char** argv)
{
    std::string filename;
    try
    {
        configuration config;
        std::string copyright_filename;

        // Read/get configuration
        {
            namespace po = boost::program_options;
            po::options_description description("=== doxml2qbk ===\nAllowed options");


            std::string convenience_headers;

            description.add_options()
                ("help", "Help message")
                ("xml", po::value<std::string>(&filename), 
                            "Name of XML file written by Doxygen")
                ("start_include", po::value<std::string>(&config.start_include), 
                            "Start include")
                ("convenience_header_path", po::value<std::string>(&config.convenience_header_path), 
                            "Convenience header path")
                ("convenience_headers", po::value<std::string>(&convenience_headers), 
                            "Convenience header(s) (comma-separated)")
                ("skip_namespace", po::value<std::string>(&config.skip_namespace), 
                            "Namespace to skip (e.g. boost::mylib::")
                ("copyright", po::value<std::string>(&copyright_filename), 
                            "Name of QBK file including (commented) copyright and license")
            ;

            po::variables_map varmap;

            if (argc == 2 && ! boost::starts_with(argv[1], "--"))
            {
                // (especially for debugging) options might go into an INI file
                std::ifstream config_file (argv[1], std::ifstream::in);
                po::store(po::parse_config_file(config_file, description), varmap);
            }
            else
            {
                po::store(po::parse_command_line(argc, argv, description), varmap);
            }

            po::notify(varmap);

            if (varmap.count("help") || filename.empty())
            {
                std::cout << description << std::endl;
                return 1;
            }

            // Split CSV with headerfile names into configuration
            if (! convenience_headers.empty())
            {
                boost::split(config.convenience_headers, convenience_headers, boost::is_any_of(","));
            }
        }

        // Read files into strings
        std::string xml_string = file_to_string(filename);
        std::string license = copyright_filename.empty() 
            ? "" 
            : file_to_string(copyright_filename);

        // Parse the XML outputted by Doxygen
        xml_doc xml(xml_string.c_str());

        documentation doc;
        parse(xml.first_node(), config, doc);

        // Check for duplicate function names
        for (std::size_t i = 0; i < doc.functions.size(); i++)
        {
            function& f1 = doc.functions[i];
            for (std::size_t j = i + 1; j < doc.functions.size(); j++)
            {
                function& f2 = doc.functions[j];

                if (f1.name == f2.name)
                {
                    // It is not a unique function, so e.g. an overload,
                    // so a description must distinguish them.
                    // Difference is either the number of parameters, or a const / non-const version
                    // Use the "\qbk{distinguish,with strategy}" in the source code to distinguish
                    f1.unique = false;
                    f2.unique = false;
                }
            }
        }


        // Write copyright/license (keep inspect silent)
        if (! license.empty())
        {
            std::cout << license << std::endl;
        }

        // Write warning comment
        std::cout
            << "[/ Generated by doxygen_xml2qbk, don't change, will be overwritten automatically]" << std::endl
            << "[/ Generated from " << filename << "]" << std::endl;

        // Write the rest: functions, defines, classes or structs
        BOOST_FOREACH(function const& f, doc.functions)
        {
            quickbook_output(f, config, std::cout);
        }
        BOOST_FOREACH(function const& f, doc.defines)
        {
            quickbook_output(f, config, std::cout);
        }
        BOOST_FOREACH(enumeration const& e, doc.enumerations)
        {
            quickbook_output(e, config, std::cout);
        }

        if (! doc.cos.name.empty())
        {
            std::sort(doc.cos.functions.begin(), doc.cos.functions.end(), sort_on_line<function>());
            quickbook_output(doc.cos, config, std::cout);
        }

    }
    catch(std::exception const& e)
    {
        std::cerr << "Exception in doxygen_xml2qbk: " << std::endl
            << "   Message: " << e.what() << std::endl
            << "   File: " << filename << std::endl
            << "   Type: " << typeid(e).name() << std::endl
            << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "Unknown exception in doxygen_xml2qbk" 
            << std::endl;
        return 1;
    }
    return 0;
}