//--------------------------------------------------------- bool CFilter_LoG::On_Execute(void) { //----------------------------------------------------- if( !Initialise() ) { return( false ); } //----------------------------------------------------- m_pInput = Parameters("INPUT")->asGrid(); CSG_Grid Result, *pResult = Parameters("RESULT")->asGrid(); if( !pResult || pResult == m_pInput ) { pResult = &Result; pResult->Create(m_pInput); } else { pResult->Set_Name(CSG_String::Format("%s [%s]", m_pInput->Get_Name(), _TL("Laplace Filter"))); pResult->Set_NoData_Value(m_pInput->Get_NoData_Value()); } //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( m_pInput->is_InGrid(x, y) ) { pResult->Set_Value(x, y, Get_Value(x, y)); } else { pResult->Set_NoData(x, y); } } } //----------------------------------------------------- if( pResult == &Result ) { CSG_MetaData History = m_pInput->Get_History(); m_pInput->Assign(pResult); m_pInput->Get_History() = History; DataObject_Update(m_pInput); Parameters("RESULT")->Set_Value(m_pInput); } DataObject_Set_Colors(pResult, 100, SG_COLORS_BLACK_WHITE); m_Kernel.Destroy(); return( true ); }
CMOOSDBHTTPServer::CMOOSDBHTTPServer(long lDBPort, long lWebServerPort) { Initialise(lDBPort, lWebServerPort); }
BoundedArray<T>::BoundedArray(unsigned int _numElements) { Initialise( _numElements ); }
CSystemTray::CSystemTray() { Initialise(); }
Point::Point() { Initialise(); }
void MoveHeroTo(int row, int column) // Ћогика движени¤ геро¤ { unsigned char destinationCell = levelData[row][column]; bool canMoveToCell = false; // √ерой не может пройти в ¤чейку switch (destinationCell) { // —вободна¤ ¤чейка case ' ': { canMoveToCell = true; // √ерой может пройти в ¤чейку break; } // ячейка-выход с ключом case symbolExitKey: { if (isKey) { // ѕереход на следующий уровень ++level; if (level < levelCount) Initialise(); else isGameActive = false; } isKey = false; break; } // ячейка-выход с расставленными ¤щиками case symbolBoxExit: { if (filledBoxArea == boxAreaCount) { // ѕереход на следующий уровень ++level; if (level < 15) Initialise(); else isGameActive = false; } break; } // ячейка-выход case symbolExit: { if (collectedCrystals == crystalsCount) { // ѕереход на следующий уровень ++level; if (level < levelCount) Initialise(); else isGameActive = false; } break; } // ячейка-мина case symbolMine: { Initialise(); break; } // ячейка-кристалл case symbolCrystal: { canMoveToCell = true; collectedCrystals++; break; } // ячейка-ключ case symbolKey: { canMoveToCell = true; isKey = true; break; } // ячейка места дл¤ ¤щика case symbolBoxArea: { canMoveToCell = true; break; } // ячейка-¤щик case symbolBox: { // –асчЄт направлени¤ движени¤ геро¤: int heroDirectionR = row - heroRow; int heroDirectionC = column - heroColumn; // ѕроверка на наличие свободной ¤чейки за ¤щиком: if (levelData[row + heroDirectionR][column + heroDirectionC] == ' ') { canMoveToCell = true; if (levelData0[level][row][column] == 'B') filledBoxArea--; // ”даление ¤щика с его нынешней ¤чейки и замена этой ¤чейки на пустую: levelData[row][column] = ' '; // ѕеремещение ¤щика на новую ¤чейку: levelData[row + heroDirectionR][column + heroDirectionC] = symbolBox; } // ѕроверка на наличие свободного места дл¤ ¤щика за ¤щиком: if (levelData[row + heroDirectionR][column + heroDirectionC] == symbolBoxArea) { canMoveToCell = true; // ”даление ¤щика с его нынешней ¤чейки и замена этой ¤чейки на пустую: levelData[row][column] = ' '; // ѕеремещение ¤щика на новую ¤чейку: levelData[row + heroDirectionR][column + heroDirectionC] = symbolBox; filledBoxArea++; } break; } } if (canMoveToCell) { // ”даление геро¤ с его нынешней ¤чейки и замена этой ¤чейки на ¤чейку места дл¤ ¤щика: if (levelData0[level][heroRow][heroColumn] == 'B') { levelData[heroRow][heroColumn] = symbolBoxArea; heroRow = row; heroColumn = column; levelData[heroRow][heroColumn] = symbolHero; } // ”даление геро¤ с его нынешней ¤чейки и замена этой ¤чейки на пустую: levelData[heroRow][heroColumn] = ' '; // ”становка новой ¤чейки дл¤ геро¤: heroRow = row; heroColumn = column; // ѕеремещение геро¤ на новую ¤чейку: levelData[heroRow][heroColumn] = symbolHero; } }
void MathPluginManagement::ProcessSwitchProperties(Telescope* pTelescope, const char *name, ISState *states, char *names[], int n) { DEBUGFDEVICE(pTelescope->getDeviceName(), INDI::Logger::DBG_DEBUG, "ProcessSwitchProperties - name(%s)", name); if (strcmp(name, AlignmentSubsystemMathPluginsV.name) == 0) { int CurrentPlugin = IUFindOnSwitchIndex(&AlignmentSubsystemMathPluginsV); IUUpdateSwitch(&AlignmentSubsystemMathPluginsV, states, names, n); AlignmentSubsystemMathPluginsV.s = IPS_OK; // Assume OK for the time being int NewPlugin = IUFindOnSwitchIndex(&AlignmentSubsystemMathPluginsV); if (NewPlugin != CurrentPlugin) { // New plugin requested // Unload old plugin if required if (0 != CurrentPlugin) { typedef void Destroy_t(MathPlugin *); Destroy_t* Destroy = (Destroy_t*)dlsym(LoadedMathPluginHandle, "Destroy"); if (NULL != Destroy) { Destroy(pLoadedMathPlugin); pLoadedMathPlugin = NULL; if (0 == dlclose(LoadedMathPluginHandle)) { LoadedMathPluginHandle = NULL; } else { IDLog("MathPluginManagement - dlclose failed on loaded plugin - %s\n", dlerror()); AlignmentSubsystemMathPluginsV.s = IPS_ALERT; } } else { IDLog("MathPluginManagement - cannot get Destroy function - %s\n", dlerror()); AlignmentSubsystemMathPluginsV.s = IPS_ALERT; } } // Load the requested plugin if required if (0 != NewPlugin) { std::string PluginPath(MathPluginFiles[NewPlugin - 1]); if (NULL != (LoadedMathPluginHandle = dlopen(PluginPath.c_str(), RTLD_NOW))) { typedef MathPlugin* Create_t(); Create_t* Create = (Create_t*)dlsym(LoadedMathPluginHandle, "Create"); if (NULL != Create) { pLoadedMathPlugin = Create(); IUSaveText(&AlignmentSubsystemCurrentMathPlugin, PluginPath.c_str()); } else { IDLog("MathPluginManagement - cannot get Create function - %s\n", dlerror()); AlignmentSubsystemMathPluginsV.s = IPS_ALERT; } } else { IDLog("MathPluginManagement - cannot load plugin %s error %s\n", PluginPath.c_str(), dlerror()); AlignmentSubsystemMathPluginsV.s = IPS_ALERT; } } else { // It is in built plugin just set up the pointers pLoadedMathPlugin = &BuiltInPlugin; } } // Update client IDSetSwitch(&AlignmentSubsystemMathPluginsV, NULL); } else if (strcmp(name, AlignmentSubsystemMathPluginInitialiseV.name) == 0) { AlignmentSubsystemMathPluginInitialiseV.s = IPS_OK; IUResetSwitch(&AlignmentSubsystemMathPluginInitialiseV); // Update client display IDSetSwitch(&AlignmentSubsystemMathPluginInitialiseV, NULL); // Initialise or reinitialise the current math plugin Initialise(CurrentInMemoryDatabase); } else if (strcmp(name, AlignmentSubsystemActiveV.name) == 0) { AlignmentSubsystemActiveV.s=IPS_OK; if (0 == IUUpdateSwitch(&AlignmentSubsystemActiveV, states, names, n)) // Update client IDSetSwitch(&AlignmentSubsystemActiveV, NULL); } }
DataIndices::DataIndices( const unsigned& x, const unsigned& y, const unsigned& z ) { Initialise( x, y, z ); }
DataIndices::DataIndices( const unsigned& x, const unsigned& y ) { Initialise( x, y, 0 ); }
void VideoVisualSpectrum::Draw(const QRect &area, MythPainter *painter, QPaintDevice* device) { if (m_disabled) return; mutex()->lock(); VisualNode *node = GetNode(); if (area.isEmpty() || !painter) { mutex()->unlock(); return; } if (!Initialise(area)) { mutex()->unlock(); return; } uint i = 0; if (node) { i = node->length; fast_real_set_from_short(lin, node->left, node->length); if (node->right) fast_real_set_from_short(rin, node->right, node->length); } mutex()->unlock(); fast_reals_set(lin + i, rin + i, 0, FFTW_N - i); fftw_execute(lplan); fftw_execute(rplan); double magL, magR, tmp; double falloff = (((double)SetLastUpdate()) / 40.0) * m_falloff; if (falloff < 0.0) falloff = 0.0; if (falloff > 2048.0) falloff = 2048.0; for (int l = 0, r = m_scale.range(); l < m_scale.range(); l++, r++) { int index = m_scale[l]; magL = (log(sq(real(lout[index])) + sq(real(lout[FFTW_N - index]))) - 22.0) * m_scaleFactor; magR = (log(sq(real(rout[index])) + sq(real(rout[FFTW_N - index]))) - 22.0) * m_scaleFactor; if (magL > m_range) magL = 1.0; if (magL < m_magnitudes[l]) { tmp = m_magnitudes[l] - falloff; if (tmp < magL) tmp = magL; magL = tmp; } if (magL < 1.0) magL = 1.0; if (magR > m_range) magR = 1.0; if (magR < m_magnitudes[r]) { tmp = m_magnitudes[r] - falloff; if (tmp < magR) tmp = magR; magR = tmp; } if (magR < 1.0) magR = 1.0; m_magnitudes[l] = magL; m_magnitudes[r] = magR; } DrawPriv(painter, device); }
CSensorDataFilter::CSensorDataFilter() { Initialise(); }
CColourPopup::CColourPopup() { Initialise(); }
int main(int argc, char *argv[]) { char *datafn, *s; int nSeg; void Initialise(void); void LoadFile(char *fn); void EstimateModel(void); void SaveModel(char *outfn); if(InitShell(argc,argv,hinit_version,hinit_vc_id)<SUCCESS) HError(2100,"HInit: InitShell failed"); InitMem(); InitLabel(); InitMath(); InitSigP(); InitWave(); InitAudio(); InitVQ(); InitModel(); if(InitParm()<SUCCESS) HError(2100,"HInit: InitParm failed"); InitTrain(); InitUtil(); if (!InfoPrinted() && NumArgs() == 0) ReportUsage(); if (NumArgs() == 0) Exit(0); SetConfParms(); CreateHMMSet(&hset,&gstack,FALSE); while (NextArg() == SWITCHARG) { s = GetSwtArg(); if (strlen(s)!=1) HError(2119,"HInit: Bad switch %s; must be single letter",s); switch(s[0]){ case 'e': epsilon = GetChkedFlt(0.0,1.0,s); break; case 'g': ignOutVec = FALSE; break; case 'i': maxIter = GetChkedInt(0,100,s); break; case 'l': if (NextArg() != STRINGARG) HError(2119,"HInit: Segment label expected"); segLab = GetStrArg(); break; case 'm': minSeg = GetChkedInt(1,1000,s); break; case 'n': newModel = FALSE; break; case 'o': outfn = GetStrArg(); break; case 'u': SetuFlags(); break; case 'v': minVar = GetChkedFlt(0.0,10.0,s); break; case 'w': mixWeightFloor = MINMIX * GetChkedFlt(0.0,100000.0,s); break; case 'B': saveBinary = TRUE; break; case 'F': if (NextArg() != STRINGARG) HError(2119,"HInit: Data File format expected"); if((dff = Str2Format(GetStrArg())) == ALIEN) HError(-2189,"HInit: Warning ALIEN Data file format set"); break; case 'G': if (NextArg() != STRINGARG) HError(2119,"HInit: Label File format expected"); if((lff = Str2Format(GetStrArg())) == ALIEN) HError(-2189,"HInit: Warning ALIEN Label file format set"); break; case 'H': if (NextArg() != STRINGARG) HError(2119,"HInit: HMM macro file name expected"); AddMMF(&hset,GetStrArg()); break; case 'I': if (NextArg() != STRINGARG) HError(2119,"HInit: MLF file name expected"); LoadMasterFile(GetStrArg()); break; case 'L': if (NextArg()!=STRINGARG) HError(2119,"HInit: Label file directory expected"); labDir = GetStrArg(); break; case 'M': if (NextArg()!=STRINGARG) HError(2119,"HInit: Output macro file directory expected"); outDir = GetStrArg(); break; case 'T': if (NextArg() != INTARG) HError(2119,"HInit: Trace value expected"); trace = GetChkedInt(0,01777,s); break; case 'X': if (NextArg()!=STRINGARG) HError(2119,"HInit: Label file extension expected"); labExt = GetStrArg(); break; default: HError(2119,"HInit: Unknown switch %s",s); } } if (NextArg()!=STRINGARG) HError(2119,"HInit: source HMM file name expected"); hmmfn = GetStrArg(); Initialise(); do { if (NextArg()!=STRINGARG) HError(2119,"HInit: training data file name expected"); datafn = GetStrArg(); LoadFile(datafn); } while (NumArgs()>0); nSeg = NumSegs(segStore); if (nSeg < minSeg) HError(2121,"HInit: Too Few Observation Sequences [%d]",nSeg); if (trace&T_TOP) { printf("%d Observation Sequences Loaded\n",nSeg); fflush(stdout); } EstimateModel(); SaveModel(outfn); if (trace&T_TOP) printf("Output written to directory %s\n", outDir==NULL?"current":outDir); InitMem(); InitLabel(); InitMath(); InitSigP(); InitWave(); InitAudio(); InitVQ(); InitModel(); if(InitParm()<SUCCESS) HError(2100,"HInit: InitParm failed"); InitTrain(); InitUtil(); ResetUtil(); ResetTrain(); ResetParm(); ResetModel(); ResetVQ(); ResetAudio(); ResetWave(); ResetSigP(); ResetMath(); ResetLabel(); ResetMem(); ResetShell(); Exit(0); return (0); /* never reached -- make compiler happy */ }
Logger::Logger() { Initialise(); }
int main(int argc, char *argv[]) { MPI_Comm CommWorld; int rank; int procCount; int procToWatch; Dictionary* dictionary; ExtensionManager_Register* extensionMgr_Register; Topology* nTopology; ElementLayout* eLayout; NodeLayout* nLayout; MeshDecomp* decomp; MeshLayout* ml; Mesh* mesh; Stream* stream; /* Initialise MPI, get world info */ MPI_Init(&argc, &argv); MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld ); MPI_Comm_size(CommWorld, &procCount); MPI_Comm_rank(CommWorld, &rank); Base_Init( &argc, &argv ); DiscretisationGeometry_Init( &argc, &argv ); DiscretisationShape_Init( &argc, &argv ); DiscretisationMesh_Init( &argc, &argv ); stream = Journal_Register (Info_Type, "myStream"); procToWatch = argc >= 2 ? atoi(argv[1]) : 0; dictionary = Dictionary_New(); Dictionary_Add( dictionary, "rank", Dictionary_Entry_Value_FromUnsignedInt( rank ) ); Dictionary_Add( dictionary, "numProcessors", Dictionary_Entry_Value_FromUnsignedInt( procCount ) ); Dictionary_Add( dictionary, "meshSizeI", Dictionary_Entry_Value_FromUnsignedInt( 7 ) ); Dictionary_Add( dictionary, "meshSizeJ", Dictionary_Entry_Value_FromUnsignedInt( 7 ) ); Dictionary_Add( dictionary, "meshSizeK", Dictionary_Entry_Value_FromUnsignedInt( 7 ) ); Dictionary_Add( dictionary, "allowUnusedCPUs", Dictionary_Entry_Value_FromBool( False ) ); Dictionary_Add( dictionary, "allowPartitionOnNode", Dictionary_Entry_Value_FromBool( True ) ); Dictionary_Add( dictionary, "allowUnbalancing", Dictionary_Entry_Value_FromBool( False ) ); Dictionary_Add( dictionary, "shadowDepth", Dictionary_Entry_Value_FromUnsignedInt( 1 ) ); nTopology = (Topology*)IJK6Topology_New( "IJK6Topology", dictionary ); eLayout = (ElementLayout*)ParallelPipedHexaEL_New( "PPHexaEL", 3, dictionary ); nLayout = (NodeLayout*)CornerNL_New( "CornerNL", dictionary, eLayout, nTopology ); decomp = (MeshDecomp*)HexaMD_New( "HexaMD", dictionary, MPI_COMM_WORLD, eLayout, nLayout ); ml = MeshLayout_New( "MeshLayout", eLayout, nLayout, decomp ); extensionMgr_Register = ExtensionManager_Register_New(); mesh = Mesh_New( "Mesh", ml, sizeof(Node), sizeof(Element), extensionMgr_Register, dictionary ); mesh->buildNodeLocalToGlobalMap = True; mesh->buildNodeDomainToGlobalMap = True; mesh->buildNodeGlobalToLocalMap = True; mesh->buildNodeGlobalToDomainMap = True; mesh->buildNodeNeighbourTbl = True; mesh->buildNodeElementTbl = True; mesh->buildElementLocalToGlobalMap = True; mesh->buildElementDomainToGlobalMap = True; mesh->buildElementGlobalToDomainMap = True; mesh->buildElementGlobalToLocalMap = True; mesh->buildElementNeighbourTbl = True; mesh->buildElementNodeTbl = True; Build( mesh, 0, False ); Initialise(mesh, 0, False ); if (rank == procToWatch) { Node_Index currElementNodesCount=0; Node_Index* currElementNodes = NULL; Element_Index element_dI = 0; Node_Index refNode_eI = 0; Node_Index node_Diagonal = 0; Node_Index node_Diagonal_gI = 0; // only use this while setting up the test //Print(mesh, stream); // Some tests involving RegularMeshUtils_GetDiagOppositeAcrossElementNodeIndex() for (element_dI=0; element_dI < mesh->elementDomainCount; element_dI++) { currElementNodes = mesh->elementNodeTbl[element_dI]; currElementNodesCount = mesh->elementNodeCountTbl[element_dI]; for (refNode_eI = 0; refNode_eI < currElementNodesCount; refNode_eI++ ) { node_Diagonal = RegularMeshUtils_GetDiagOppositeAcrossElementNodeIndex(mesh, element_dI, currElementNodes[refNode_eI]) ; node_Diagonal_gI = Mesh_NodeMapDomainToGlobal( mesh, node_Diagonal ); //print message stating: Element #, curr node #, diag opp node # printf("Element #: %d, Current Node #: %d, Diagonal Node #: %d, (%d) \n", element_dI, currElementNodes[refNode_eI], node_Diagonal, node_Diagonal_gI); } } } Stg_Class_Delete(mesh); Stg_Class_Delete(ml); Stg_Class_Delete(decomp); Stg_Class_Delete(nLayout); Stg_Class_Delete(eLayout); Stg_Class_Delete( nTopology ); Stg_Class_Delete(dictionary); DiscretisationMesh_Finalise(); DiscretisationShape_Finalise(); DiscretisationGeometry_Finalise(); Base_Finalise(); /* Close off MPI */ MPI_Finalize(); return 0; /* success */ }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- tMFDDigitalDataManager::tMFDDigitalDataManager( tISettingsWriterFactory& settingsWriterFactory, tNMEA0183Settings* pNMEA0183Settings, tDigitalDataConfig& digitalDataConfig, tNDP2k& ndp2k, tNDP2kDeviceSelection& ndp2kDeviceSelection, tConvert& convert, tLoran& loran, tUnitsSettings& unitsSettings, tHAL& hal, tGpsInternalProxy& gpsInternalProxy, tSerialPortManager& serialPortManager, tSerialSettings& serialSettings, tNetworkMonitor& networkMonitor, bool createTestAppNetworkProxy ) : tDigitalDataManager( settingsWriterFactory, pNMEA0183Settings, digitalDataConfig, ndp2k, hal, ndp2kDeviceSelection, convert, &loran, unitsSettings) , m_GpsInternalProxy(gpsInternalProxy) , m_SerialPortManager(serialPortManager) , m_NetworkMonitor(networkMonitor) , m_CreateTestAppNetworkProxy(createTestAppNetworkProxy) { if ( (m_DigitalDataConfig.TimePlotsAllowed()) || (m_DigitalDataConfig.WindPlotsAllowed()) ) { tDigitalTimePlotDataManager::CreateInstance(); } // Create and register the MFD specialized digital data engines { { // Navigation Data Engine tNavigationDataEngine::tConfig config = { tNavigationDataEngine::tSailingFeaturesAllowed( m_DigitalDataConfig.SailingFeaturesAllowed() ) }; m_pNavigationDataEngine = new tNavigationDataEngine(config); // Connect the NavigationDataEngine to UDB Connect( UDB::GetUDBWpRtDB()->asQObject(), SIGNAL( DBUpdated( const tWaypoint&, tUDBCmdType ) ), m_pNavigationDataEngine, SLOT( OnWaypointUpdated( const tWaypoint&, tUDBCmdType ) ) ); Connect( UDB::GetUDBWpRtDB()->asQObject(), SIGNAL( DBUpdated( const tRoute&, tUDBCmdType ) ), m_pNavigationDataEngine, SLOT( OnRouteUpdated( const tRoute&, tUDBCmdType ) ) ); Connect( UDB::GetUDBWpRtDB()->asQObject(), SIGNAL( DBReloaded() ), m_pNavigationDataEngine, SLOT( OnDbReloaded() ) ); Connect( UDB::GetUDBVariablesDB()->asQObject(), SIGNAL( NavVariablesChanged( const quint64&, const QVariant ) ), m_pNavigationDataEngine, SLOT( OnUDBVariablesChanged( const quint64&, const QVariant ) ) ); Connect( UDB::GetUDBVariablesDB()->asQObject(), SIGNAL( DBReloaded() ), m_pNavigationDataEngine, SLOT( OnVariablesReloaded() ) ); m_pNavigationDataEngine->OnVariablesReloaded(); // check if already navigating at startup // Inform interested parties whether we are navigating or not Connect( m_pNavigationDataEngine, SIGNAL(NavigatingChanged(bool)), m_pAutoGpsDataEngine, SLOT(SetNavigating(bool)) ); m_pAutoGpsDataEngine->SetNavigating(m_pNavigationDataEngine->Navigating()); RegisterDataEngine( DATA_ENGINE_NAVIGATION, m_pNavigationDataEngine ); } { // NMEA0183 QList<tSerialPort::eComPort> serialPorts; for(unsigned int i = 0; i < hal.IOInterface()->NumSerialPorts(); i++) { serialPorts << static_cast<tSerialPort::eComPort>(hal.IOInterface()->SerialPortNumber(i+1)); } tNMEA0183::tConfig config = { tUtc (boost::bind(&tSystemDateTime::CurrentDateTimeUtc, hal.SystemDateTime())), tGlcSentence (boost::bind(&tLoran::GetGlcSentence, &loran, _1)), hal.GPSChipset(), tNMEA0183::tHaveIgps (hal.IOInterface()->HaveIGPS()), static_cast<tSerialPort::eComPort>(hal.IOInterface()->SerialPortNumber(0)), &gpsInternalProxy, serialPorts, tNMEA0183::tNMEA0183OverTcpAllowed(m_DigitalDataConfig.NMEA0183OverTcpAllowed()), Get0183OutTcpManager(), }; m_pNMEA0183 = new tNMEA0183( serialPortManager, *m_pNMEA0183Settings, serialSettings, *m_pNavigationDataEngine, tHAL::Instance()->IOInterface(), config); RegisterDataEngine( DATA_ENGINE_NMEA183, m_pNMEA0183 ); Connect( &m_DigitalDataConfig, SIGNAL(SimulatorEnabledChanged(bool)), m_pNMEA0183, SLOT(SetSimulatorEnabled(bool)) ); Connect( &m_DigitalDataConfig, SIGNAL(LocalTimeOffsetChanged(int)), m_pNMEA0183, SLOT(SetLocalTimeOffset(int)) ); Connect( m_pNMEA0183, SIGNAL(RequestExitAppRestart()), this, SIGNAL(RequestExitAppRestart())); Connect( m_pNMEA0183, SIGNAL(RequestExitTestMode()), this, SIGNAL(RequestExitTestMode())); Connect( m_pNMEA0183, SIGNAL(RequestExitBurnin()), this, SIGNAL(RequestExitBurnin())); m_pNMEA0183->SetSimulatorEnabled(m_DigitalDataConfig.SimulatorEnabled()); m_pNMEA0183->SetLocalTimeOffset(m_DigitalDataConfig.LocalTimeOffset()); } { m_pSimulateDataEngine = new tSimulateDataEngine(*m_pNavigationDataEngine, m_DigitalDataConfig.SailingFeaturesAllowed()); RegisterDataEngine( DATA_ENGINE_SIMULATE, m_pSimulateDataEngine ); QVector<tDataType> simulatedTypes = m_pSimulateDataEngine->SimulatedDataTypes(); m_pActiveDataEngine->SetSimulationTypes(simulatedTypes); } { int numEngines = tDigitalData::NumInstances(DATA_CATEGORY_ENGINE); int numTanks = tDigitalData::NumInstances(DATA_CATEGORY_FUEL_TANK); m_pFuelManagementEngine = new tFuelManagementEngine(numEngines, numTanks, *m_pFuelSettings); Connect(m_pSourceSelection, SIGNAL(NumInstancesChanged(int)), m_pFuelManagementEngine, SLOT(OnNumberInstancesChanged(int))); RegisterDataEngine( DATA_ENGINE_FUEL_MANAGEMENT, m_pFuelManagementEngine ); RegisterDataEngine( DATA_ENGINE_VESSEL_FUEL_MANAGEMENT, m_pFuelManagementEngine ); } } // Connection for tNMEA0183 Connect( m_pNMEA0183, SIGNAL( UtcTimeAndDateUpdated( const tDataId&, const QTime&, const QDate& ) ), this, SLOT( OnUtcTimeAndDateUpdated(const tDataId&, const QTime&, const QDate& ) ) ); // Connect signal to be notified when a 0183 MOB is received Connect(m_pNMEA0183, SIGNAL(MOBReceived(const tRCoord&, QString)), this, SIGNAL(MOBReceived(const tRCoord&, QString))); // Create the virtual device objects { char iGpsSource; if (m_pNMEA0183->GetIGPSSource(&iGpsSource)) { m_pIGPSVirtualDevice = new tInternalGPSVirtualDevice( iGpsSource, m_NDP2k, *m_pNMEA0183Settings, *m_pNDP2kDataEngine ); } if(m_DigitalDataConfig.Ndp2kNavVirtualDeviceAllowed() == true) { tNavigationVirtualDevice::tConfig config = { tNavigationVirtualDevice::tSailingFeaturesAllowed(m_DigitalDataConfig.SailingFeaturesAllowed()) }; m_pNavigationVirtualDevice = new tNavigationVirtualDevice( m_NDP2k, *m_pNavigationDataEngine, *m_pNDP2kDataEngine, config); Connect( &m_DigitalDataConfig, SIGNAL(LocalTimeOffsetChanged(int)), m_pNavigationVirtualDevice, SLOT(SetLocalTimeOffset(int)) ); m_pNavigationVirtualDevice->SetLocalTimeOffset(m_DigitalDataConfig.LocalTimeOffset()); m_pNavigationVirtualDevice->Initialise(); } // NMEA0183 Virtual Device(s) QList<char> nmea0183Sources = m_pNMEA0183->Get0183Sources(); if(nmea0183Sources.size() > 0) // Port 1 { m_pNMEA0183VirtualDevice1 = CreateAndConnectNMEA0183VirtualDevice(nmea0183Sources[0], tNDP2k::TxDeviceNmea0183Port1); } if(nmea0183Sources.size() > 1) // Port 2 { m_pNMEA0183VirtualDevice2 = CreateAndConnectNMEA0183VirtualDevice(nmea0183Sources[1], tNDP2k::TxDeviceNmea0183Port2); } }
Tree::Tree() { Initialise(); }
/* main: */ int main(int argc, char *argv[]) { char *s; char fname[MAXSTRLEN]; InitShell(argc, argv, hmgetool_version, hmgetool_vc_id); InitMem(); InitMath(); InitSigP(); InitWave(); InitLabel(); InitModel(); InitTrain(); InitParm(); InitUtil(); InitFB(); InitGen(); InitAdapt(&xfInfo, NULL); InitMTrain(); /* process argument */ if (NumArgs() == 0) ReportUsage(); CreateHeap(&hmmStack, "Model Stack", MSTAK, 1, 1.0, 80000, 4000000); CreateHeap(&orighmmStack, "Model Stack", MSTAK, 1, 1.0, 80000, 4000000); CreateHeap(&accStack, "Acc Stack", MSTAK, 1, 1.0, 80000, 400000); CreateHeap(&genStack, "Gen Stack", MSTAK, 1, 1.0, 80000, 400000); CreateHeap(&mgeStack, "MGE Train Stack", MSTAK, 1, 1.0, 80000, 400000); SetConfParms(); CreateHMMSet(&hset, &hmmStack, TRUE); CreateHMMSet(&orighset, &orighmmStack, TRUE); statInfo = (MTStatInfo *) New(&gstack, sizeof(MTStatInfo)); memset(statInfo, 0, sizeof(MTStatInfo)); genInfo = (GenInfo *) New(&genStack, sizeof(GenInfo)); memset(genInfo, 0, sizeof(GenInfo)); genInfo->hset = &hset; genInfo->genMem = &genStack; mtInfo = (MgeTrnInfo *) New(&mgeStack, sizeof(MgeTrnInfo)); memset(mtInfo, 0, sizeof(MgeTrnInfo)); mtInfo->genInfo = genInfo; mtInfo->statInfo = statInfo; mtInfo->hset = &hset; mtInfo->orighset = &orighset; mtInfo->mgeMem = &mgeStack; while (NextArg() == SWITCHARG) { s = GetSwtArg(); if (strlen(s) != 1) HError(6601, "HMgeTool: Bad switch %s; must be single letter", s); switch (s[0]) { case 'a': nMaxBAIter = GetChkedInt(1, 1000, s); nMaxBALen = GetChkedInt(1, 1000, s); break; case 'b': mtInfo->bBoundAdj = TRUE; nBAEndIter = GetChkedInt(0, 1000, s); nBoundAdjWin = GetChkedInt(1, 1000, s); break; case 'c': outProcData = TRUE; break; case 'd': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM definition directory expected"); hmmDir = GetStrArg(); break; case 'e': mtInfo->bStepLimit = TRUE; break; case 'f': frameRate = (HTime) GetChkedFlt(0.0, 10000000.0, s); break; case 'g': mtInfo->bMVar = TRUE; break; case 'i': startIter = GetChkedInt(0, 1000, s); endIter = GetChkedInt(startIter, 1000, s); break; case 'j': funcType = GetChkedInt(0, 2, s); mtInfo->funcType = funcType; break; case 'l': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: Label file output directory expected"); outLabDir = GetStrArg(); break; case 'o': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM file extension expected"); outExt = GetStrArg(); break; case 'p': A_STEP = GetChkedFlt(0.0, 10000000.0, s); B_STEP = GetChkedFlt(0.0, 10000000.0, s); break; case 'r': mtInfo->bOrigHmmRef = TRUE; if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM macro file name expected"); s = GetStrArg(); AddMMF(&orighset, s); break; case 's': /* updating scale file */ scalefn = GetStrArg(); break; case 'u': SetuFlags(); break; case 'v': MSDthresh = GetChkedFlt(0.0, 1.0, s); break; case 'w': fGVDistWght = GetChkedFlt(0.0, 1000.0, s); break; case 'x': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM file extension expected"); hmmExt = GetStrArg(); break; case 'B': inBinary = TRUE; break; case 'G': mtInfo->nGainStreamIndex = GetChkedInt(1, SMAX, s); mtInfo->nGainDimIndex = GetChkedInt(1, 1000, s); if (NextArg() == FLOATARG || NextArg() == INTARG) mtInfo->fGainWghtComp = GetChkedFlt(-10000.0, 1000000.0, s); break; case 'H': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM macro file name expected"); mmfFn = GetStrArg(); AddMMF(&hset, mmfFn); break; case 'I': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: MLF file name expected"); LoadMasterFile(GetStrArg()); break; case 'J': /* regression class and tree */ if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM regression class/tree file name expected"); s = GetStrArg(); AddMMF(&hset, s); AddMMF(&orighset, s); break; case 'K': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: HMM transform file name expected"); xformfn = GetStrArg(); break; case 'L': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: Label file directory expected"); labDir = GetStrArg(); break; case 'M': if (NextArg() != STRINGARG) HError(6601, "HMgeTool: Output macro file directory expected"); outDir = GetStrArg(); break; case 'T': trace = GetChkedInt(0, 0100000, s); break; case 'X': if (NextArg() != STRINGARG) HError(2319, "HMGenS: Label file extension expected"); labExt = GetStrArg(); break; default: HError(6601, "HMgeTool: Unknown switch %s", s); } } if (NextArg() != STRINGARG) HError(6601, "HMgeTool: file name of model list expected"); hmmListFn = GetStrArg(); Initialise(); if (funcType == MGE_EVAL) { PerformMgeEval(); } else if (funcType == MGE_TRAIN) { PerformMgeTrain(); if (endIter > 0 && bMgeUpdate) { /* output HMM files */ ConvDiagC(&hset, TRUE); SaveHMMSet(&hset, outDir, outExt, NULL, inBinary); } } else if (funcType == MGE_ADAPT) { PerformMgeAdapt(); if (endIter > 0 && bMgeUpdate) { MakeFN(xformfn, outDir, NULL, fname); SaveOneXForm(&hset, hset.curXForm, fname, FALSE); } } ResetHeap(&hmmStack); ResetHeap(&orighmmStack); ResetHeap(&accStack); ResetHeap(&genStack); ResetHeap(&mgeStack); return 0; }
int main(int argc, char *argv[]) { char *datafn, *s; int stream = 0; void Initialise(char *datafn); void LoadFile(char *fn); void CalcMeanCov(Sequence seq[], int s); void ClusterVecs(Sequence seq[], int s); void WriteVQTable(ClusterSet *cs[], char *fn); if(InitShell(argc,argv,hquant_version,hquant_vc_id)<SUCCESS) HError(2500,"HQuant: InitShell failed"); InitMem(); InitLabel(); InitMath(); InitSigP(); InitWave(); InitAudio(); InitVQ(); InitModel(); if(InitParm()<SUCCESS) HError(2500,"HQuant: InitParm failed"); InitTrain(); if (!InfoPrinted() && NumArgs() == 0) ReportUsage(); if (NumArgs() == 0) Exit(0); SetConfParms(); InitStreamVars(); while (NextArg() == SWITCHARG) { s = GetSwtArg(); if (strlen(s)!=1) HError(2519,"HQuant: Bad switch %s; must be single letter",s); switch(s[0]){ case 'd': if ( ck != NULLC) HError(2519,"HQuant: Specify one of -d or -f, not both"); ck = INVDIAGC; break; case 'f': if ( ck != NULLC) HError(2519,"HQuant: Specify one of -d or -f, not both"); ck = FULLC; break; case 'g': globClustVar = TRUE; break; case 'l': if (NextArg() != STRINGARG) HError(2519,"HQuant: Segment label expected"); segLab = GetStrArg(); break; case 'n': if (NextArg() != INTARG) HError(2519,"HQuant: Stream number expected"); stream = GetChkedInt(1,SMAX,s); if (NextArg() != INTARG) HError(2519,"HQuant: Codebook size expected"); cbSizes[stream]= GetChkedInt(1,32768,s); break; case 's': if (NextArg() != INTARG) HError(2519,"HQuant: Number of streams expected"); swidth[0] = GetChkedInt(1,SMAX,s); break; case 't': tType = binTree; break; case 'w': if (NextArg() != INTARG) HError(2519,"HQuant: Stream number expected"); stream = GetChkedInt(1,SMAX,s); if(swidth[0] < stream) swidth[0] = stream; widthSet = TRUE; if (NextArg() != INTARG) HError(2519,"HQuant: Stream width expected"); swidth[stream]= GetChkedInt(1,256,s); break; case 'F': if (NextArg() != STRINGARG) HError(2519,"HQuant: Data File format expected"); if((dff = Str2Format(GetStrArg())) == ALIEN) HError(-2589,"HQuant: Warning ALIEN Data file format set"); break; case 'G': if (NextArg() != STRINGARG) HError(2519,"HQuant: Label File format expected"); if((lff = Str2Format(GetStrArg())) == ALIEN) HError(-2589,"HQuant: Warning ALIEN Label file format set"); break; case 'I': if (NextArg() != STRINGARG) HError(2519,"HQuant: MLF file name expected"); LoadMasterFile(GetStrArg()); break; case 'L': if (NextArg()!=STRINGARG) HError(2519,"HQuant: Label file directory expected"); labDir = GetStrArg(); break; case 'T': if (NextArg() != INTARG) HError(2519,"HQuant: Trace value expected"); trace = GetChkedInt(0,077,s); break; case 'X': if (NextArg()!=STRINGARG) HError(2519,"HQuant: Label file extension expected"); labExt = GetStrArg(); break; default: HError(2519,"HQuant: Unknown switch %s",s); } } if (NextArg()!=STRINGARG) HError(2519,"HQuant: Output VQ table file name expected"); vqfn = GetStrArg(); if (NextArg()!=STRINGARG) HError(2519,"HQuant: Training data file name expected"); datafn = GetStrArg(); Initialise(datafn); LoadFile(datafn); while (NumArgs()>0) { if (NextArg()!=STRINGARG) HError(2519,"HQuant: Training data file name expected"); datafn = GetStrArg(); LoadFile(datafn); } for (stream=1;stream<=swidth[0];stream++){ if (trace&T_TOP) printf("%s-clustering data for stream %d (width %d)\n", (tType==linTree)?"Flat":"Tree",stream,swidth[stream]); CalcMeanCov(dSeq,stream); ClusterVecs(dSeq,stream); } WriteVQTable(cs,vqfn); ResetTrain(); ResetParm(); ResetModel(); ResetVQ(); ResetAudio(); ResetWave(); ResetSigP(); ResetMath(); ResetLabel(); ResetMem(); ResetShell(); Exit(0); return (0); /* never reached -- make compiler happy */ }
/* SetConfParms: set conf parms relevant to HCompV */ void SetConfParms(void) { int i; Boolean b; double f; char buf[MAXSTRLEN]; nParm = GetConfig("HEREST", TRUE, cParm, MAXGLOBS); if (nParm>0) { if (GetConfInt(cParm,nParm,"TRACE",&i)) trace = i; if (GetConfFlt(cParm,nParm,"VARFLOORPERCENTILE",&f)) varFloorPercent = f; if (GetConfBool(cParm,nParm,"SAVEBINARY",&b)) saveBinary = b; if (GetConfBool(cParm,nParm,"BINARYACCFORMAT",&b)) ldBinary = b; /* 2-model reestimation alignment model set */ if (GetConfStr(cParm,nParm,"ALIGNMODELMMF",buf)) { strcpy(al_hmmMMF,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNHMMLIST",buf)) { strcpy(al_hmmLst,buf); al_hmmUsed = TRUE; } /* allow multiple individual model files */ if (GetConfStr(cParm,nParm,"ALIGNMODELDIR",buf)) { strcpy(al_hmmDir,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNMODELEXT",buf)) { strcpy(al_hmmExt,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNXFORMEXT",buf)) { xfInfo.alXFormExt = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"ALIGNXFORMDIR",buf)) { xfInfo.alXFormDir = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"INXFORMMASK",buf)) { xfInfo.inSpkrPat = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"PAXFORMMASK",buf)) { xfInfo.paSpkrPat = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"LABFILEMASK",buf)) { labFileMask = (char*)malloc(strlen(buf)+1); strcpy(labFileMask, buf); } if (GetConfStr(cParm,nParm,"UPDATEMODE",buf)) { if (!strcmp (buf, "DUMP")) updateMode = UPMODE_DUMP; else if (!strcmp (buf, "UPDATE")) updateMode = UPMODE_UPDATE; else if (!strcmp (buf, "BOTH")) updateMode = UPMODE_BOTH; else HError(2319, "Unknown UPDATEMODE specified (must be DUMP, UPDATE or BOTH)"); } } } void ReportUsage(void) { printf("\nUSAGE: HERest [options] hmmList dataFiles...\n\n"); printf(" Option Default\n\n"); printf(" -a Use an input linear transform off\n"); printf(" -c f Mixture pruning threshold 10.0\n"); printf(" -d s dir to find hmm definitions current\n"); printf(" -h s set output speaker name pattern *.%%%%%%\n"); printf(" to s, optionally set input and parent patterns\n"); printf(" -l N set max files per speaker off\n"); printf(" -m N set min examples needed per model 3\n"); printf(" -o s extension for new hmm files as src\n"); printf(" -p N set parallel mode to N off\n"); printf(" -r Enable Single Pass Training... \n"); printf(" ...using two parameterisations off\n"); printf(" -s s print statistics to file s off\n"); printf(" -t f [i l] set pruning to f [inc limit] inf\n"); printf(" -u tmvwap update t)rans m)eans v)ars w)ghts tmvw\n"); printf(" a)daptation xform p)rior used \n"); printf(" s)semi-tied xform \n"); printf(" -v f set minimum variance to f 0.0\n"); printf(" -w f set mix weight floor to f*MINMIX 0.0\n"); printf(" -x s extension for hmm files none\n"); printf(" -z s Save all xforms to TMF file s TMF\n"); PrintStdOpts("BEFGHIJKLMSTX"); printf("\n\n"); } void SetuFlags(void) { char *s; s=GetStrArg(); uFlags=(UPDSet) 0; while (*s != '\0') switch (*s++) { case 't': uFlags = (UPDSet) (uFlags+UPTRANS); break; case 'm': uFlags = (UPDSet) (uFlags+UPMEANS); break; case 'v': uFlags = (UPDSet) (uFlags+UPVARS); break; case 'w': uFlags = (UPDSet) (uFlags+UPMIXES); break; case 's': uFlags = (UPDSet) (uFlags+UPSEMIT); break; case 'a': uFlags = (UPDSet) (uFlags+UPXFORM); break; case 'p': uFlags = (UPDSet) (uFlags+UPMAP); break; default: HError(2320,"SetuFlags: Unknown update flag %c",*s); break; } } /* ScriptWord: return next word from script */ char *ScriptWord(FILE *script, char *scriptBuf) { int ch,qch,i; i=0; ch=' '; while (isspace(ch)) ch = fgetc(script); if (ch==EOF) { scriptBuf=NULL; return NULL; } if (ch=='\'' || ch=='"'){ qch = ch; ch = fgetc(script); while (ch != qch && ch != EOF) { scriptBuf[i++] = ch; ch = fgetc(script); } if (ch==EOF) HError(5051,"ScriptWord: Closing quote missing in script file"); } else { do { scriptBuf[i++] = ch; ch = fgetc(script); }while (!isspace(ch) && ch != EOF); } scriptBuf[i] = '\0'; return scriptBuf; } void CheckUpdateSetUp() { AdaptXForm *xf;
static std::vector<paint_session> extract_paint_session(const std::string parkFileName) { core_init(); gOpenRCT2Headless = true; auto context = OpenRCT2::CreateContext(); std::vector<paint_session> sessions; log_info("Starting..."); if (context->Initialise()) { drawing_engine_init(); if (!context->LoadParkFromFile(parkFileName)) { log_error("Failed to load park!"); return {}; } gIntroState = INTRO_STATE_NONE; gScreenFlags = SCREEN_FLAGS_PLAYING; int32_t mapSize = gMapSize; int32_t resolutionWidth = (mapSize * 32 * 2); int32_t resolutionHeight = (mapSize * 32 * 1); resolutionWidth += 8; resolutionHeight += 128; rct_viewport viewport; viewport.x = 0; viewport.y = 0; viewport.width = resolutionWidth; viewport.height = resolutionHeight; viewport.view_width = viewport.width; viewport.view_height = viewport.height; viewport.var_11 = 0; viewport.flags = 0; int32_t customX = (gMapSize / 2) * 32 + 16; int32_t customY = (gMapSize / 2) * 32 + 16; int32_t x = 0, y = 0; int32_t z = tile_element_height(customX, customY) & 0xFFFF; x = customY - customX; y = ((customX + customY) / 2) - z; viewport.view_x = x - ((viewport.view_width) / 2); viewport.view_y = y - ((viewport.view_height) / 2); viewport.zoom = 0; gCurrentRotation = 0; // Ensure sprites appear regardless of rotation reset_all_sprite_quadrant_placements(); rct_drawpixelinfo dpi; dpi.x = 0; dpi.y = 0; dpi.width = resolutionWidth; dpi.height = resolutionHeight; dpi.pitch = 0; dpi.bits = (uint8_t*)malloc(dpi.width * dpi.height); log_info("Obtaining sprite data..."); viewport_render(&dpi, &viewport, 0, 0, viewport.width, viewport.height, &sessions); free(dpi.bits); drawing_engine_dispose(); } log_info("Got %u paint sessions.", std::size(sessions)); return sessions; }
//--------------------------------------------------------- bool CGridding_Spline_CSA::On_Execute(void) { //----------------------------------------------------- if( Initialise(m_Points, true) == false ) { return( false ); } //----------------------------------------------------- int i, x, y; TSG_Point p; csa *pCSA = csa_create(); csa_setnpmin(pCSA, Parameters("NPMIN") ->asInt()); csa_setnpmax(pCSA, Parameters("NPMAX") ->asInt()); csa_setk (pCSA, Parameters("K") ->asInt()); csa_setnppc (pCSA, Parameters("NPPC") ->asDouble()); //----------------------------------------------------- point *pSrc = (point *)SG_Malloc(m_Points.Get_Count() * sizeof(point)); for(i=0; i<m_Points.Get_Count() && Set_Progress(i, m_Points.Get_Count()); i++) { pSrc[i].x = m_Points[i].x; pSrc[i].y = m_Points[i].y; pSrc[i].z = m_Points[i].z; } csa_addpoints(pCSA, m_Points.Get_Count(), pSrc); m_Points.Clear(); //----------------------------------------------------- point *pDst = (point *)SG_Malloc(m_pGrid->Get_NCells() * sizeof(point)); for(y=0, i=0, p.y=m_pGrid->Get_YMin(); y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++, p.y+=m_pGrid->Get_Cellsize()) { for(x=0, p.x=m_pGrid->Get_XMin(); x<m_pGrid->Get_NX(); x++, p.x+=m_pGrid->Get_Cellsize(), i++) { pDst[i].x = p.x; pDst[i].y = p.y; } } //----------------------------------------------------- Process_Set_Text(_TL("calculating splines...")); csa_calculatespline (pCSA); Process_Set_Text(_TL("approximating points...")); csa_approximate_points (pCSA, m_pGrid->Get_NCells(), pDst); //----------------------------------------------------- for(y=0, i=0; y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++) { for(x=0; x<m_pGrid->Get_NX(); x++, i++) { if( isnan(pDst[i].z) ) { m_pGrid->Set_NoData(x, y); } else { m_pGrid->Set_Value(x, y, pDst[i].z); } } } //----------------------------------------------------- csa_destroy(pCSA); SG_Free(pSrc); SG_Free(pDst); //----------------------------------------------------- return( true ); }
//load the desktop file or the required template void Dialog::LoadDesktopFile(QString input) { //if we have "-" as 1st char, it means that this is not a desktop file, but a parameter desktopFileName = input; if (input.startsWith("-")) { QMessageBox::critical(this,tr("Error"),tr("The filename cannot start with a \"-\".")); exit(1); } //if proposed file does not exist, than we will create one based on the templates QFileInfo info(desktopFileName); if ((info.size() == 0) && (desktopFileName.endsWith(".desktop"))) { QFile::remove(desktopFileName); //for the copy, we need to remove it if (desktopType=="link") { copyTemplate("-link"); } else { copyTemplate("-app"); } } this->setWindowTitle(desktopFileName.section("/",-1)); ui->tabWidget->setCurrentIndex(0); //always start on the file info tab //Now load the file info and put it into the UI QString mime = LXDG::findAppMimeForFile(desktopFileName); QList<QByteArray> fmt = QImageReader::supportedImageFormats(); bool foundimage=false; for(int i=0; i<fmt.length(); i++){ if(info.suffix().toLower() == QString(fmt[i]).toLower()){foundimage=true; break; } } if(foundimage){ ui->label_file_icon->setPixmap( QPixmap(desktopFileName).scaledToHeight(64) ); }else{ ui->label_file_icon->setPixmap( LXDG::findMimeIcon(mime).pixmap(QSize(64,64)) ); } ui->label_file_mimetype->setText(mime); QString type; if(desktopFileName.endsWith(".desktop")){ type = tr("XDG Shortcut"); } else if(info.isDir()){ type = tr("Directory"); ui->label_file_icon->setPixmap( LXDG::findIcon("folder","").pixmap(QSize(64,64)) ); } else if(info.isExecutable()){ type = tr("Binary"); } else{ type = info.suffix().toUpper(); } if(info.isHidden()){ type = QString(tr("Hidden %1")).arg(type); } ui->label_file_type->setText(type); double bytes = info.size(); QStringList lab; lab << "B" << "KB" << "MB" << "GB" << "TB" << "PB"; int i=0; while(i<lab.length() && bytes>1024){ bytes = bytes/1024; i++; //next label } //convert the size to two decimel places and add the label QString sz = QString::number( qRound(bytes*100)/100.0 )+lab[i]; ui->label_file_size->setText( sz ); ui->label_file_owner->setText(info.owner()); ui->label_file_group->setText(info.group()); QString perms; if(info.isReadable() && info.isWritable()){ perms = tr("Read/Write"); } else if(info.isReadable()){ perms = tr("Read Only"); } else if(info.isWritable()){ perms = tr("Write Only"); } else{ perms = tr("No Access"); } ui->label_file_perms->setText(perms); ui->label_file_created->setText( info.created().toString(Qt::SystemLocaleLongDate) ); ui->label_file_modified->setText( info.lastModified().toString(Qt::SystemLocaleLongDate) ); //use the standard LXDG object and load the desktop file bool ok = false; if(desktopFileName.endsWith(".desktop")){ DF = LXDG::loadDesktopFile(desktopFileName, ok); } if( ok ) { if ((DF.type == XDGDesktop::LINK) && (desktopType!="link" )) { //we open a desktop type "link" but it was not mentionned by parameters Dialog::Initialise("-link"); } ui->lName->setText(DF.name); ui->lComment->setText(DF.comment); ui->lCommand->setText(DF.exec); //in case of "link" desktop, we populate the correct content in lWorkingDir if (desktopType=="link") { ui->lWorkingDir->setText(DF.url); } else { ui->lWorkingDir->setText(DF.path); } if (DF.startupNotify) ui->cbStartupNotification->setChecked(true); else ui->cbStartupNotification->setChecked(false); if (DF.useTerminal) ui->cbRunInTerminal->setChecked(true); else ui->cbRunInTerminal->setChecked(false); iconFileName=""; ui->pbIcon->setIcon(LXDG::findIcon(DF.icon,"")); if(!info.isWritable()){ ui->tab_deskedit->setEnabled(false); } } else { ui->tabWidget->removeTab(1); return; } //we load the file in memory and will adapt it before saving it to disk QFile file(desktopFileName); inMemoryFile=""; if (file.open(QFile::ReadOnly)) { QTextStream fileData(&file); inMemoryFile = fileData.readAll(); file.close(); //perform some validation checks //this will allow checks improvements without compilation of the file if ((inMemoryFile.contains(QRegExp(".*\\[Desktop Entry\\].*\n"))) && (inMemoryFile.contains(QRegExp("\n\\s*Type\\s*=.*\n"))) && (inMemoryFile.contains(QRegExp("\n\\s*Name\\s*=.*\n")))) { //qDebug() << "sounds a good file"; } else { //qDebug() << "wrong file!!!!"; QMessageBox msgBox; msgBox.setIcon(QMessageBox::Question); msgBox.setText(tr("There are some issues with this file !!!!")); msgBox.setInformativeText(tr("Either you correct this file your self with an editor, or you start from scratch using the link or app template.\nPlease note that this process will update the file called:") + desktopFileName); QPushButton *linkButton = msgBox.addButton("Link",QMessageBox::AcceptRole); QPushButton *appButton = msgBox.addButton("App",QMessageBox::ResetRole); QPushButton *cancelButton = msgBox.addButton("Cancel",QMessageBox::NoRole); msgBox.exec(); if (msgBox.clickedButton() == linkButton) { QFile::remove(desktopFileName); copyTemplate("-link"); Initialise("-link"); LoadDesktopFile(desktopFileName); } if (msgBox.clickedButton() == appButton) { QFile::remove(desktopFileName); copyTemplate("-app"); Initialise("-app"); LoadDesktopFile(desktopFileName); } if (msgBox.clickedButton() == cancelButton) { //we stop here exit(0); } } } }
Event::Event( Monitor *p_monitor, struct timeval p_start_time, const std::string &p_cause, const StringSetMap &p_noteSetMap ) : monitor( p_monitor ), start_time( p_start_time ), cause( p_cause ), noteSetMap( p_noteSetMap ) { if ( !initialised ) Initialise(); std::string notes; createNotes( notes ); bool untimedEvent = false; if ( !start_time.tv_sec ) { untimedEvent = true; gettimeofday( &start_time, 0 ); } static char sql[ZM_SQL_MED_BUFSIZ]; struct tm *stime = localtime( &start_time.tv_sec ); snprintf( sql, sizeof(sql), "insert into Events ( MonitorId, Name, StartTime, Width, Height, Cause, Notes ) values ( %d, 'New Event', from_unixtime( %ld ), %d, %d, '%s', '%s' )", monitor->Id(), start_time.tv_sec, monitor->Width(), monitor->Height(), cause.c_str(), notes.c_str() ); if ( mysql_query( &dbconn, sql ) ) { Error( "Can't insert event: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } id = mysql_insert_id( &dbconn ); if ( untimedEvent ) { Warning( "Event %d has zero time, setting to current", id ); } end_time.tv_sec = 0; frames = 0; alarm_frames = 0; tot_score = 0; max_score = 0; if ( config.use_deep_storage ) { char *path_ptr = path; path_ptr += snprintf( path_ptr, sizeof(path), "%s/%d", config.dir_events, monitor->Id() ); int dt_parts[6]; dt_parts[0] = stime->tm_year-100; dt_parts[1] = stime->tm_mon+1; dt_parts[2] = stime->tm_mday; dt_parts[3] = stime->tm_hour; dt_parts[4] = stime->tm_min; dt_parts[5] = stime->tm_sec; char date_path[PATH_MAX] = ""; char time_path[PATH_MAX] = ""; char *time_path_ptr = time_path; for ( unsigned int i = 0; i < sizeof(dt_parts)/sizeof(*dt_parts); i++ ) { path_ptr += snprintf( path_ptr, sizeof(path)-(path_ptr-path), "/%02d", dt_parts[i] ); struct stat statbuf; errno = 0; stat( path, &statbuf ); if ( errno == ENOENT || errno == ENOTDIR ) { if ( mkdir( path, 0755 ) ) { Fatal( "Can't mkdir %s: %s", path, strerror(errno)); } } if ( i == 2 ) strncpy( date_path, path, sizeof(date_path) ); else if ( i >= 3 ) time_path_ptr += snprintf( time_path_ptr, sizeof(time_path)-(time_path_ptr-time_path), "%s%02d", i>3?"/":"", dt_parts[i] ); } char id_file[PATH_MAX]; // Create event id symlink snprintf( id_file, sizeof(id_file), "%s/.%d", date_path, id ); if ( symlink( time_path, id_file ) < 0 ) Fatal( "Can't symlink %s -> %s: %s", id_file, path, strerror(errno)); // Create empty id tag file snprintf( id_file, sizeof(id_file), "%s/.%d", path, id ); if ( FILE *id_fp = fopen( id_file, "w" ) ) fclose( id_fp ); else Fatal( "Can't fopen %s: %s", id_file, strerror(errno)); } else { snprintf( path, sizeof(path), "%s/%d/%d", config.dir_events, monitor->Id(), id ); struct stat statbuf; errno = 0; stat( path, &statbuf ); if ( errno == ENOENT || errno == ENOTDIR ) { if ( mkdir( path, 0755 ) ) { Error( "Can't mkdir %s: %s", path, strerror(errno)); } } char id_file[PATH_MAX]; // Create empty id tag file snprintf( id_file, sizeof(id_file), "%s/.%d", path, id ); if ( FILE *id_fp = fopen( id_file, "w" ) ) fclose( id_fp ); else Fatal( "Can't fopen %s: %s", id_file, strerror(errno)); } last_db_frame = 0; }
CMOOSDBHTTPServer::CMOOSDBHTTPServer(long lDBPort) { Initialise(lDBPort, DEFAULT_WEBSERVER_PORT); }
CSystemTray::CSystemTray(CWnd* pParent, UINT uCallbackMessage, LPCTSTR szToolTip, HICON icon, UINT uID) { Initialise(); Create(pParent, uCallbackMessage, szToolTip, icon, uID); }
int main(int argc, char *argv[]) { int i; char *c,*s,*fn; char sBuf[256],fmt[256]; void Initialise(void); void ProcessText(char *fn,bool lastFile); bool Exists(char *fn); BackOffLM *CombineModels(MemHeap *heap,LMInfo *lmi,int nLModel,int nSize,WordMap *wl) ; InitShell(argc,argv,ladapt_version,ladapt_vc_id); InitMem(); InitMath(); InitWave(); InitLabel(); InitLUtil(); InitWMap(); InitGBase(); InitLModel(); InitPCalc(); InitPMerge(); SetConfParms(); if (!InfoPrinted() && NumArgs() == 0) ReportUsage(); if (NumArgs() == 0) Exit(EXIT_SUCCESS); InitBuildInfo(&binfo); binfo.dctype = DC_ABSOLUTE; nLModel = 1; while (NextArg() == SWITCHARG) { s = GetSwtArg(); if (strlen(s)!=1) HError(16419,"Bad switch %s; must be single letter",s); switch(s[0]){ case 'a': newWords = GetChkedInt(10,10000000,s); break; case 'b': ngbSize = GetChkedInt(10,10000000,s); break; case 'c': i = GetChkedInt(2,LM_NSIZE,s); binfo.cutOff[i] = GetChkedInt(0,1000,s); break; case 'd': if (NextArg()!=STRINGARG) HError(16419,"Gram base root file name expected"); rootFN = GetStrArg(); break; case 'f': strcpy(fmt, GetStrArg()); for (c=fmt; *c; *c=toupper(*c), c++); /* To uppercase */ if (strcmp(fmt, LM_TXT_TEXT)==0) binfo.saveFmt = LMF_TEXT; else if (strcmp(fmt, LM_TXT_BINARY)==0) binfo.saveFmt = LMF_BINARY; else if (strcmp(fmt, LM_TXT_ULTRA)==0) binfo.saveFmt = LMF_ULTRA; else HError(16419,"Unrecognised LM format, should be one of [%s, %s, %s]", LM_TXT_TEXT, LM_TXT_BINARY, LM_TXT_ULTRA); break; case 'g': processText = FALSE; break; case 'i': if (NextArg()!=FLOATARG) HError(16419,"Interpolation weight expected"); lmInfo[nLModel].weight = GetChkedFlt(0.0,1.0,s); if (NextArg()!=STRINGARG) HError(16419,"Interpolation LM filename expected"); lmInfo[nLModel].fn = GetStrArg(); nLModel++; break; case 'j': i = GetChkedInt(2,LM_NSIZE,s); binfo.wdThresh[i] = GetChkedFlt(0.0,1E10,s); break; case 'n': nSize = GetChkedInt(1, MAXNG, s); break; #ifdef HTK_TRANSCRIBER case 's': if (NextArg()!=STRINGARG) HError(16419,"Gram file text source descriptor expected"); txtSrc = GetStrArg(); break; case 't': binfo.dctype = DC_KATZ; break; #endif case 'w': if (NextArg()!=STRINGARG) HError(16419,"Word list file name expected"); wlistFN = GetStrArg(); break; #ifndef HTK_TRANSCRIBER case 'x': binfo.ptype = LMP_COUNT; break; #endif case 'T': trace = GetChkedInt(0,077,s); break; default: HError(16419,"LAdapt: Unknown switch %s",s); } } #ifdef HTK_TRANSCRIBER if (nLModel==1) { /* must interpolate with at least one model */ HError(16419,"LAdapt: at least one model must be specified with -i option"); } if (binfo.saveFmt==LMF_TEXT) { /* save fomat cannot be TEXT */ binfo.saveFmt=LMF_BINARY; } #endif if (NextArg() != STRINGARG) HError(16419,"LAdapt: language model file name expected"); outFN = CopyString(&gstack,GetStrArg()); Initialise(); if (processText) { if (NextArg() != STRINGARG) ProcessText(NULL,TRUE); /* input from stdin */ else while (NextArg() == STRINGARG) { /* !! copy string argument since it gets overwritten by NextArg() when reading from script file */ fn = CopyString(&gstack,GetStrArg()); ProcessText(fn,NextArg() != STRINGARG); } if (NumArgs() != 0) HError(-16419,"LAdapt: unused args left on cmd line"); for (i=0; i<stdBuf.ngb->fndx; i++) { sprintf(sBuf,"%s.%d",stdBuf.ngb->fn,i); AddInputGFile(&inSet,sBuf,1.0); } ResetHeap(&langHeap); } else { for (i=0; i<MAX_NGRAM_FILES; i++) { sprintf(sBuf,"%s.%d",rootFN,i); if (!Exists(sBuf)) break; AddInputGFile(&inSet,sBuf,1.0); } if (i==MAX_NGRAM_FILES) { HError(-16419, "LAdapt: Only %d n-gram files read (recompile with different setting\nof MAX_NGRAM_FILES"); } } if (nLModel==1) { adpLM = GenerateModel(&langHeap,&binfo); } else { if (binfo.ptype==LMP_COUNT) binfo.ptype = LMP_FLOAT; newLM = GenerateModel(&langHeap,&binfo); lmInfo[0].lm = newLM; lmInfo[0].fn = "unknown"; /* combine all models into one */ adpLM = CombineModels(&langHeap,lmInfo,nLModel,nSize,tgtVoc); } #ifdef HTK_TRANSCRIBER #ifdef HTK_CRYPT adpLM->encrypt = TRUE; /* force to write encrypted model */ #endif #endif SaveLangModel(outFN,adpLM); Exit(EXIT_SUCCESS); return EXIT_SUCCESS; /* never reached -- make compiler happy */ }
// Solution method void NewtonSolver::Solve(arma::vec& solution, arma::vec& residualHistory, ExitFlagType& exitFlag, arma::mat* pJacobianExternal) { // Parse parameter list Initialise(); // Eventually print the header if (mPrintOutput) { PrintHeader("Newton Method", mMaxIterations, mTolerance); } // Check if dimensions are compatible int problem_size = mpInitialGuess->n_rows; assert( problem_size == solution.n_rows ); // Iterator int iteration = 0; // Assign initial guess solution = *mpInitialGuess; // Initial residual arma::vec residual(problem_size); mpProblem->ComputeF(solution,residual); // Residual norm double residual_norm = arma::norm(residual,2); // Residual history residualHistory.set_size(1+mpParameterList->maxIterations); residualHistory(iteration) = residual_norm; // Eventually print iteration if (mPrintOutput) { PrintIteration(iteration, residual_norm, true); } // Check convergence bool converged = mpConvergenceCriterion->TestConvergence(residual_norm); arma::mat jacobian(problem_size,problem_size); // Newton's method main loop while ( (iteration < mMaxIterations) && (!converged) ) { // Compute Jacobian (eventually use finite differences) if (mpProblemJacobian) { mpProblemJacobian->ComputeDFDU(solution,jacobian); } else { ComputeDFDU(solution,residual,jacobian); } // Linear solve to find direction arma::vec direction = arma::solve( jacobian, -residual); // Update solution solution += direction; // Update iterator iteration++; // Update residual mpProblem->ComputeF(solution,residual); // Update residual norm residual_norm = arma::norm(residual,2); // Check convergence converged = mpConvergenceCriterion->TestConvergence(residual_norm); // Update residual history residualHistory(iteration) = residual_norm; // Print infos if (mPrintOutput) { PrintIteration(iteration, residual_norm); } } // Trim residual history residualHistory.head(iteration); // Assign exit flag if (converged) { exitFlag = AbstractNonlinearSolver::ExitFlagType::converged; } else { exitFlag = AbstractNonlinearSolver::ExitFlagType::notConverged; } // Eventually print final message if (mPrintOutput) { PrintFooter(iteration, exitFlag); } // Output to external jacobian if requested if (pJacobianExternal) { assert( (*pJacobianExternal).n_rows==problem_size); assert( (*pJacobianExternal).n_cols==problem_size); assert( jacobian.n_rows==problem_size); (*pJacobianExternal) = jacobian; } }
BoundedArray<T>::BoundedArray(BoundedArray &_otherArray) { Initialise( _otherArray ); }
int main(int argc, char** argv) { Opaque o = Initialise(argc); return 0; }