コード例 #1
0
ファイル: m_pgsql.cpp プロジェクト: AliSharifi/inspircd
	void submit(SQLQuery *req, const std::string& q)
	{
		if (qinprog.q.empty())
		{
			DoQuery(QueueItem(req,q));
		}
		else
		{
			// wait your turn.
			queue.push_back(QueueItem(req,q));
		}
	}
コード例 #2
0
unsigned UnwrappedLineFormatter::analyzeSolutionSpace(LineState &InitialState,
                                                      bool DryRun) {
  std::set<LineState *, CompareLineStatePointers> Seen;

  // Increasing count of \c StateNode items we have created. This is used to
  // create a deterministic order independent of the container.
  unsigned Count = 0;
  QueueType Queue;

  // Insert start element into queue.
  StateNode *Node =
      new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
  Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
  ++Count;

  unsigned Penalty = 0;

  // While not empty, take first element and follow edges.
  while (!Queue.empty()) {
    Penalty = Queue.top().first.first;
    StateNode *Node = Queue.top().second;
    if (!Node->State.NextToken) {
      DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
      break;
    }
    Queue.pop();

    // Cut off the analysis of certain solutions if the analysis gets too
    // complex. See description of IgnoreStackForComparison.
    if (Count > 10000)
      Node->State.IgnoreStackForComparison = true;

    if (!Seen.insert(&Node->State).second)
      // State already examined with lower penalty.
      continue;

    FormatDecision LastFormat = Node->State.NextToken->Decision;
    if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
      addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
    if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
      addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
  }

  if (Queue.empty()) {
    // We were unable to find a solution, do nothing.
    // FIXME: Add diagnostic?
    DEBUG(llvm::dbgs() << "Could not find a solution.\n");
    return 0;
  }

  // Reconstruct the solution.
  if (!DryRun)
    reconstructPath(InitialState, Queue.top().second);

  DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
  DEBUG(llvm::dbgs() << "---\n");

  return Penalty;
}
コード例 #3
0
void HbSplashGenerator::regenerate()
{
    QString themeName = hbInstance->theme()->name();
    qDebug() << PRE << "regenerate() theme:" << themeName;
    if (!themeName.isEmpty()) {
        try {
            emit regenerateStarted();
            QTime queuePrepTime;
            queuePrepTime.start();
            // Delete existing splash screens. This is important because apps
            // should never pick up a screen with the previous theme or
            // language. If the generation of the new screens (at least the
            // empty view) has not finished when a new app is started then it is
            // better to show no splash screen at all.
            QDir outDir(hbsplash_output_dir());
            if (outDir.exists()) {
                QStringList names = outDir.entryList(QStringList() << "*", QDir::Files);
                foreach(const QString & name, names) {
                    outDir.remove(name);
                }
            }
            // Clear the queue, generating screens with a non-current theme is
            // not possible anyway.
            mQueue.clear();
            // If this is the first invocation then put some requests for
            // screens we won't use. On certain platforms the very first
            // rendering (with a newly created mainwindow) may lead to
            // mysteriously scaled down output.
            if (mFirstRegenerate) {
                mFirstRegenerate = false;
                mQueue.enqueue(QueueItem(themeName, Qt::Vertical));
                mQueue.enqueue(QueueItem(themeName, Qt::Horizontal));
            }
            // Queue the screenshot request for both orientations.
            mQueue.enqueue(QueueItem(themeName, Qt::Vertical));
            mQueue.enqueue(QueueItem(themeName, Qt::Horizontal));
            queueAppSpecificItems(themeName, Qt::Vertical);
            queueAppSpecificItems(themeName, Qt::Horizontal);
            qDebug() << PRE << "queue preparation time (ms):" << queuePrepTime.elapsed();
            QMetaObject::invokeMethod(this, "processQueue", Qt::QueuedConnection);
        } catch (const std::bad_alloc &) {
コード例 #4
0
ファイル: Cube.cpp プロジェクト: dalton/mosesdecoder
void Cube::CreateNeighbour(const std::vector<int> &coordinates)
{
  // Add the coordinates to the set of visited coordinates if not already
  // present.
  std::pair<CoordinateSet::iterator, bool> p = m_visited.insert(coordinates);
  if (!p.second) {
    // We have visited this neighbour before, so there is nothing to do.
    return;
  }
  SHyperedge *hyperedge = CreateHyperedge(coordinates);
  const std::vector<int> &storedCoordinates = *p.first;
  m_queue.push(QueueItem(hyperedge, &storedCoordinates));
}
コード例 #5
0
ファイル: Cube.cpp プロジェクト: dalton/mosesdecoder
Cube::Cube(const SHyperedgeBundle &bundle)
    : m_bundle(bundle)
{
  // Create the SHyperedge for the 'corner' of the cube.
  std::vector<int> coordinates(bundle.beams.size()+1, 0);
  SHyperedge *hyperedge = CreateHyperedge(coordinates);
  // Add its coordinates to the set of visited coordinates.
  std::pair<CoordinateSet::iterator, bool> p = m_visited.insert(coordinates);
  const std::vector<int> &storedCoordinates = *p.first;
  // Add the SHyperedge to the queue along with its coordinates (which will be
  // needed for creating its neighbours).
  m_queue.push(QueueItem(hyperedge, &storedCoordinates));
}
コード例 #6
0
void CNoteQueueMidiInputHandler::OnNoteOff(int Note, int Velocity, std::uint32_t TimeStamp)
{
    SQueueItem QueueItem(Note, Velocity, TimeStamp);
    m_NoteQueue.remove(QueueItem);
    if(m_NoteQueue.empty())
    {
        m_Handler->OnNoteOff(Note, Velocity, TimeStamp);
    }
    else if(m_NoteQueue.back()!=QueueItem)
    {
        m_Handler->OnNoteOn(m_NoteQueue.back().s_Note, m_NoteQueue.back().s_Velocity, m_NoteQueue.back().s_TimeStamp);
    }
}
コード例 #7
0
ファイル: CConnection.cpp プロジェクト: lfqt5/FREEDM
///////////////////////////////////////////////////////////////////////////////
/// CConnection::Send
/// @description: Given a message and wether or not it should be sequenced,
///   write that message to the channel.
/// @pre: The CConnection object is initialized.
/// @post: If the window is in not full, the message will have been written to
///   to the channel. Before being sent the message has been signed with the
///   UUID, source hostname and sequence number (if it is being sequenced).
///   If the message is being sequenced  and the window is not already full,
///   the timeout timer is cancelled and reset.
/// @param p_mesg: A CMessage to write to the channel.
/// @param sequence: if true, the message will be sequenced and reliably
///   delievered in order. Otherwise it is immediately fired and forgotten.
///   this is mostly meant for use with ACKs. True by default.
///////////////////////////////////////////////////////////////////////////////
void CConnection::Send(CMessage p_mesg, bool sequence)
{
    Logger::Debug << __PRETTY_FUNCTION__ << std::endl;

    //Make a call to the dispatcher to sign the messages
    //With a bunch of shiny stuff.
    ptree x = static_cast<ptree>(p_mesg);
    unsigned int msgseq;

    //m_dispatch.HandleWrite(x);  

    CMessage outmsg(x);

    // Sign the message with the hostname, uuid, and squencenumber
    if(sequence == true)
    {
        if(m_synched == false)
        {
            m_synched = true;
            SendSYN();
        }
        msgseq = m_outsequenceno;
        outmsg.SetSequenceNumber(msgseq);
        m_outsequenceno = (m_outsequenceno+1) % GetSequenceModulo();
    }
    outmsg.SetSourceUUID(GetConnectionManager().GetUUID()); 
    outmsg.SetSourceHostname(GetConnectionManager().GetHostname());

    if(sequence == true)
    {
        // If it isn't squenced then don't put it in the queue.
        m_queue.Push( QueueItem(msgseq,outmsg) );
    }
    // Before, we would put it into a queue to be sent later, now we are going
    // to immediately write it to channel.

    if(m_queue.size() <= GetWindowSize() || sequence == false)
    {
        // Only try to write to the socket if the window isn't already full.
        // Or it is an unsequenced message
        
        HandleSend(outmsg);
        if(sequence == true)
        {
            m_timeout.cancel();
            m_timeout.expires_from_now(boost::posix_time::milliseconds(1000));
            m_timeout.async_wait(boost::bind(&CConnection::Resend,this,
                boost::asio::placeholders::error));
        }
    }
}
コード例 #8
0
  /// \brief Add the following state to the analysis queue \c Queue.
  ///
  /// Assume the current state is \p PreviousNode and has been reached with a
  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
                           bool NewLine, unsigned *Count, QueueType *Queue) {
    if (NewLine && !Indenter->canBreak(PreviousNode->State))
      return;
    if (!NewLine && Indenter->mustBreak(PreviousNode->State))
      return;

    StateNode *Node = new (Allocator.Allocate())
        StateNode(PreviousNode->State, NewLine, PreviousNode);
    if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
      return;

    Penalty += Indenter->addTokenToState(Node->State, NewLine, true);

    Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
    ++(*Count);
  }
コード例 #9
0
ファイル: m_pgsql.cpp プロジェクト: AliSharifi/inspircd
	void DoConnectedPoll()
	{
restart:
		while (qinprog.q.empty() && !queue.empty())
		{
			/* There's no query currently in progress, and there's queries in the queue. */
			DoQuery(queue.front());
			queue.pop_front();
		}

		if (PQconsumeInput(sql))
		{
			if (PQisBusy(sql))
			{
				/* Nothing happens here */
			}
			else if (qinprog.c)
			{
				/* Fetch the result.. */
				PGresult* result = PQgetResult(sql);

				/* PgSQL would allow a query string to be sent which has multiple
				 * queries in it, this isn't portable across database backends and
				 * we don't want modules doing it. But just in case we make sure we
				 * drain any results there are and just use the last one.
				 * If the module devs are behaving there will only be one result.
				 */
				while (PGresult* temp = PQgetResult(sql))
				{
					PQclear(result);
					result = temp;
				}

				/* ..and the result */
				PgSQLresult reply(result);
				switch(PQresultStatus(result))
				{
					case PGRES_EMPTY_QUERY:
					case PGRES_BAD_RESPONSE:
					case PGRES_FATAL_ERROR:
					{
						SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
						qinprog.c->OnError(err);
						break;
					}
					default:
						/* Other values are not errors */
						qinprog.c->OnResult(reply);
				}

				delete qinprog.c;
				qinprog = QueueItem(NULL, "");
				goto restart;
			}
			else
			{
				qinprog.q.clear();
			}
		}
		else
		{
			/* I think we'll assume this means the server died...it might not,
			 * but I think that any error serious enough we actually get here
			 * deserves to reconnect [/excuse]
			 * Returning true so the core doesn't try and close the connection.
			 */
			DelayReconnect();
		}
	}
コード例 #10
0
/**
 * Perform a breadth first construction of all requested derivatives.
 */
void
DerivativeParsedMaterialHelper::assembleDerivatives()
{
  // need to check for zero derivatives here, otherwise at least one order is generated
  if (_derivative_order < 1) return;

  // if we are not on thread 0 we fetch all data from the thread 0 copy that already did all the work
  if (_tid > 0)
  {
    // get the master object from thread 0
    const MaterialWarehouse<Material> & material_warehouse = _fe_problem.getMaterialWarehouse();
    const ExecuteMooseObjectWarehouse<Material> & warehouse = material_warehouse[_material_data_type];

    MooseSharedPointer<DerivativeParsedMaterialHelper> master =
      MooseSharedNamespace::dynamic_pointer_cast<DerivativeParsedMaterialHelper>(warehouse.getActiveObject(name()));

    // copy parsers and declare properties
    for (unsigned int i = 0; i < master->_derivatives.size(); ++i)
    {
      Derivative newderivative;
      newderivative.first = &declarePropertyDerivative<Real>(_F_name, master->_derivatives[i].darg_names);
      newderivative.second = ADFunctionPtr(new ADFunction(*master->_derivatives[i].second));
      _derivatives.push_back(newderivative);
    }

    // copy coupled material properties
    for (unsigned int i = 0; i < master->_mat_prop_descriptors.size(); ++i)
    {
      FunctionMaterialPropertyDescriptor newdescriptor(master->_mat_prop_descriptors[i]);
      _mat_prop_descriptors.push_back(newdescriptor);
    }

    // size parameter buffer
    _func_params.resize(master->_func_params.size());
  }

  // set up job queue. We need a deque here to be able to iterate over the currently queued items.
  std::deque<QueueItem> queue;
  queue.push_back(QueueItem(_func_F));

  // generate derivatives until the queue is exhausted
  while (!queue.empty())
  {
    QueueItem current = queue.front();

    // all permutations of one set of derivatives are equal, so we make sure to generate only one each
    unsigned int first = current._dargs.empty() ? 0 : current._dargs.back();

    // add necessary derivative steps
    for (unsigned int i = first; i < _nargs; ++i)
    {
      // go through list of material properties and check if derivatives are needed
      unsigned int ndesc = _mat_prop_descriptors.size();
      for (unsigned int jj = 0; jj < ndesc; ++jj)
      {
        FunctionMaterialPropertyDescriptor * j = &_mat_prop_descriptors[jj];

        // take a property descriptor and check if it depends on the current derivative variable
        if (j->dependsOn(_arg_names[i]))
        {
          FunctionMaterialPropertyDescriptor matderivative(*j);
          matderivative.addDerivative(_arg_names[i]);

          // search if this new derivative is not yet in the list of material properties
          MatPropDescriptorList::iterator m = findMatPropDerivative(matderivative);
          if (m == _mat_prop_descriptors.end())
          {
            // construct new variable name for the material property derivative as base name + number
            std::string newvarname = _dmatvar_base + Moose::stringify(_dmatvar_index++);
            matderivative.setSymbolName(newvarname);

            // loop over all queue items to register the new dmatvar variable (includes 'current' which is popped below)
            for (std::deque<QueueItem>::iterator k = queue.begin(); k != queue.end(); ++k)
            {
              k->_F->AddVariable(newvarname);
              k->_F->RegisterDerivative(j->getSymbolName(), _arg_names[i], newvarname);
            }

            _mat_prop_descriptors.push_back(matderivative);
          }
        }
      }

      // construct new derivative
      QueueItem newitem = current;
      newitem._dargs.push_back(i);

      // build derivative
      newitem._F = ADFunctionPtr(new ADFunction(*current._F));
      if (newitem._F->AutoDiff(_variable_names[i]) != -1)
        mooseError("Failed to take order " << newitem._dargs.size() << " derivative in material " << _name);

      // optimize and compile
      if (!_disable_fpoptimizer)
        newitem._F->Optimize();
      if (_enable_jit && !newitem._F->JITCompile())
        mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

      // generate material property argument vector
      std::vector<VariableName> darg_names(0);
      for (unsigned int j = 0; j < newitem._dargs.size(); ++j)
        darg_names.push_back(_arg_names[newitem._dargs[j]]);

      // append to list of derivatives if the derivative is non-vanishing
      if (!newitem._F->isZero())
      {
        Derivative newderivative;
        newderivative.first = &declarePropertyDerivative<Real>(_F_name, darg_names);
        newderivative.second = newitem._F;
        newderivative.darg_names = darg_names;
        _derivatives.push_back(newderivative);
      }

      // push item to queue if further differentiation is required
      if (newitem._dargs.size() < _derivative_order)
        queue.push_back(newitem);
    }

    // remove the 'current' element from the queue
    queue.pop_front();
  }

  // increase the parameter buffer to provide storage for the material property derivatives
  _func_params.resize(_nargs + _mat_prop_descriptors.size());
}