Ejemplo n.º 1
0
/**. The node existence in treee. */
int isChild(Node_t* root, Node_t* node) {
  if (!root)
    return 0;
  if (root == node) 
    return 1;

  // Recursively traverse the tree to see if 
  // the node matches the nodes in the tree.
  return isChild(root->left, node) || 
         isChild(root->right, node);
}
Ejemplo n.º 2
0
Node_t* leastCommonAncestor(Node_t* root, Node_t* node1, Node_t* node2) {
  // Both node1 and node2 belongs to left side.
  if (isChild(root->left, node1) && 
      isChild(root->left, node2))
    return leastCommonAncestor(root->left, node1, node2);
  // Both node1 and node2 belongs to right side.
  else if(isChild(root->right, node1)&&
          isChild(root->right, node2))
    return leastCommonAncestor(root->right, node1, node2);
  else
    return root;
}
Ejemplo n.º 3
0
void SFVDomain::instantiateMembers(){

    // Obtain a pointer to the parent solver:
    std::shared_ptr<SFVSolver> parentSolver(nullptr);
    if (isChild()) parentSolver = parent->getSolver();

    // Instantiate the solver (and so the grid) after the hierarchy is set
    solver = std::make_shared<SFVSolver>(parentSolver);

    // Instantiate the qOutput
    qOutput = std::make_unique<QOutput>(outputDir,isChild(),std::ref(*this), solver->getGrid()->cells);

}
Ejemplo n.º 4
0
void ILocalEntity::addChild(ILocalEntity * child)
{
    if (child != nullptr && child != this && !isChild(child))
    {
        m_children.push_front(child);
        child->setParent(this);
    }
}
Ejemplo n.º 5
0
//-----------------------------------------------------------------------------
CMouseEventResult CDataBrowser::onMouseDown (CPoint& where, const CButtonState& buttons)
{
	CMouseEventResult result = CViewContainer::onMouseDown (where, buttons);
	CView* focusView = getFrame ()->getFocusView ();
	if (focusView != dbView && !isChild (focusView, true))
		getFrame ()->setFocusView (dbView);
	return result;
}
Ejemplo n.º 6
0
void SFVDomain::doInitialize(){

    // Initialize the solver:
    solver->initialize();

    // write the headers of the output files:
    qOutput->writeHeader();

    // Insert the phase functions which are to be called every timestep
    if (solver->get_dimension()==1){

        // Phase-0: timestep initialization
        insertPhase([this](unsigned int ts){
            if (isChild()){
                solver->adjustPatches(ts);
                solver->imposePatchBCs(0);
            }
            solver->imposeGridBC(ts);
        });

        // Phase-1: Riemann solver
        insertPhase([this](unsigned int ts){
            solver->riemann(0);
        });

        // Phase-2: Calculate new Q values
        insertPhase([this](unsigned int ts){
            solver->calculateQ();
            solver->applyBottomFriction();
            if (isChild()){
                solver->getQfromParent();
            }
        });

        // Phase-3: Post-processing
        insertPhase([this](unsigned int ts){
            qOutput->writeOutput(ts);
        });

    }
    else if (solver->get_dimension()==2){
        Report::error("SFVDomain","2d solver not yet supported!");
    }

}
Ejemplo n.º 7
0
/** Adds a group to the list of \ref children of this group. It will first be detached from its previous parent group if necessary. No child id can be shared amongst several children of the same group. */
void Group::addChild(shared_ptr< Group > child) {
  // Bouml preserved body begin 0001F9E5
    if (!child)
        throw Exception("Couldn't add child, it's uninitialized.");
    shared_ptr<Group> t = shared_from_this();
    if (t == child)
        throw Exception("Couldn't add child to itself.");
    if (isChild(child))
        throw Exception("Couldn't add child, it's already a child.");
    if (isAncestor(child))
        throw Exception("Couldn't add child, it must not be any ancestor of this group.");
    if (isChild(child->getId()))
        throw Exception("Couldn't add child, its id is already in use by another child.");

    child->setParent(t);
    children.push_back(child);
  // Bouml preserved body end 0001F9E5
}
Ejemplo n.º 8
0
void SaveNexus::runSaveNexusProcessed() {
  IAlgorithm_sptr saveNexusPro =
      createChildAlgorithm("SaveNexusProcessed", 0.0, 1.0, true);
  // Pass through the same output filename
  saveNexusPro->setPropertyValue("Filename", m_filename);
  // Set the workspace property
  std::string inputWorkspace = "InputWorkspace";
  saveNexusPro->setProperty(inputWorkspace, m_inputWorkspace);
  //
  std::vector<int> specList = getProperty("WorkspaceIndexList");
  if (!specList.empty())
    saveNexusPro->setPropertyValue("WorkspaceIndexList",
                                   getPropertyValue("WorkspaceIndexList"));
  //
  int specMax = getProperty("WorkspaceIndexMax");
  if (specMax != Mantid::EMPTY_INT()) {
    saveNexusPro->setPropertyValue("WorkspaceIndexMax",
                                   getPropertyValue("WorkspaceIndexMax"));
    saveNexusPro->setPropertyValue("WorkspaceIndexMin",
                                   getPropertyValue("WorkspaceIndexMin"));
  }
  std::string title = getProperty("Title");
  if (!title.empty())
    saveNexusPro->setPropertyValue("Title", getPropertyValue("Title"));

  // Pass through the append property
  saveNexusPro->setProperty<bool>("Append", getProperty("Append"));

  // If we're tracking history, add the entry before we save it to file
  if (trackingHistory()) {
    m_history->fillAlgorithmHistory(
        this, Mantid::Kernel::DateAndTime::getCurrentTime(), 0,
        Algorithm::g_execCount);
    if (!isChild()) {
      m_inputWorkspace->history().addHistory(m_history);
    }
    // this is a child algorithm, but we still want to keep the history.
    else if (isRecordingHistoryForChild() && m_parentHistory) {
      m_parentHistory->addChildHistory(m_history);
    }
  }
  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  try {
    saveNexusPro->execute();
  } catch (std::runtime_error &) {
    g_log.error(
        "Unable to successfully run SaveNexusprocessed Child Algorithm");
  }
  if (!saveNexusPro->isExecuted())
    g_log.error(
        "Unable to successfully run SaveNexusProcessed Child Algorithm");
  //
  progress(1);
}
Ejemplo n.º 9
0
void TreeNode::removeChild(boost::shared_ptr<TreeNode> objectPtr,bool callback)
{
    if(isChild(objectPtr))
    {
        this->children.erase(std::find(this->children.begin(), this->children.end(), objectPtr));
        this->childrenNames.erase(std::find(this->childrenNames.begin(), this->childrenNames.end(), objectPtr->getName()));
	if(callback)
	  objectPtr->setParent();

    }
}
Ejemplo n.º 10
0
static int
isa(const char *sns, const char *child, const char *parent)
{
  int             rv;
  _SFCB_ENTER(TRACE_INDPROVIDER, "isa");
    
  if (strcasecmp(child, parent) == 0)
    return 1;
  rv = isChild(sns, parent, child);
  _SFCB_RETURN(rv);
}
Ejemplo n.º 11
0
/** Returns the child group that has the provided id string. \sa addChild */
shared_ptr<Group> Group::getChild(const string & id) const {
  // Bouml preserved body begin 0001F5C0
    vector<shared_ptr<Group> >::const_iterator result;
    if (!isChild(id))
        throw Exception ("Couldn't get child, none has the provided id.");

    for(result=children.begin(); result!=children.end(); result++)
        if ((*result)->getId() == id)
            break;

    return *result;
  // Bouml preserved body end 0001F5C0
}
Ejemplo n.º 12
0
/*
 * The program is passed as a vector of strings which is parsed from the text file back in main.
 * I do this in part due to the single responsibility principle. However, the main reason is that
 * it allows me to easily write unit test which exercise the functionality of the CPU.
 * The unit test are likely not include with this assignment.
 */
ComputerSim::ComputerSim(const std::vector<std::string>& program, const int timerInterval) {
    int cpuToMem[2];
    int memToCpu[2];
    tryPipe(cpuToMem, memToCpu);
    int forkResult = tryFork();

    if (isChild(forkResult)) {
        Memory m(cpuToMem[0], memToCpu[1], program);
    } else if (isParent(forkResult)) {
        Cpu c(memToCpu[0], cpuToMem[1], timerInterval);
        waitpid(-1, NULL, 0); // wait for child
    }
}
Ejemplo n.º 13
0
/** Makes up the correct history of the output workspace
*/
void ConjoinXRuns::fillHistory() {
  // If this is not a child algorithm add the history
  if (!isChild()) {
    // Loop over the input workspaces, making the call that copies their
    // history to the output one
    for (auto &inWS : m_inputWS) {
      m_outWS->history().addHistory(inWS->getHistory());
    }
    // Add the history for the current algorithm to the output
    m_outWS->history().addHistory(m_history);
  }
  // this is a child algorithm, but we still want to keep the history.
  else if (isRecordingHistoryForChild() && m_parentHistory) {
    m_parentHistory->addChildHistory(m_history);
  }
}
Ejemplo n.º 14
0
std::size_t htd::PathDecomposition::rememberedVertexCount(htd::vertex_t vertex, htd::vertex_t child) const
{
    std::size_t ret = 0;

    if (isVertex(vertex) && isChild(vertex, child))
    {
        const htd::ConstCollection<htd::vertex_t> & bag = bagContent(vertex);
        const htd::ConstCollection<htd::vertex_t> & childBag = bagContent(child);

        ret = htd::compute_set_intersection_size(bag.begin(), bag.end(), childBag.begin(), childBag.end());
    }
    else
    {
        throw std::logic_error("std::size_t htd::PathDecomposition::rememberedVertexCount(htd::vertex_t, htd::vertex_t) const");
    }

    return ret;
}
Ejemplo n.º 15
0
void CLayoutVertical::addChild(IWidget * widget, TAlignment align, int pos, int stretch)
{
    if (widget && !isChild(widget))
    {
        widget->setParent(this);

        int i = 0;
        int y = 0;

        TLayoutItem tmp;
        tmp.widget  = widget;
        tmp.align   = align;
        tmp.stretch = stretch;
        tmp.size    = widget->getHeight() + m_padding.getTop() + m_padding.getBottom();

        // On insère l'objet à la fin de la liste
        if (pos < 0 || pos >= getNumChildren())
        {
            m_children.push_back(tmp);
        }
        else
        {
            for (std::list<TLayoutItem>::iterator it = m_children.begin(); it != m_children.end(); ++it, ++i)
            {
                if (i == pos)
                {
                    it = m_children.insert(it, tmp);
                    y += tmp.size;
                }

                y += it->widget->getHeight();
            }
        }

        if (y > m_height)
        {
            setHeight(y);
        }
        else
        {
            computeSize();
        }
    }
}
Ejemplo n.º 16
0
/**
 * Process two groups and ensure the Result string is set properly on the final
 * algorithm.
 *
 * @return A boolean true if execution was sucessful, false otherwise
 */
bool CompareWorkspaces::processGroups() {
  m_Result = true;
  m_Messages->setRowCount(0); // Clear table

  // Get workspaces
  Workspace_const_sptr w1 = getProperty("Workspace1");
  Workspace_const_sptr w2 = getProperty("Workspace2");

  // Attempt to cast to WorkspaceGroups (will be nullptr on failure)
  WorkspaceGroup_const_sptr ws1 =
      boost::dynamic_pointer_cast<const WorkspaceGroup>(w1);
  WorkspaceGroup_const_sptr ws2 =
      boost::dynamic_pointer_cast<const WorkspaceGroup>(w2);

  if (ws1 && ws2) { // Both are groups
    processGroups(ws1, ws2);
  } else if (!ws1 && !ws2) { // Neither are groups (shouldn't happen)
    m_Result = false;
    throw std::runtime_error("CompareWorkspaces::processGroups - Neither "
                             "input is a WorkspaceGroup. This is a logical "
                             "error in the code.");
  } else if (!ws1 || !ws2) {
    recordMismatch(
        "Type mismatch. One workspace is a group, the other is not.");
  }

  if (m_Result && ws1 && ws2) {
    g_log.notice() << "All workspaces in workspace groups \"" << ws1->name()
                   << "\" and \"" << ws2->name() << "\" matched!" << std::endl;
  }

  setProperty("Result", m_Result);
  setProperty("Messages", m_Messages);

  // Store output workspace in AnalysisDataService
  if (!isChild())
    this->store();

  setExecuted(true);
  notificationCenter().postNotification(
      new FinishedNotification(this, this->isExecuted()));

  return true;
}
Ejemplo n.º 17
0
htd::ConstCollection<htd::vertex_t> htd::PathDecomposition::rememberedVertices(htd::vertex_t vertex, htd::vertex_t child) const
{
    htd::VectorAdapter<htd::vertex_t> ret;

    auto & result = ret.container();

    if (isVertex(vertex) && isChild(vertex, child))
    {
        const htd::ConstCollection<htd::vertex_t> & bag = bagContent(vertex);
        const htd::ConstCollection<htd::vertex_t> & childBag = bagContent(child);

        std::set_intersection(bag.begin(), bag.end(), childBag.begin(), childBag.end(), std::back_inserter(result));
    }
    else
    {
        throw std::logic_error("htd::ConstCollection<htd::vertex_t> htd::PathDecomposition::rememberedVertices(htd::vertex_t, htd::vertex_t) const");
    }

    return htd::ConstCollection<htd::vertex_t>::getInstance(ret);
}
Ejemplo n.º 18
0
static int  instCompare(QLOperand* self, QLOperand* op, QLPropertySource* src)
{
   CMPIInstance *ov=NULL;
   char *sov;
   QLOpd type=op->type;
   
   sov=(char*)instGetClassName(self->inst);
   if (type==QL_PropertyName) {
      ov=getPropValue(op, src, &type).inst;
   }
   
   if (type==QL_Name) {
      if (strcasecmp(sov,op->charsVal)==0) return 0;
      return isChild(src->sns,op->charsVal,sov)==0;
   }
   if (type==QL_Inst) {
      return instanceCompare(self->inst, ov);
   }
   return -2;
}
Ejemplo n.º 19
0
//-----------------------------------------------------------------------------
CMessageResult CScrollContainer::notify (CBaseObject* sender, IdStringPtr message)
{
	if (message == kMsgViewSizeChanged && !inScrolling)
	{
		uint32_t numSubViews = getNbViews ();
		CView* view = static_cast<CView*> (sender);
		if (numSubViews == 1 && view && isChild (view))
		{
			CRect r (view->getViewSize ());
			CRect newContainerSize (containerSize);
			newContainerSize.setWidth (r.getWidth ());
			newContainerSize.setHeight (r.getHeight ());
			if (newContainerSize != containerSize)
			{
				CScrollView* scrollView = (CScrollView*)getParentView ();
				scrollView->setContainerSize (newContainerSize);
			}
		}
	}
	return getParentView () ? getParentView ()->notify (sender, message) : kMessageUnknown;
}
Ejemplo n.º 20
0
int ProtoNode::row()
{
    if (!isChild()) {
        return -1;
    }

    int cur_row = 0;
    ProtoNode::ChildIterator kids = parentNode().children();
    while ( kids.element().isValid() )
    {
        if ( kids.element().protoNode() == node_ ) {
            break;
        }
        cur_row++;
        kids.next();
    }
    if ( ! kids.element().isValid() ) {
        return -1;
    }
    return cur_row;
}
Ejemplo n.º 21
0
	void FalagardSuperTooltip::setPageElementsName(const String& strName)
	{
		//Split string 
		std::vector< String > vElementNameVector = split_string(strName, (utf8*)";", getChildCount());

		//Hide all sub window
		int nChildSize = (int)getChildCount();
		for(int i=0; i<nChildSize; i++)
		{
			d_children[i]->hide();
		}

		//Clear old elements
		d_VectorElements.clear();
		int nSize = (int)vElementNameVector.size();
		for(int i=0; i<nSize; i++)
		{
			//Only accept child window
			if(!isChild(vElementNameVector[i])) continue;

			//Get Child window
			Window* pChild = getChild(vElementNameVector[i]);
			pChild->show();

			Elements newElement;
			newElement.pWindow = pChild;
			//Dynamic size window (Resize Text)
			if(pChild->testClassName("FalagardSuperTooltip/ResizeText"))
			{
				newElement.bDynamicSize = true;
			}
			//Static size window
			else
			{
				newElement.bDynamicSize = false;
			}

			d_VectorElements.push_back(newElement);
		}
	}
Ejemplo n.º 22
0
bool InputEventRecorder::eventFilter(QObject *obj, QEvent *ev)
{
    if (m_InReplay || !m_ReplayFilter.isEmpty())
    {
        if (!m_ReplayFilter.remove(ev) && isRecordable(ev))
            return true; /* filtering external events during replays */
        else if (m_ReplayFilter.isEmpty() && !m_InReplay)
            qApp->removeEventFilter(this);
        return false;
    }

    if ((obj != m_Obj) && !isChild(obj, m_Obj))
        return false;

    /* stop recording when we detect ctrl-c */
    if (ev && ev->type() == QEvent::KeyPress)
    {
        QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
        if ((kev->modifiers() == Qt::ControlModifier) &&
                (kev->key() == Qt::Key_C))
        {
            stop();
            return false;
        }
    }

    QEvent *clonedEv = cloneEvent(ev);

    if (clonedEv)
    {
        int timeOffset;
        QDateTime curDt(QDateTime::currentDateTime());
        timeOffset = m_RecordingStartTime.daysTo(curDt) * 24 * 3600 * 1000 + m_RecordingStartTime.time().msecsTo(curDt.time());
        m_Recording.push_back(EventDelivery(timeOffset, obj, clonedEv));
    }

    return false;
}
Ejemplo n.º 23
0
TokenTyp MODULE::parseOptPar(QMap<std::string, Occurence> *nameOptPar)
{
    if (nameOptPar->isEmpty())
        return nextToken();
    else
    {
        TokenTyp token = nextToken();
        while (token == BlockBegin || token == Keyword)
        {
            //Nodes
            if (token == BlockBegin)
            {
                token = this->nextToken();
                if (token == Keyword)
                {
                    std::string lexem = lex->getLexem();
                    if (factoryOptNode->contains(lexem))
                    {
                        if (this->occOptPar->value(lexem) == ZeroOrOne)
                        {
                            this->occOptPar->insert(lexem, Zero);
                            Node  *instance = factoryOptNode->value(lexem)->createInstance(this);
                            this->addChildNode(instance);
                            token = nextToken();
                        }
                        else if (this->occOptPar->value(lexem) == ZeroOrMore)
                        {
                            Node *instance;
                            if (lexem == "CHARACTERISTIC")
                            {
                                if (!this->isChild("CHARACTERISTIC"))
                                {
                                    Node *Char = new Node(this, this->lex, this->errorList);
                                    Char->name = (char*)"CHARACTERISTIC";
                                    this->addChildNode(Char);
                                    //Char->_pixmap = ":/icones/CHAR.bmp";
                                    Char->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("CHARACTERISTIC", false));
                                child("CHARACTERISTIC", false)->addChildNode(instance);
                                listChar.append(instance->name);
                            }
                            else if (lexem == "AXIS_PTS")
                            {
                                if (!this->isChild("AXIS_PTS"))
                                {
                                    Node *Axis = new Node(this, this->lex, this->errorList);
                                    Axis->name = (char*)"AXIS_PTS";
                                    this->addChildNode(Axis);
                                    //Axis->_pixmap = ":/icones/AXIS.bmp";
                                    Axis->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("AXIS_PTS", false));
                                child("AXIS_PTS", false)->addChildNode(instance);
                                listChar.append(instance->name);
                            }
                            else if (lexem == "MEASUREMENT")
                            {
                                if (!this->isChild("MEASUREMENT"))
                                {
                                    Node *Meas = new Node(this, this->lex, this->errorList);
                                    Meas->name = (char*)"MEASUREMENT";
                                    this->addChildNode(Meas);
                                    //Meas->_pixmap = ":/icones/MEAS.bmp";
                                    Meas->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("MEASUREMENT", false));
                                child("MEASUREMENT", false)->addChildNode(instance);
                            }
                            else if (lexem == "FUNCTION")
                            {
                                if (!this->isChild("FUNCTION"))
                                {
                                    Node *Func = new Node(this, this->lex, this->errorList);
                                    Func->name = (char*)"FUNCTION";
                                    this->addChildNode(Func);
                                    //Func->_pixmap = ":/icones/FUNCTION.bmp";
                                    Func->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("FUNCTION", false));
                                child("FUNCTION", false)->addChildNode(instance);
                            }
                            else if (lexem == "GROUP")
                            {
                                if (!this->isChild("GROUP"))
                                {
                                    Node *Grp = new Node(this, this->lex, this->errorList);
                                    Grp->name = (char*)"GROUP";
                                    this->addChildNode(Grp);
                                    //Func->_pixmap = ":/icones/FUNCTION.bmp";
                                    Grp->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("GROUP", false));
                                child("GROUP", false)->addChildNode(instance);
                            }
                            else if (lexem == "UNIT")
                            {
                                if (!this->isChild("UNIT"))
                                {
                                    Node *Grp = new Node(this, this->lex, this->errorList);
                                    Grp->name = (char*)"UNIT";
                                    this->addChildNode(Grp);
                                    //Func->_pixmap = ":/icones/FUNCTION.bmp";
                                    Grp->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("UNIT", false));
                                child("UNIT", false)->addChildNode(instance);
                            }
                            else if (lexem == "COMPU_METHOD")
                            {
                                if (!this->isChild("COMPU_METHOD"))
                                {
                                    Node *Comp_m = new Node(this, this->lex, this->errorList);
                                    Comp_m->name = (char*)"COMPU_METHOD";
                                    this->addChildNode(Comp_m);
                                    //Comp_m->_pixmap = ":/icones/COMPU_METHOD.bmp";
                                    Comp_m->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("COMPU_METHOD", false));
                                child("COMPU_METHOD", false)->addChildNode(instance);
                            }
                            else if (lexem == "COMPU_VTAB")
                            {
                                if (!this->isChild("COMPU_VTAB"))
                                {
                                    Node *Comp_v = new Node(this, this->lex, this->errorList);
                                    Comp_v->name = (char*)"COMPU_VTAB";
                                    this->addChildNode(Comp_v);
                                    //Comp_v->_pixmap = ":/icones/COMPU_VTAB.bmp";
                                    Comp_v->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("COMPU_VTAB", false));
                                child("COMPU_VTAB", false)->addChildNode(instance);
                            }
                            else if (lexem == "RECORD_LAYOUT")
                            {
                                if (!this->isChild("RECORD_LAYOUT"))
                                {
                                    Node *Rec = new Node(this, this->lex, this->errorList);
                                    Rec->name = (char*)"RECORD_LAYOUT";
                                    this->addChildNode(Rec);
                                    //Rec->_pixmap = ":/icones/CONV.bmp";
                                    Rec->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("RECORD_LAYOUT", false));
                                child("RECORD_LAYOUT", false)->addChildNode(instance);
                            }
                            else if (lexem == "IF_DATA")
                            {
                                if (!isChild("IF_DATA"))
                                {
                                    Node *If_data = new Node(this, this->lex, this->errorList);
                                    If_data->name = (char*)"IF_DATA";
                                    this->addChildNode(If_data);
                                    //If_data->_pixmap = ":/icones/MOD_PAR.bmp";
                                    If_data->_pixmap = "";
                                }
                                instance = factoryOptNode->value(lexem)->createInstance(child("IF_DATA", false));
                                child("IF_DATA", false)->addChildNode(instance);
                            }
                            else
                            {
                                instance = factoryOptNode->value(lexem)->createInstance(this);
                                this->addChildNode(instance);
                            }

                            token = nextToken();
                        }
                        else
                        {
                            QString s(lexem.c_str());
                            this->showError(" Keyword : " + s + " can only be once declared");
                            return token;
                        }
                    }
                    else
                    {
                        QString s(lexem.c_str());
                        this->showError("unknown Keyword : " + s);
                        return token;
                    }
                }
                else
                {
                    QString s(lex->toString(token).c_str());
                    this->showError("expected token : BlockBegin or Keyword\nfind token : " + s);
                    return token;
                }
            }
            //Items
            else if (token == Keyword)
            {
                std::string lexem = lex->getLexem();
                if (factoryOptItem->contains(lexem))
                {
                    if (this->occOptPar->value(lexem) == ZeroOrOne)
                    {
                        this->occOptPar->insert(lexem, Zero);
                        Item  *instance = factoryOptItem->value(lexem)->createInstance(this);
                        this->addOptItem(instance);
                        token = nextToken();
                    }
                    else if (this->occOptPar->value(lexem) == ZeroOrMore)
                    {
                        Item  *instance = factoryOptItem->value(lexem)->createInstance(this);
                        this->addOptItem(instance);
                        token = nextToken();
                    }
                    else
                    {
                        QString s(lexem.c_str());
                        this->showError(" Keyword : " + s + " can only be once declared");
                        return token;
                    }
                }
                else
                {
                    QString s(lexem.c_str());
                    this->showError("unknown Keyword : " + s);
                    return token;
                }
            }
        }
        
        return token;
    }
}
Ejemplo n.º 24
0
//-----------------------------------------------------------------------------
bool CFrame::advanceNextFocusView (CView* oldFocus, bool reverse)
{
	if (pModalView)
	{
		CViewContainer* container = dynamic_cast<CViewContainer*> (pModalView);
		if (container)
		{
			if (oldFocus == 0 || container->isChild (oldFocus, true) == false)
				return container->advanceNextFocusView (0, reverse);
			else
			{
				CViewContainer* parentView = static_cast<CViewContainer*> (oldFocus->getParentView ());
				if (parentView)
				{
					CView* tempOldFocus = oldFocus;
					while (parentView != container)
					{
						if (parentView->advanceNextFocusView (tempOldFocus, reverse))
							return true;
						else
						{
							tempOldFocus = parentView;
							parentView = static_cast<CViewContainer*> (parentView->getParentView ());
						}
					}
					if (container->advanceNextFocusView (tempOldFocus, reverse))
						return true;
					return container->advanceNextFocusView (0, reverse);
				}
			}
		}
		else if (oldFocus != pModalView)
		{
			setFocusView (pModalView);
			return true;
		}
		return false; // currently not supported, but should be done sometime
	}
	if (oldFocus == 0)
	{
		if (pFocusView == 0)
			return CViewContainer::advanceNextFocusView (0, reverse);
		oldFocus = pFocusView;
	}
	if (isChild (oldFocus))
	{
		if (CViewContainer::advanceNextFocusView (oldFocus, reverse))
			return true;
		else
		{
			setFocusView (0);
			return false;
		}
	}
	CViewContainer* parentView = static_cast<CViewContainer*> (oldFocus->getParentView ());
	if (parentView)
	{
		CView* tempOldFocus = oldFocus;
		while (parentView)
		{
			if (parentView->advanceNextFocusView (tempOldFocus, reverse))
				return true;
			else
			{
				tempOldFocus = parentView;
				parentView = static_cast<CViewContainer*> (parentView->getParentView ());
			}
		}
	}
	return CViewContainer::advanceNextFocusView (oldFocus, reverse);
}
Ejemplo n.º 25
0
void SPC_HIERARCHICAL(edge_t * V, nid_t n, int d, int k, nid_t minClusSize, int Nmc, int * Nc, nid_t ** Cn, nid_t *** C, nid_t ** P)
{
    // Declare variables
    FS_TREE * FST;
  	Graph * D, * MSG, * Tb;
    edge_t tmin, tmax, aKi, aWs, ival, b_thresh, tval, maxval, cval, Tsp;
    edge_t minTempStep, minTempStep_end, ta, tb, tc, Tspa;
    edge_t * Teval;
    nid_t tid, maxid, mcid, Sma, Smb, Smc, cid, cid2, tcs;
    nid_t * maxCor, * Ct, * MCS, * MCI, * newC;
    List * S;  
    int i, j, l, init_temps, ei, scan_temps, scan_print, ilc, ncf, Njumps;
    int p, jj, maxPosClusts, llci, hier_print, plt, nsplits;
    int SI[1000]; 
    int ** Ch;
    int * ChN, * newCh;


    //0. Find the fair-split tree
    //mexPrintf("Computing fair-split tree...\n"); mexEvalString("drawnow;");
    FST = FAIR_SPLIT(V, n, d); //compute the fair split tree
    //mexPrintf("  Finished.\n"); mexEvalString("drawnow;");


    // 1. Find mutual K Nearest Neighbors
    mexPrintf("Finding mutual K Nearest Neighbors...\n"); mexEvalString("drawnow;");
    D = NEW_ALGRAPH(n,0); //graph of distances between mutual KNN
    FS_AMKNN(FST, D, n, k); //compute the approx MKNN using the fair-split tree
    mexPrintf("  Finished.\n"); mexEvalString("drawnow;");


    // 2. Find Approximate Minimum Spanning Graph
    //mexPrintf("Approximating the minimum spanning graph...\n"); mexEvalString("drawnow;");
    MSG = NEW_ALGRAPH(n,0); //allocate new graph for min span graph
    FS_AEMSG(FST, MSG); //compute approx. min spanning graph using fair-split tree
    //mexPrintf("  Finished.\n"); mexEvalString("drawnow;");
    CLEAR_FS_TREE(FST); //don't need the tree anymore


    // 3. Superimpose KNN and MST
    ALG_ORIP(D, MSG); //OR the edges of each graph, store in D
    ALG_CLEAR(MSG); //free the MST from mem


    // 4. Calculate interaction values between each neighbor
    b_thresh = 0.5; //probability threshold for edge
    aKi = 1.0/(2.0*((float) D->ne)/((float) D->n)); //inverse of avg. number of neighbors
    aWs = ALG_AVG_EDGE_WEIGHT(D); //the average distance between neighbors
    aWs = 2.0*aWs*aWs; //twice the squared average distance between neighbors
    Tb = NEW_ALGRAPH(n, 0); //allocate new graph for break temps
    for (i=0;  i<D->n; i++) { //for each node
        for (j=0; j<LIST_LENGTH(D->nodes[i]); j++) { //for each edge from that node
            tid = LIST_GET_ID(D->nodes[i], j); //id of edge's endpoint
            if (i < tid) { //undir graph, so only worry about lesser->larger id edges
                tval = LIST_GET_VAL(D->nodes[i], j); //distance between i and tid
                ival = aKi*exp(-tval*tval/aWs); //this interaction strength
                ival = -ival/log(1.0-b_thresh); //the temp above which this edge breaks
                ival = 1e3*ival*ival*ival; //cubing it and *1k seems to work well just to get a more linear eval
                if (ival > tmax) tmax = ival; //store max edge val
                if (ival < tmin) tmin = ival; //store min val
                ALG_ADD_EDGE(Tb, i, tid, ival); //add the interaction to the graph
            }
        }
    }


    // Get the max-correlation neighbor of each point
    maxCor = malloc(Tb->n * sizeof(nid_t)); //id of the max-cor point for each point
    for (i=0; i<Tb->n; i++) { //for each node
        maxid = 0;
        maxval = 0;
        for (j=1; j<LIST_LENGTH(Tb->nodes[i]); j++) { //for each edge
            mcid = LIST_GET_ID(Tb->nodes[i], j); //get this child's id
            cval = LIST_GET_VAL(Tb->nodes[i], j); //get child's value
            if (cval > maxval) {
                maxval = cval;
                maxid = mcid;
            }
        }
        maxCor[i] = maxid;
    }
    

    // 5. Guestimate SPM-to-Paramagnetic phase transition temperature
    Tsp = tmax;


    // 6. Evaluate at the theoretical SPM->PM temp
    init_temps = 100;
    ei = 0;  //index of current evaluation
    S = NEW_LIST(10); //dfs stack of nodes to visit during subgraphs search
    Teval = malloc(init_temps*sizeof(edge_t)); //temps which were evaluated
    Ct = malloc(n*init_temps*sizeof(nid_t)); //clusterids at each temp
    MCS = malloc(Nmc*init_temps*sizeof(nid_t)); //max cluster sizes
    MCI = malloc(Nmc*init_temps*sizeof(nid_t)); //ids of the max clusters
    THRESH_SUBGRAPHS_SIZES(Tb, maxCor, Tsp, Nmc, S, Ct, MCS, MCI); //find the cluster ids and sizes of the largest clusters at the theoretical temp
    *Teval = Tsp; //store where we evaluated at
    ei++; //increment evaluation index

    // 6.5 "Evaluate" at T=0
    for (i=0; i<n; i++) { *(Ct+n+i) = 1; } //all points are of the same cluster
    for (i=1; i<Nmc; i++) { *(MCI+Nmc+i) = -1; } //all points are of the same cluster
    for (i=1; i<Nmc; i++) { *(MCS+Nmc+i) = 0; } //all other cluster sizes are 0
    *(MCS+Nmc) = n; //at lowest temp, largest cluster consists of all points
    *(MCI+Nmc) = 1; //and it has id of 1
    *(Teval+1) = 0.0;
    ei++;


    // 7. Find the true SPM->PM phase transition temperature
    //mexPrintf("Finding true SPM->PM temp...\n");
    minTempStep_end = Tsp/100;
    ta=0; tb=Tsp; //bound temps for binary search
    Sma=n; Smb=*MCS; //max cluster size at bound temps
    while ( tb-ta > minTempStep_end ) {
        if ( Smb > minClusSize ) { //SPM->PM temp is above our bracket
            ta = tb; //set A to B
            Sma = Smb; //set A to B
            tb = 2*tb; //extend bracket range
            *(Teval+ei) = tb; //evaluate at new T
            THRESH_SUBGRAPHS_SIZES(Tb, maxCor, tb, Nmc, S, Ct+ei*n, MCS+ei*Nmc, MCI+ei*Nmc);
            Smb = *(MCS+ei*Nmc); //store the max cluster size @ that temp
        } else { //SPM->PM temp is below top bracket
            tc = (ta+tb)/2; //midpoint temperature between brackets
            *(Teval+ei) = tc; //evaluate at midpoint
            THRESH_SUBGRAPHS_SIZES(Tb, maxCor, tc, Nmc, S, Ct+ei*n, MCS+ei*Nmc, MCI+ei*Nmc);
            Smc = *(MCS+ei*Nmc); //store the max cluster size @ that temp
            if ( Smc < minClusSize ) { //SPM->PM is between A and C
                tb = tc; //set B to C
                Smb = Smc;
            } else { //SPM->PM is between C and B
                ta = tc; //set A to C
            }
        }
        ei++; //increment evaluation index
        if (ei >= init_temps) { //double array sizes if we need more space
            doubleArraySizes(&Teval, &Ct, &MCS, &MCI, &init_temps, n, Nmc);
        }
    }
    Tspa = tb; //the actual SPM->PM transtion temperature
    //mexPrintf("  Finished.\n");


    // 8. Do an initial scan across temperatures
    scan_temps = 50;  
    scan_print = scan_temps/10;
    mexPrintf("Performing initial scan over temperatures...\n"); mexEvalString("drawnow;");
    for (i=1; i<scan_temps; i++) {
        tc = i*Tspa/scan_temps; //linspace from 0 to SPM->PM
        *(Teval+ei) = tc; //evaluate at each temp
        THRESH_SUBGRAPHS_SIZES(Tb, maxCor, tc, Nmc, S, Ct+ei*n, MCS+ei*Nmc, MCI+ei*Nmc);
        ei++;
        if (ei >= init_temps) { //double array sizes if we need more space
            doubleArraySizes(&Teval, &Ct, &MCS, &MCI, &init_temps, n, Nmc);
        }
    scan_print = scan_temps/10;
        if (i%scan_print==0) { //print progress
            //mexPrintf("  %.1f percent complete\n", 100 * (float) i / (float) scan_temps);
            //mexEvalString("drawnow;");
        }
    }
    mexPrintf("  Finished.\n"); mexEvalString("drawnow;");


    // 9. Find the jump points for each i-th largest cluster
    minTempStep = Tspa/800;
    Njumps = 0;  //number of jumps so far
    printf("Zooming in on cluster splits...\n"); mexEvalString("drawnow;");
    for (ilc=1; ilc<Nmc; ilc++) {  //for each of the i-th largest clusters
        //printf("  Looking for %d-largest cluster jumps (out of %d)...\n", ilc+1, Nmc);  ncf = 1;
        //mexEvalString("drawnow;");
        sortTemps(Teval, ei, SI); //get the order of Teval in SI
        i = 1;
        while ( Teval[SI[i]] < Tspa ) { //while we haven't reached the SPM->PM temp
            if ( ( *(MCS+Nmc*SI[i]+ilc) > *(MCS+Nmc*SI[i-1]+ilc) ) //if i-th largest cluster increased in size since last timestep
              && ( *(MCS+Nmc*SI[i]+ilc) > minClusSize ) // and it's not too small,
              && ( Teval[SI[i]]-Teval[SI[i-1]] > minTempStep ) ) { // and we haven't already zoomed in here
                // Then do a binary search for jump point between these two points!
                //printf("    Found total of %d, this one at T=%f\n", ncf++, Teval[SI[i]]);
                //mexEvalString("drawnow;");
                ta = Teval[SI[i-1]];  tb = Teval[SI[i]]; //bracket the jump point
                Sma = *(MCS+Nmc*SI[i-1]+ilc);
                Smb = *(MCS+Nmc*SI[i]+ilc);
                while ( tb-ta > minTempStep ) {
                    tc = (ta+tb)/2; //midpoint
                    *(Teval+ei) = tc; //evaluate at midpoint
                    THRESH_SUBGRAPHS_SIZES(Tb, maxCor, tc, Nmc, S, Ct+ei*n, MCS+ei*Nmc, MCI+ei*Nmc);
                    Smc = *(MCS+ei*Nmc+ilc); //store the max cluster size @ that temp
                    ei++;
                    if (ei >= init_temps) { //double array sizes if we need more space
                        doubleArraySizes(&Teval, &Ct, &MCS, &MCI, &init_temps, n, Nmc);
                    }
                    if (Sma < Smc && Smc > minClusSize) { //there is a jump between A and C and C is above size threshold
                        tb = tc; //set B to C
                        Smb = Smc;
                    } else { //jump point is between C and B
                        ta = tc;  //set A to C
                        Sma = Smc;
                    }
                }
                sortTemps(Teval, ei, SI); //get the order of Teval in SI
            }
            i++; //move on to next temp step
        }
    }
    printf("  Finished.\n"); mexEvalString("drawnow;");

    printf("\nRan %d evaluations total\n\n", ei); mexEvalString("drawnow;");


    // 10. Find the clusters which have jumped at each jump point, and hierarchical structure
    //printf("Determining hierarchical structure of clusters...\n");
    maxPosClusts = 200; //not gonna be more than that many clusters, right?
    *Nc = 0;
    *Cn = malloc(maxPosClusts*sizeof(nid_t)); //allocate list of cluster sizes
    *C = malloc(maxPosClusts*sizeof(nid_t *)); //allocate list of pointers to cluster id lists
    *P = malloc(maxPosClusts*sizeof(nid_t)); //allocate list of parent cluster ids
    Ch = malloc(maxPosClusts*sizeof(nid_t *)); //list of pointers to child list for each cluster
    for (p=0; p<maxPosClusts; p++) { //initialize to null
        Ch[p] = NULL;
    }
    ChN = malloc(maxPosClusts*sizeof(nid_t)); //number of children for each cluster
    for (p=0; p<maxPosClusts; p++) { //initialize to zero
        ChN[p] = 0;
    }
    llci = 0; //index of the temp of the last break from the largest clus
    hier_print = ei/5;

    for (i=1; i<ei; i++) { //for each evaluation,

        //if (i%hier_print==0) { //print progress occasionally
        //    printf("  %.1f percent complete\n", 100.0 * ((float) i) / ((float) ei));
        //}

        // If the gap is small enough, there may be a split here
        if ( Teval[SI[i]]-Teval[SI[i-1]] < 2*minTempStep ) { 
            nsplits = 0;
            for (j=0; j<Nmc; j++) { //for each of the i-th largest clusters

                // Find which cluster at the last tempstep was its parent
                plt = -1; //parent id at the last temperature
                for (jj=Nmc-1; jj>=0 && plt<0; jj--) {
                    if (isChild(j, i, jj, i-1, MCI, Nmc, SI, Ct, n)) { 
                        plt = jj;
                    }
                }

                // Was there a jump?
                tcs = *(MCS+Nmc*SI[i]+j); //this cluster's size at current temp
                if ((*(MCS+Nmc*SI[i-1]+plt)-tcs) > minClusSize && tcs>minClusSize) { //if there was a jump and this cluster is large enough to consider

                    // Make a new cluster of clus(j,i)
                    nsplits++; //count the number of clusters which split
                    newC = malloc(tcs*sizeof(nid_t)); //list of cluster IDs for the new cluster
                    (*C)[*Nc] = newC; //make corresponding element of C point to that list
                    (*Cn)[*Nc] = tcs; //store the size of the new cluster
                    cid2 = 0; //reset counter
                    for (cid=0; cid<n; cid++) { //for each point,
                        //if this point is in the new cluster
                        if ( *(Ct+n*SI[i]+cid) == *(MCI+Nmc*SI[i]+j) ) { 
                            newC[cid2++] = cid; //store the ids of each point in the cluster
                        }
                    }
                    (*Nc)++; //increment the number of clusters found
                    
                    // Find its parent in the list of existing clusters
                    p = parentSearch(newC, tcs, *C, *Cn, *P, *Nc-1); 
                    (*P)[*Nc-1] = p; //set element in P to the parent clus id of new clus 
                    
                    // Print info
                    //printf("At T=%f, cluster id=%d of size %d broke off from %d\n", Teval[SI[i]], *Nc-1, tcs, p);

                }
            }

            if (nsplits == 1) { //can't have just one! Need to have two which split off
                //so delete the most recently added cluster
                free(newC);
                (*Nc)--; //decrement the number of clusters found
                (*C)[*Nc] = NULL; //make corresponding element of C point to that list
                (*Cn)[*Nc] = -1; //store the size of the new cluster
            }
        }
    }
    //printf("  Finished.\n"); mexEvalString("drawnow;");


    // Done, clean up
    ALG_CLEAR(Tb);
    CLEAR_LIST(S);
    free(maxCor);
    free(Teval);
    free(Ct); 
    free(MCS);
    free(MCI);
    mexPrintf("Done.\n");

}
Ejemplo n.º 26
0
/**
 *	Pass the sample list through the CSG node.
 *	The sample list will contain only the relevant entry and exit points for
 *	the resulting surface for this operation, and they will be promoted to
 *	this node for further processing up the tree.
 *
 *	@param	samples	Array of samples to process.
 */
void CqCSGTreeNode::ProcessSampleList( std::vector<SqImageSample>& samples )
{
	// First process any children nodes.
	// Process all nodes depth first.
	std::list<boost::weak_ptr<CqCSGTreeNode> >::const_iterator
	ii = lChildren().begin(), ie = lChildren().end();
	for (; ii != ie; ++ii)
	{
		// If the node is a primitive, no need to process it.
		// In fact as the primitive, just nulls out its owned samples
		// this would break the CSG code.
		boost::shared_ptr<CqCSGTreeNode> pChild = ii->lock()
		        ;
		if ( pChild.get() && pChild->NodeType() != CSGNodeType_Primitive )
			pChild->ProcessSampleList( samples );
	}

	std::vector<bool> abChildState( cChildren() );
	std::vector<TqInt> aChildIndex( samples.size() );
	TqInt iChild;
	for ( iChild = 0; iChild < cChildren(); iChild++ )
		abChildState[ iChild ] = false;

	// Now get the initial state
	bool bCurrentI = false;

	// Find out if the camera is starting inside a solid. This is the case if you
	// see an odd number of walls for that solid when looking out.
	std::vector<SqImageSample>::iterator i;
	TqInt j = 0;
	for ( i = samples.begin(); i != samples.end(); ++i, ++j )
	{
		if ( ( aChildIndex[j] = isChild( i->csgNode.get() ) ) >= 0 )
		{
			if ( ((i->csgNode.get())->NodeType() == CSGNodeType_Primitive ) &&
			        ((i->csgNode.get())->NodeType() == CSGNodeType_Union ) )
			{
				abChildState[ aChildIndex[j] ] = !abChildState[ aChildIndex[j] ];
			}
		}
	}

	bCurrentI = EvaluateState( abChildState );

	// Now go through samples, clearing any where the state doesn't change, and
	// promoting any where it does to this node.
	for ( i = samples.begin(), j = 0; i != samples.end(); ++j )
	{
		// Find out if sample is in out children nodes, if so are we entering or leaving.
		if ( aChildIndex[j] >= 0 )
			abChildState[ aChildIndex[j] ] = !abChildState[ aChildIndex[j] ];
		else
		{
			++i;
			continue;
		}

		// Work out the new state
		bool bNewI = EvaluateState( abChildState );

		// If it hasn't changed, remove the sample.
		if ( bNewI == bCurrentI )
			i = samples.erase( i );
		else
			// Otherwise promote it to this node unless we are a the top.
		{
			bCurrentI = bNewI;
			if ( pParent() )
			{
				i->csgNode = shared_from_this();
			}
			else
			{
				i->csgNode = boost::shared_ptr<CqCSGTreeNode>();
			}
			i++;
		}
	}
}
Ejemplo n.º 27
0
int main()
{
    int i, j, k; /* for loop */
    char name1[maxLenName], name2[maxLenName]; /* input */
    char nameSet[maxNumName][maxLenName];
    int numName = 0;
    int parent[maxNumName], child[maxNumName];
    int check1, check2;
    int result;

    /* freopen("input.txt", "r", stdin); */

    memset(parent, -1, sizeof(parent));

    while(scanf("%s %s", name1, name2) == 2)
    {
        if(!strcmp(name1, "no.child"))
        {
            break;
        }
        check1 = check2 = 0;
        for(i=0;i<numName;i++)
        {
            if(!strcmp(nameSet[i], name1))
            {
                check1 = 1;
                break;
            }
        }
        for(j=0;j<numName;j++)
        {
            if(!strcmp(nameSet[j], name2))
            {
                check2 = 1;
                break;
            }
        }
        if(check1 == 0)
        {
            strcpy(nameSet[numName],name1);
            i = numName;
            numName++;
        }
        if(check2 == 0)
        {
            strcpy(nameSet[numName],name2);
            j = numName;
            numName++;
        }
        parent[i] = j;
        child[j] = i;
    }

    while(scanf("%s %s", name1, name2) == 2)
    {
        /* search index of array of the name */
        for(i=0;i<numName;i++)
        {
            if(!strcmp(nameSet[i], name1))
            {
                break;
            }
        }
        for(j=0;j<numName;j++)
        {
            if(!strcmp(nameSet[j], name2))
            {
                break;
            }
        }

        result = isChild(parent, numName, i, j);
        if(result != 0)
        {
            if(result == 1)
            {
                printf("child\n");
            }
            else
            {
                for(i=2;i<result;i++)
                {
                    printf("great ");
                }
                printf("grand child\n");
            }
            continue;
        }

        result = isParent(parent, numName, i, j);
        if(result != 0)
        {
            if(result == 1)
            {
                printf("parent\n");
            }
            else
            {
                for(i=2;i<result;i++)
                {
                    printf("great ");
                }
                printf("grand parent\n");
            }
            continue;
        }

        result = isSibling(parent, numName, i, j);
        if(result == 1)
        {
            printf("sibling\n");
            continue;
        }

        /* check if cousin relation, and use i, j variable to return m, n-ancestor relationship */
        result = isCousin(parent, numName, &i, &j);
        if(result == 1)
        {
            if(i == j)
            {
                printf("%d cousin\n", i);
            }
            else if(i < j)
            {
                printf("%d cousin removed %d\n", i, j-i);
            }
            else
            {
                printf("%d cousin removed %d\n", j, i-j);
            }
            continue;
        }

        /* None of the above */
        printf("no relation\n");
    }

    return 0;
}
Ejemplo n.º 28
0
/**
* Clean up when the real algorithm stops
*/
void AlgorithmProxy::stopped() {
    if (!isChild())
        dropWorkspaceReferences();
    m_isExecuted = m_alg->isExecuted();
    m_alg.reset();
}