// Invoke solver's built-in enumeration algorithm
void 
OsiCbcSolverInterface::branchAndBound()
{
  *messageHandler() << "Warning: Use of OsiCbc is deprecated." << CoinMessageEol;
  *messageHandler() << "To enjoy the full performance of Cbc, use the CbcSolver interface." << CoinMessageEol;
  agentPtr_->branchAndBound();
}
Esempio n. 2
0
void QXmlSchemaPrivate::load(QIODevice *source, const QUrl &documentUri, const QString &targetNamespace)
{
    m_schemaParserContext = QPatternist::XsdSchemaParserContext::Ptr(new QPatternist::XsdSchemaParserContext(m_namePool.d, m_schemaContext));
    m_schemaIsValid = false;

    if (!source) {
        qWarning("A null QIODevice pointer cannot be passed.");
        return;
    }

    if (!source->isReadable()) {
        qWarning("The device must be readable.");
        return;
    }

    m_documentUri = QPatternist::XPathHelper::normalizeQueryURI(documentUri);
    m_schemaContext->setMessageHandler(messageHandler());
    m_schemaContext->setUriResolver(uriResolver());
    m_schemaContext->setNetworkAccessManager(networkAccessManager());

    QPatternist::XsdSchemaParser parser(m_schemaContext, m_schemaParserContext, source);
    parser.setDocumentURI(documentUri);
    parser.setTargetNamespace(targetNamespace);

    try {
        parser.parse();
        m_schemaParserContext->resolver()->resolve();

        m_schemaIsValid = true;
    } catch (QPatternist::Exception exception) {
        Q_UNUSED(exception);
        m_schemaIsValid = false;
    }
}
Esempio n. 3
0
void QXmlSchemaPrivate::load(const QUrl &source, const QString &targetNamespace)
{
    m_documentUri = QPatternist::XPathHelper::normalizeQueryURI(source);

    m_schemaContext->setMessageHandler(messageHandler());
    m_schemaContext->setUriResolver(uriResolver());
    m_schemaContext->setNetworkAccessManager(networkAccessManager());

    const QPatternist::AutoPtr<QNetworkReply> reply(QPatternist::AccelTreeResourceLoader::load(source, m_schemaContext->networkAccessManager(),
                                                                                               m_schemaContext, QPatternist::AccelTreeResourceLoader::ContinueOnError));
    if (reply)
        load(reply.data(), source, targetNamespace);
}
Esempio n. 4
0
/*!
  Validates the XML instance document read from \a source against the schema.

  Returns \c true if the XML instance document is valid according to the
  schema, \c false otherwise.

  Example:

  \snippet qxmlschemavalidator/main.cpp 0
 */
bool QXmlSchemaValidator::validate(const QUrl &source) const
{
    d->m_context->setMessageHandler(messageHandler());
    d->m_context->setUriResolver(uriResolver());
    d->m_context->setNetworkAccessManager(networkAccessManager());

    const QPatternist::AutoPtr<QNetworkReply> reply(QPatternist::AccelTreeResourceLoader::load(source, d->m_context->networkAccessManager(),
                                                                                               d->m_context, QPatternist::AccelTreeResourceLoader::ContinueOnError));
    if (reply)
        return validate(reply.data(), source);
    else
        return false;
}
Esempio n. 5
0
/**
 *  Główna pętla serwera. Serwer bedzie nasłuchiwal przychodzących połączeń. Dla nowego połączenia
 *  zostanie uruchomiony nowy wątek, który je obsłuży przy użyciu osobnego gniazda.
 */
void Server::listen()
{
    try{
        tcp::acceptor acceptor(ioService, tcp::endpoint(tcp::v4(), messagePort));
        while(!interrupted)
        {
            cout<<"Serwer nasłuchuje..."<<endl;
            tcp::socket* socket = new tcp::socket(ioService);
            acceptor.accept(*socket);
            boost::thread messageHandler(boost::bind(&Server::handleMessage, this, socket));
        }
    } catch (exception& e){
        cerr << e.what() << endl;
    }
}
Esempio n. 6
0
/*!
  Validates the XML instance document read from \a source with the
  given \a documentUri against the schema.

  Returns \c true if the XML instance document is valid according to the
  schema, \c false otherwise.

  Example:

  \snippet doc/src/snippets/qxmlschemavalidator/main.cpp 1
 */
bool QXmlSchemaValidator::validate(QIODevice *source, const QUrl &documentUri) const
{
    if (!source) {
        qWarning("A null QIODevice pointer cannot be passed.");
        return false;
    }

    if (!source->isReadable()) {
        qWarning("The device must be readable.");
        return false;
    }

    const QUrl normalizedUri = QPatternist::XPathHelper::normalizeQueryURI(documentUri);

    d->m_context->setMessageHandler(messageHandler());
    d->m_context->setUriResolver(uriResolver());
    d->m_context->setNetworkAccessManager(networkAccessManager());

    QPatternist::NetworkAccessDelegator::Ptr delegator(new QPatternist::NetworkAccessDelegator(d->m_context->networkAccessManager(),
                                                                                               d->m_context->networkAccessManager()));

    QPatternist::AccelTreeResourceLoader loader(d->m_context->namePool(), delegator, QPatternist::AccelTreeBuilder<true>::SourceLocationsFeature);

    QPatternist::Item item;
    try {
        item = loader.openDocument(source, normalizedUri, d->m_context);
    } catch (QPatternist::Exception exception) {
        Q_UNUSED(exception);
        return false;
    }

    QXmlNodeModelIndex index = item.asNode();
    const QAbstractXmlNodeModel *model = item.asNode().model();

    QPatternist::XsdValidatedXmlNodeModel *validatedModel = new QPatternist::XsdValidatedXmlNodeModel(model);

    QPatternist::XsdValidatingInstanceReader reader(validatedModel, normalizedUri, d->m_context);
    if (d->m_schema)
        reader.addSchema(d->m_schema, d->m_schemaDocumentUri);
    try {
        reader.read();
    } catch (QPatternist::Exception exception) {
        Q_UNUSED(exception);
        return false;
    }

    return true;
}
Esempio n. 7
0
void GameManager :: waitForMessage(Phase* p){
    fd_set nefds, fds;
    int maxFd =0;
    maxFd=p->setAllFd(fds);
    struct timeval tv;
    int retval;
    while(!p->finished()){
        tv.tv_sec = 15;
        tv.tv_usec = 0;
        nefds = fds;
        retval = select(maxFd, &nefds, NULL, NULL, &tv);
        if (retval == -1)
            perror("select()");
        else if (retval){
            messageHandler(p, nefds);
        }
        else{ //Timeout
        }
    }
}
    void processFrame (CanMsg& msg) {
	        Logger::info("Received marine sensor readings from CanBus");
	    Float16Compressor fltCompressor;
		CanMessageHandler messageHandler(msg);
		float current, voltage;
		SensedElement element;
		uint16_t comp_current, comp_voltage;

		if (messageHandler.getMessageId() == MSG_ID_CURRENT_SENSOR_DATA) {
	                // Use get data instead(int)? Parse data here or add the routine in another file?
			messageHandler.getData(&comp_current, CURRENT_SENSOR_CURRENT_DATASIZE);
			messageHandler.getData(&comp_voltage, CURRENT_SENSOR_VOLTAGE_DATASIZE);

		}
	    current = fltCompressor.decompress(comp_current);
	    voltage = fltCompressor.decompress(comp_voltage);
	    element = SAILDRIVE;                                                 // TO CHANGE FOR MULTI SENSOR READING
	    MessagePtr currentSensorDataMsg = std::make_unique<CurrentSensorDataMsg>(static_cast<float>(current),
	                                                static_cast<float>(voltage), static_cast<SensedElement>(element));
	    m_msgBus.sendMessage(std::move(currentSensorDataMsg));
	    Logger::info(" Current sensor data: \n Current: %lf \n Voltage: %lf \n",current,voltage);
	}
Esempio n. 9
0
static void qt4MessageHandler(QtMsgType type, const char *text)
{ messageHandler(type, QString::fromLocal8Bit(text)); }
Esempio n. 10
0
static void qt5MessageHandler(QtMsgType type, const QMessageLogContext &, const QString &text)
{ messageHandler(type, text); }
Esempio n. 11
0
bool XSLTProcessor::transformToString(Node* sourceNode, String&, String& resultString, String&)
{
    bool success = false;

    RefPtr<XSLStyleSheet> stylesheet = m_stylesheet;
    if (!stylesheet && m_stylesheetRootNode) {
        Node* node = m_stylesheetRootNode.get();
        stylesheet = XSLStyleSheet::createForXSLTProcessor(node->parent() ? node->parent() : node,
            node->document()->url().string(),
            node->document()->url()); // FIXME: Should we use baseURL here?

        // According to Mozilla documentation, the node must be a Document node, an xsl:stylesheet or xsl:transform element.
        // But we just use text content regardless of node type.
        stylesheet->parseString(createMarkup(node));
    }

    if (!stylesheet || stylesheet->sheetString().isEmpty())
        return success;

    RefPtr<Document> ownerDocument = sourceNode->document();
    bool sourceIsDocument = (sourceNode == ownerDocument.get());

    QXmlQuery query(QXmlQuery::XSLT20);

    XSLTMessageHandler messageHandler(ownerDocument.get());
    XSLTUriResolver uriResolver(ownerDocument.get());
    query.setMessageHandler(&messageHandler);

    XSLTProcessor::ParameterMap::iterator end = m_parameters.end();
    for (XSLTProcessor::ParameterMap::iterator it = m_parameters.begin(); it != end; ++it)
        query.bindVariable(QString(it->first), QXmlItem(QVariant(it->second)));

    QString source;
    if (sourceIsDocument && ownerDocument->transformSource())
        source = ownerDocument->transformSource()->platformSource();
    if (!sourceIsDocument || source.isEmpty())
        source = createMarkup(sourceNode);

    QBuffer inputBuffer;
    QBuffer styleSheetBuffer;
    QBuffer outputBuffer;

    inputBuffer.setData(source.toUtf8());
    styleSheetBuffer.setData(QString(stylesheet->sheetString()).toUtf8());

    inputBuffer.open(QIODevice::ReadOnly);
    styleSheetBuffer.open(QIODevice::ReadOnly);
    outputBuffer.open(QIODevice::ReadWrite);

    query.setFocus(&inputBuffer);
    query.setQuery(&styleSheetBuffer, QUrl(stylesheet->href()));

    query.setUriResolver(&uriResolver);

    success = query.evaluateTo(&outputBuffer);
    outputBuffer.reset();
    resultString = QString::fromUtf8(outputBuffer.readAll()).trimmed();

    if (m_stylesheet) {
        m_stylesheet->clearDocuments();
        m_stylesheet = 0;
    }

    return success;
}
Esempio n. 12
0
void Flow::fragmentSortedHandler(UInt64 stage,PacketReader& fragment,UInt8 flags) {
	if(stage<=this->stage) {
		ERROR("Stage %llu not sorted on flow %llu",stage,id);
		return;
	}
	if(stage>(this->stage+1)) {
		// not following stage!
		UInt32 lostCount = (UInt32)(stage-this->stage-1);
		(UInt64&)this->stage = stage;
		if(_pPacket) {
			delete _pPacket;
			_pPacket = NULL;
		}
		if(flags&MESSAGE_WITH_BEFOREPART) {
			lostFragmentsHandler(lostCount+1);
			return;
		}
		lostFragmentsHandler(lostCount);
	} else
		(UInt64&)this->stage = stage;

	// If MESSAGE_ABANDONMENT, content is not the right normal content!
	if(flags&MESSAGE_ABANDONMENT) {
		if(_pPacket) {
			delete _pPacket;
			_pPacket = NULL;
		}
		return;
	}

	PacketReader* pMessage(&fragment);
	if(flags&MESSAGE_WITH_BEFOREPART){
		if(!_pPacket) {
			WARN("A received message tells to have a 'beforepart' and nevertheless partbuffer is empty, certainly some packets were lost");
			lostFragmentsHandler(1);
			delete _pPacket;
			_pPacket = NULL;
			return;
		}
		
		_pPacket->add(fragment);

		if(flags&MESSAGE_WITH_AFTERPART)
			return;

		pMessage = _pPacket->release();
	} else if(flags&MESSAGE_WITH_AFTERPART) {
		if(_pPacket) {
			ERROR("A received message tells to have not 'beforepart' and nevertheless partbuffer exists");
			lostFragmentsHandler(_pPacket->fragments);
			delete _pPacket;
		}
		_pPacket = new Packet(fragment);
		return;
	}

	Message::Type type = unpack(*pMessage);

	if(type!=Message::EMPTY) {
		writer._callbackHandle = 0;
		string name;
		AMFReader amf(*pMessage);
		if(type==Message::AMF_WITH_HANDLER || type==Message::AMF) {
			amf.read(name);
			if(type==Message::AMF_WITH_HANDLER) {
				writer._callbackHandle = amf.readNumber();
				if(amf.followingType()==AMF::Null)
					amf.readNull();
			}
		}

		try {
			switch(type) {
				case Message::AMF_WITH_HANDLER:
				case Message::AMF:
					messageHandler(name,amf);
					break;
				case Message::AUDIO:
					audioHandler(*pMessage);
					break;
				case Message::VIDEO:
					videoHandler(*pMessage);
					break;
				default:
					rawHandler(type,*pMessage);
			}
		} catch(Exception& ex) {
			_error = "flow error, " + ex.displayText();
		} catch(exception& ex) {
			_error = string("flow error, ") + ex.what();
		} catch(...) {
			_error = "Unknown flow error";
		}
	}
	writer._callbackHandle = 0;

	if(_pPacket) {
		delete _pPacket;
		_pPacket=NULL;
	}

	if(flags&MESSAGE_END)
		complete();
	
}
Esempio n. 13
0
void Flow::messageHandler(UInt32 stage,PacketReader& message,UInt8 flags) {
	if(_completed)
		return;

	if(stage<=_stage) {
		DEBUG("Stage %u on flow %u has already been received",stage,id);
		return;
	}
	_stage = stage;

	PacketReader* pMessage(NULL);
	if(flags&MESSAGE_WITH_BEFOREPART){
		if(_sizeBuffer==0) {
			ERROR("A received message tells to have a 'afterpart' and nevertheless partbuffer is empty");
			return;
		}
		
		UInt8* pOldBuffer = _pBuffer;
		_pBuffer = new UInt8[_sizeBuffer + message.available()]();
		memcpy(_pBuffer,pOldBuffer,_sizeBuffer);
		memcpy(_pBuffer+_sizeBuffer,message.current(),message.available());
		_sizeBuffer += message.available();
		delete [] pOldBuffer;

		if(flags&MESSAGE_WITH_AFTERPART)
			return;

		pMessage = new PacketReader(_pBuffer,_sizeBuffer);
	} else if(flags&MESSAGE_WITH_AFTERPART) {
		if(_sizeBuffer>0) {
			ERROR("A received message tells to have not 'beforepart' and nevertheless partbuffer exists");
			delete [] _pBuffer;
			_sizeBuffer=0;
		}
		_sizeBuffer = message.available();
		_pBuffer = new UInt8[_sizeBuffer]();
		memcpy(_pBuffer,message.current(),_sizeBuffer);
		return;
	}
	if(!pMessage)
		pMessage = new PacketReader(message);

	UInt8 type = unpack(*pMessage);
	if(type!=EMPTY) {
		writer._callbackHandle = 0;
		string name;
		AMFReader amf(*pMessage);
		if(type==AMF_WITH_HANDLER || type==AMF) {
			amf.read(name);
			if(type==AMF_WITH_HANDLER) {
				writer._callbackHandle = amf.readNumber();
				amf.skipNull();
			}
		}

		// create code prefix
		writer._code.assign(_name);
		if(!name.empty()) {
			writer._code.append(".");
			writer._code.push_back(toupper(name[0]));
			if(name.size()>1)
				writer._code.append(&name[1]);
		}

		switch(type) {
			case AMF_WITH_HANDLER:
			case AMF:
				messageHandler(name,amf);
				break;
			case AUDIO:
				audioHandler(*pMessage);
				break;
			case VIDEO:
				videoHandler(*pMessage);
				break;
			default:
				rawHandler(type,*pMessage);
		}
	}

	delete pMessage;

	if(flags&MESSAGE_END)
		complete();

	if(_sizeBuffer>0) {
		delete [] _pBuffer;
		_sizeBuffer=0;
	}
}
Esempio n. 14
0
slm_machine::slm_machine(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::slm_machineClass)
{
/************************** UI and Buddy Management *******************************/
    ui->setupUi(this);
    setProgressBarVisibility(false);
    //Buddy Management
    buddies = new buddyManager();
    buddies->loadBuddiesAndIPs();
    buddyModel = new QStringListModel();
    buddyModel->setStringList(buddies->AliasBuddyList);

    ui->buddyList->setModel(buddyModel);
    ui->buddyList->setEditTriggers(QAbstractItemView::NoEditTriggers);

    this->setWindowTitle("SLM");

    //UI connections
    connect(ui->addBuddyButton, SIGNAL(clicked()),this, SLOT(addBuddyPressed()));
    connect(ui->removeBuddyButton, SIGNAL(clicked()), this, SLOT(removeBuddypressed()));
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(closeApplication()));
    connect(ui->buddyList, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(buddyPressed(QModelIndex)));
    connect(ui->actionAbout_Qt, SIGNAL(triggered()), this, SLOT(aboutQTPressed()));
    connect(ui->actionAbout_SLM, SIGNAL(triggered()), this, SLOT(aboutSLMPressed()));
    connect(ui->actionEncryption_Key, SIGNAL(triggered()), this, SLOT(encryptionKeyPressed()));

/************************************************************************************/

/************************** Message Server Management *******************************/
    messageServer = slm_server::getInstance();
    connect(messageServer, SIGNAL(sendtoUI(QByteArray,QHostAddress)),this,SLOT(messageHandler(QByteArray,QHostAddress)));
/************************************************************************************/

/***************************** File Server Management *******************************/
    onGoingFileTransfer = false;

    FServer = new fileServer();

    //File Server Connections
    connect(FServer,SIGNAL(newDocumentArrived(QString,QString,quint32,quint8)),this,SLOT(incomingFileSlot(QString,QString,quint32,quint8)),Qt::QueuedConnection);
    connect(FServer,SIGNAL(transferCompleted(QString)),this,SLOT(incomingFileTransferCompleted(QString)),Qt::QueuedConnection);
    connect(FServer,SIGNAL(transferCanceled()),this,SLOT(transferIsCancelled()),Qt::QueuedConnection);
    connect(FServer,SIGNAL(ongoingTransfer()),this,SLOT(ongoingTransferExists()),Qt::QueuedConnection);
    connect(FServer,SIGNAL(receivingProgress(quint32)),this,SLOT(updateReceivingProgress(quint32)),Qt::QueuedConnection);

    //Start the File Server Thread
    FServer->start();
/***********************************************************************************/

/***************************** Buddy List Right Click *******************************/
    checkOnline = new QAction(tr("&Check Online"), this);
    checkOnline->setIcon(QIcon(":/icons/CheckOnline"));
    rightClickUserMenu = new QMenu();
    rightClickUserMenu->addAction(checkOnline);
    connect(checkOnline,SIGNAL(triggered()),this,SLOT(checkUserOnline()));
    ui->buddyList->installEventFilter(this);
/***********************************************************************************/

/***************************** Tray Icon Management ********************************/
    //Create tray icon and contex menu actions
    this->createActions();
    this->createTrayIcon();

    //Tray Icon Connections
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    connect(this, SIGNAL(signalPlaceToTray()),this, SLOT(slotPlaceToTray()),Qt::QueuedConnection);

    //Show application icon in the tray
    trayIcon->setIcon(QIcon(":/icons/SLM_Logo"));
    trayIcon->setToolTip("SLM (SMG Lan Messenger)");
    trayIcon->show();
/**********************************************************************************/
}
Esempio n. 15
0
//#############################################################################
//  Parameters:
//  cuts:	 (o) all cuts generated in this round of cut generation
//  numberTries: (i) the maximum number of iterations for this round of cut
//                   generation; no a priori limit if 0
//  whichGenerator: (i/o) whichGenerator[i] is loaded with the index of the
//                        generator that produced cuts[i]; reallocated as
//                        required
//  numberOldActiveCuts: (o) the number of active cuts at this node from
//                           previous rounds of cut generation
//  numberNewCuts:       (o) the number of cuts produced in this round of cut
//                           generation
//  maximumWhich:      (i/o) capacity of whichGenerator; may be updated if
//                           whichGenerator grows.
//  cutDuringRampup:    (i) Whether generating cuts during rampup
//  found: (o)  great than 0 means that heuristics found solutions;
//              otherwise not.
bool
DcModel::solveWithCuts(OsiCuts & cuts, int numberTries,
			DcTreeNode * node, int & numberOldActiveCuts,
			int & numberNewCuts, int & maximumWhich,
			int *& whichGenerator, const bool cutDuringRampup,
			int & found)
{
    found = -10;
    bool feasible;
    int lastNumberCuts = 0;
    double lastObjective = -1.0e100 ;
    int violated = 0;
    int numberRowsAtStart = solver_->getNumRows();
    int numberColumns = solver_->getNumCols();

    numberOldActiveCuts = numberRowsAtStart - numberRowsAtContinuous_;
    numberNewCuts = 0;

    feasible = resolve();
    if(!feasible) {
	return false;  // If lost feasibility, bail out right now
    }

    reducedCostFix();
    const double *lower = solver_->getColLower();
    const double *upper = solver_->getColUpper();
    const double *solution = solver_->getColSolution();

    double minimumDrop = minimumDrop_;
    if (numberTries < 0) {
	numberTries = -numberTries;
	minimumDrop = -1.0;
    }

    //-------------------------------------------------------------------------
    // Is it time to scan the cuts in order to remove redundant cuts? If so,
    // set up to do it.
# define SCANCUTS 100
    int *countColumnCuts = NULL;
    int *countRowCuts = NULL;
    bool fullScan = false;
    if ((numberNodes_ % SCANCUTS) == 0) {
	fullScan = true;
	countColumnCuts = new int[numberCutGenerators_ + numberHeuristics_];
	countRowCuts = new int[numberCutGenerators_ + numberHeuristics_];
	memset(countColumnCuts, 0,
	       (numberCutGenerators_ + numberHeuristics_) * sizeof(int));
	memset(countRowCuts, 0,
	       (numberCutGenerators_ + numberHeuristics_) * sizeof(int));
    }

    double direction = solver_->getObjSense();
    double startObjective = solver_->getObjValue() * direction;

    int numberPasses = 0;
    double primalTolerance = 1.0e-7;

    //-------------------------------------------------------------------------
    // Start cut generation loop
//     do {
// 	numberPasses++;
// 	numberTries--;
// 	OsiCuts theseCuts;

// 	// First check if there are cuts violated in global cut pool
// 	if (numberPasses == 1 && howOftenGlobalScan_ > 0 &&
// 	    (numberNodes_ % howOftenGlobalScan_) == 0) {
// 	    int numberCuts = globalCuts_.sizeColCuts();
// 	    int i;
// 	    for ( i = 0; i < numberCuts; ++i) {
// 		const OsiColCut *thisCut = globalCuts_.colCutPtr(i);
// 		if (thisCut->violated(solution) > primalTolerance) {
// 		    printf("Global cut added - violation %g\n",
// 			   thisCut->violated(solution));
// 		    theseCuts.insert(*thisCut);
// 		}
// 	    }
// 	    numberCuts = globalCuts_.sizeRowCuts();
// 	    for ( i = 0; i < numberCuts; ++i) {
// 		const OsiRowCut * thisCut = globalCuts_.rowCutPtr(i);
// 		if (thisCut->violated(solution) > primalTolerance) {
// 		    printf("Global cut added - violation %g\n",
// 			   thisCut->violated(solution));
// 		    theseCuts.insert(*thisCut);
// 		}
// 	    }
// 	}

// 	//---------------------------------------------------------------------
// 	// Generate new cuts (global and/or local) and/or apply heuristics
// 	// NOTE: Make sure CglProbing is added FIRST
// 	double * newSolution = new double [numberColumns];
// 	double heuristicValue = getCutoff();

// #if defined(DC_DEBUG_MORE)
// 	    std::cout << "numberCutGenerators_ = " << numberCutGenerators_
// 		      << "numberHeuristics_ = " << numberHeuristics_
// 		      << std::endl;
// #endif
// 	for (int i = 0; i < numberCutGenerators_ + numberHeuristics_; ++i) {
// 	    int numberRowCutsBefore = theseCuts.sizeRowCuts();
// 	    int numberColumnCutsBefore = theseCuts.sizeColCuts();
// 	    if (i < numberCutGenerators_) {
// 		if (cutDuringRampup) {
// 		    bool mustResolve =
// 			generator_[i]->generateCuts(theseCuts, fullScan);
// 		    if (mustResolve) {
// 			feasible = resolve();
// 			if (!feasible)
// 			    break;
// 		    }
// 		}
// 	    }
// 	    else {
// 		double saveValue = heuristicValue;
// 		int ifSol = heuristic_[i-numberCutGenerators_]->
// 		    solution(heuristicValue, newSolution);
// 		    //    solution(heuristicValue, newSolution, theseCuts);

// 		if (ifSol > 0) {
// 		    found = i;
// 		}
// 		else if (ifSol < 0) {
// 		    heuristicValue = saveValue;
// 		}
// 	    }
// 	    int numberRowCutsAfter = theseCuts.sizeRowCuts();
// 	    int numberColumnCutsAfter = theseCuts.sizeColCuts();
// 	    int numberBefore =
// 		numberRowCutsBefore + numberColumnCutsBefore + lastNumberCuts;
// 	    int numberAfter =
// 		numberRowCutsAfter + numberColumnCutsAfter + lastNumberCuts;
// 	    if (numberAfter > maximumWhich) {
// 		maximumWhich = std::max(maximumWhich * 2 + 100, numberAfter);
// 		int * temp = new int[2 * maximumWhich];
// 		memcpy(temp, whichGenerator, numberBefore * sizeof(int));
// 		delete [] whichGenerator;
// 		whichGenerator = temp;
// 	    }
// 	    int j;
// 	    if (fullScan) {
// 		countRowCuts[i] += numberRowCutsAfter -
// 		    numberRowCutsBefore;
// 		countColumnCuts[i] += numberColumnCutsAfter -
// 		    numberColumnCutsBefore;
// 	    }
// 	    for (j = numberRowCutsBefore; j < numberRowCutsAfter; ++j) {
// 		whichGenerator[numberBefore++] = i;
// 		const OsiRowCut * thisCut = theseCuts.rowCutPtr(j);
// 		if (thisCut->globallyValid()) {
// 		    globalCuts_.insert(*thisCut);
// 		}
// 	    }
// 	    for (j = numberColumnCutsBefore; j < numberColumnCutsAfter; ++j) {
// 		whichGenerator[numberBefore++] = i;
// 		const OsiColCut * thisCut = theseCuts.colCutPtr(j);
// 		if (thisCut->globallyValid()) {
// 		    globalCuts_.insert(*thisCut);
// 		}
// 	    }
// 	}

// 	//---------------------------------------------------------------------
// 	// If found a solution, Record it before we free the vector
// 	if (found >= 0) {
// 	    bool better =
// 		setBestSolution(DC_ROUNDING, heuristicValue, newSolution);
// 	    //    if (!better){
// 	    //	found = -1;
// 	    //}
// 	    //std::cout << "better = "  << better
// 	    //	      << "; found = " << found << std::endl;
// 	}
// 	if(newSolution != 0) delete [] newSolution;

// 	int numberColumnCuts = theseCuts.sizeColCuts();
// 	int numberRowCuts = theseCuts.sizeRowCuts();
// 	violated = numberRowCuts + numberColumnCuts;

// 	//---------------------------------------------------------------------
// 	// Apply column cuts
// 	if (numberColumnCuts) {
// 	    double integerTolerance = getDblParam(DcIntegerTolerance);
// 	    for (int i = 0; i < numberColumnCuts; ++i) {
// 		const OsiColCut * thisCut = theseCuts.colCutPtr(i);
// 		const CoinPackedVector & lbs = thisCut->lbs();
// 		const CoinPackedVector & ubs = thisCut->ubs();
// 		int j;
// 		int n;
// 		const int * which;
// 		const double * values;
// 		n = lbs.getNumElements();
// 		which = lbs.getIndices();
// 		values = lbs.getElements();
// 		for (j = 0; j < n; ++j){
// 		    int iColumn = which[j];
// 		    double value = solution[iColumn];
// 		    solver_->setColLower(iColumn, values[j]);
// 		    if (value < values[j] - integerTolerance)
// 			violated = -1;   // violated, TODO: when happen?
// 		    if (values[j] > upper[iColumn] + integerTolerance) {
// 			violated = -2;   // infeasible
// 			break;
// 		    }
// 		}
// 		n = ubs.getNumElements();
// 		which = ubs.getIndices();
// 		values = ubs.getElements();
// 		for (j = 0; j < n; ++j) {
// 		    int iColumn = which[j];
// 		    double value = solution[iColumn];
// 		    solver_->setColUpper(iColumn, values[j]);
// 		    if (value > values[j] + integerTolerance)
// 			violated = -1;
// 		    if (values[j] < lower[iColumn] - integerTolerance) {
// 			violated = -2;   // infeasible
// 			break;
// 		    }
// 		}
// 	    }
// 	}

// 	if (violated == -2) {
// 	    feasible = false ;
// 	    break ;    // break the cut generation loop
// 	}

// 	//---------------------------------------------------------------------
// 	// Now apply the row (constraint) cuts.
// 	int numberRowsNow = solver_->getNumRows();
// 	assert(numberRowsNow == numberRowsAtStart + lastNumberCuts);
// 	int numberToAdd = theseCuts.sizeRowCuts();
// 	numberNewCuts = lastNumberCuts + numberToAdd;

// 	// Get a basis by asking the solver for warm start information.
// 	// Resize it (retaining the basis) so it can accommodate the cuts.
// 	delete basis_;
// 	basis_ = dynamic_cast<CoinWarmStartBasis*>(solver_->getWarmStart());
// 	assert(basis_ != NULL); // make sure not volume
// 	basis_->resize(numberRowsAtStart + numberNewCuts, numberColumns);

// 	//  Now actually add the row cuts and reoptimise.
// 	if (numberRowCuts > 0 || numberColumnCuts > 0) {
// 	    if (numberToAdd > 0) {
// 		int i;
// 		OsiRowCut * addCuts = new OsiRowCut [numberToAdd];
// 		for (i = 0; i < numberToAdd; ++i) {
// 		    addCuts[i] = theseCuts.rowCut(i);
// 		}
// 		solver_->applyRowCuts(numberToAdd, addCuts);
// 		// AJK this caused a memory fault on Win32
// 		delete [] addCuts;
// 		for (i = 0; i < numberToAdd; ++i) {
// 		    cuts.insert(theseCuts.rowCut(i));
// 		}
// 		for (i = 0; i < numberToAdd; ++i) {
// 		    basis_->setArtifStatus(numberRowsNow + i,
// 					   CoinWarmStartBasis::basic);
// 		}
// 		if (solver_->setWarmStart(basis_) == false) {
// 		    throw CoinError("Fail setWarmStart() after cut install.",
// 				    "solveWithCuts", "SbbModel");
// 		}
// 	    }
// 	    feasible = resolve() ;
// 	}
// 	else {
// 	    numberTries = 0;
// 	}

// 	//---------------------------------------------------------------------
// 	if (feasible) {
// 	    int cutIterations = solver_->getIterationCount();
// 	    //takeOffCuts(cuts, whichGenerator,
// 	    // numberOldActiveCuts, numberNewCuts, true);
// 	    if (solver_->isDualObjectiveLimitReached()) {
// 		feasible = false;
// #ifdef DC_DEBUG
// 		double z = solver_->getObjValue();
// 		double cut = getCutoff();
// 		//	printf("Lost feasibility by %g in takeOffCuts; z = %g, cutoff = %g\n",
// 		//   z - cut, z, cut);
// #endif
// 	    }
// 	    if (feasible) {
// 		numberRowsAtStart = numberOldActiveCuts +
// 		    numberRowsAtContinuous_;
// 		lastNumberCuts = numberNewCuts;
// 		if ((direction * solver_->getObjValue() <
// 		    lastObjective + minimumDrop) &&  (numberPasses >= 3)) {
// 		    numberTries = 0;
// 		}
// 		if (numberRowCuts+numberColumnCuts == 0 || cutIterations == 0)
// 		{ break; }
// 		if (numberTries > 0) {
// 		    reducedCostFix();
// 		    lastObjective = direction * solver_->getObjValue();
// 		    lower = solver_->getColLower();
// 		    upper = solver_->getColUpper();
// 		    solution = solver_->getColSolution();
// 		}
// 	    }
// 	}

// 	// We've lost feasibility
// 	if (!feasible) {
// 	    numberTries = 0;
// 	}
//     } while (numberTries);
    // END OF GENERATING CUTS

    //------------------------------------------------------------------------
    // Adjust the frequency of use for any of the cut generator
    double thisObjective = solver_->getObjValue() * direction;
    if (feasible && fullScan && numberCutGenerators_) {
	double totalCuts = 0.0;
	int i;
	for (int i = 0; i < numberCutGenerators_; ++i)
	totalCuts += countRowCuts[i] + 5.0 * countColumnCuts[i];
	// Root node or every so often - see what to turn off
	if (!numberNodes_)
	    handler_->message(DC_ROOT, messages_)
		<< numberNewCuts
		<< startObjective << thisObjective
		<< numberPasses
		<< CoinMessageEol;
	int * count = new int[numberCutGenerators_];
	memset(count, 0, numberCutGenerators_ * sizeof(int));
	for (i = 0; i < numberNewCuts; ++i)
	    count[whichGenerator[i]]++;
	double small = (0.5 * totalCuts) / ((double) numberCutGenerators_);
	for (i = 0; i < numberCutGenerators_; ++i) {
	    int howOften = generator_[i]->howOften();
	    if (howOften < -99)
		continue;
	    if (howOften < 0 || howOften >= 1000000) {
		// If small number switch mostly off
		double thisCuts = countRowCuts[i] + 5.0 * countColumnCuts[i];
		if (!thisCuts || howOften == -99) {
		    if (howOften == -99)
			howOften = -100;
		    else
			howOften = 1000000 + SCANCUTS; // wait until next time
		}
		else if (thisCuts < small) {
		    int k = (int) sqrt(small / thisCuts);
		    howOften = k + 1000000;
		}
		else {
		    howOften = 1 + 1000000;
		}
	    }
	    generator_[i]->setHowOften(howOften);
	    int newFrequency = generator_[i]->howOften() % 1000000;
	    // if (handler_->logLevel() > 1 || !numberNodes_)
	    if (!numberNodes_)
		handler_->message(DC_GENERATOR, messages_)
		    << i
		    << generator_[i]->cutGeneratorName()
		    << countRowCuts[i]
		    << countRowCuts[i] //<<count[i]
		    << countColumnCuts[i]
		    << newFrequency
		    << CoinMessageEol;
	}
	delete [] count;
    }

    delete [] countRowCuts;
    delete [] countColumnCuts;

#ifdef CHECK_CUT_COUNTS
    if (feasible) {
	delete basis_;
	basis_ = dynamic_cast<CoinWarmStartBasis*>(solver_->getWarmStart());
	printf("solveWithCuts: Number of rows at end (only active cuts) %d\n",
	       numberRowsAtContinuous_+numberNewCuts+numberOldActiveCuts);
	basis_->print();
    }
    if (numberNodes_ % 1000 == 0) {
	messageHandler()->message(DC_CUTS, messages_)
	    << numberNodes_
	    << numberNewCuts
	    << startObjective
	    << thisObjective
	    << numberPasses
	    << CoinMessageEol;
    }
#endif


    //takeOffCuts(cuts, whichGenerator, numberOldActiveCuts,
    //		numberNewCuts, true);
    incrementNodeCount();

    return feasible;
}
Esempio n. 16
0
//! [0]
S2Controller::S2Controller(QWidget *parent):   QWidget(parent), networkSession(0)
{

    hostLabel = new QLabel(tr("&Server name:"));
    portLabel = new QLabel(tr("S&erver port:"));
    cmdLabel = new QLabel(tr("Command:"));

    QString ipAddress;
    ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    int portnumber= 1236;
    hostLineEdit = new QLineEdit("10.128.48.53");
    portLineEdit = new QLineEdit("1236");
    portLineEdit->setValidator(new QIntValidator(1, 65535, this));
    cmdLineEdit = new QLineEdit;

    hostLabel->setBuddy(hostLineEdit);
    portLabel->setBuddy(portLineEdit);

    statusLabel = new QLabel(tr(" - - - "));

    sendCommandButton = new QPushButton(tr("Send Command"));
    sendCommandButton->setDefault(true);
    sendCommandButton->setEnabled(true);
    connectButton = new QPushButton(tr("connect to PrairieView"));
    connectButton->setEnabled(true);

    quitButton = new QPushButton(tr("Quit"));
    getReplyButton = new QPushButton(tr("get reply"));

    buttonBox = new QGroupBox;
    QVBoxLayout *vb = new QVBoxLayout;

    vb->addWidget(sendCommandButton);
    vb->addWidget(quitButton);
    vb->addWidget(connectButton);
    vb->addWidget(getReplyButton);
    buttonBox->setLayout(vb);

    tcpSocket = new QTcpSocket(this);

    connect(hostLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enablesendCommandButton()));
    connect(portLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enablesendCommandButton()));
    connect(sendCommandButton, SIGNAL(clicked()),
            this, SLOT(sendCommand()));
    connect(connectButton, SIGNAL(clicked()), this, SLOT(initializeS2()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(checkForMessage()));
    connect(this, SIGNAL(messageIsComplete()), this, SLOT(processMessage()));
    connect(this, SIGNAL(newMessage(QString)),
            this, SLOT(messageHandler(QString)));
    connect(this, SIGNAL(newMessage(QString)),
            this, SLOT(posMonListener(QString)));


    connect(quitButton, SIGNAL(clicked()), this, SLOT(sendX()));

    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(hostLabel, 0, 0);
    mainLayout->addWidget(hostLineEdit, 0, 1);
    mainLayout->addWidget(portLabel, 1, 0);
    mainLayout->addWidget(portLineEdit, 1, 1);
    mainLayout->addWidget(cmdLabel, 2,0);
    mainLayout->addWidget(cmdLineEdit,2,1);
    mainLayout->addWidget(statusLabel, 3, 0, 1, 2);
    mainLayout->addWidget(buttonBox, 4, 0, 1, 2);
    setLayout(mainLayout);

    setWindowTitle(tr("smartScope2 Controller"));
    portLineEdit->setFocus();

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
                QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        sendCommandButton->setEnabled(false);
        statusLabel->setText(tr("Opening network session."));
        networkSession->open();
    }
    //enablesendCommandButton();
    //! [5]
    ii =-1;
    okToSend= true;
    cancelPosMon = false;
    inPosMonMode = false;
}