Example #1
0
void CGfxPopupMenu::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
//	CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
//	CRect rcItem(lpDrawItemStruct->rcItem);
//	pDC->FillSolidRect(rcItem, RGB(255,0,0));
	if (lpDrawItemStruct->CtlType == ODT_MENU)
	{
		UINT id = lpDrawItemStruct->itemID;
		UINT state = lpDrawItemStruct->itemState;
		bool bEnab = !(state & ODS_DISABLED);
		bool bSelect = (state & ODS_SELECTED) ? true : false;
		bool bChecked = (state & ODS_CHECKED) ? true : false;
		// David 08/04/98 - start - bold font handling
		bool bBold = (state & ODS_DEFAULT) ? true : false;
		// David 08/04/98 - end - bold font handling

		SpawnItem * pItem = (SpawnItem *) lpDrawItemStruct->itemData;
		if (pItem)
		{
			CDC * pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
			CFont * pft;
			// David 08/04/98 - start - bold font handling
			if (!bBold) pft = CFont::FromHandle((HFONT) hMenuFont ? hMenuFont : hGuiFont);
			else pft = CFont::FromHandle((HFONT) hMenuBoldFont ? hMenuBoldFont : hGuiFont);
			// David 08/04/98 - end - bold font handling
			CFont * of = pDC->SelectObject(pft);

			CRect rc(lpDrawItemStruct->rcItem);
			CRect rcImage(rc), rcText(rc);
			rcImage.right = rcImage.left + rc.Height();
			rcImage.bottom = rc.bottom;

			if (pItem->iCmd == -3) // is a separator
			{
				CPen pnDk(PS_SOLID,1,cr3dShadow);
				CPen pnLt(PS_SOLID,1,cr3dHilight);
				CPen * opn = pDC->SelectObject(&pnDk);
				pDC->MoveTo(rc.left + 2, rc.top + 2);
				pDC->LineTo(rc.right - 2, rc.top + 2);
				pDC->SelectObject(&pnLt);
				pDC->MoveTo(rc.left + 2, rc.top + 3);
				pDC->LineTo(rc.right - 2, rc.top + 3);
				pDC->SelectObject(opn);
			}
			else if (pItem->iCmd == -4) // is a title item
			{
				CString cs(pItem->cText), cs1;
				CRect rcBdr(rcText);

				if (bSelect && bEnab)
				{
					rcText.top ++;
					rcText.left += 2;
				}
				pDC->FillSolidRect(rcText, crMenu);
				pDC->DrawText(cs, rcText, DT_VCENTER|DT_CENTER|DT_SINGLELINE);
				if (bSelect && bEnab) pDC->Draw3dRect(rcBdr,cr3dShadow,cr3dHilight);
			}
			else
			{
				rcText.left += rcImage.right + 1;

				int obk = pDC->SetBkMode(TRANSPARENT);
				
				COLORREF ocr;
				if (bSelect)
				{
					if (pItem->iImageIdx >= 0 || (state & ODS_CHECKED))
						pDC->FillSolidRect(rcText, crHighlight);
					else
						pDC->FillSolidRect(rc, crHighlight);

					ocr = pDC->SetTextColor(crMenuTextSel);
				}
				else
				{
					if (pItem->iImageIdx >= 0 || (state & ODS_CHECKED))
						pDC->FillSolidRect(rcText, crMenu);
					else
						pDC->FillSolidRect(rc/*rcText*/, crMenu);
					ocr = pDC->SetTextColor(crMenuText);
				}

				if (pItem->iImageIdx >= 0)
				{
					int ay = (rcImage.Height() - szImage.cy) / 2;
					int ax = (rcImage.Width()  - szImage.cx) / 2;

					if (bSelect && bEnab)
						pDC->Draw3dRect(rcImage,cr3dHilight,cr3dShadow);
					else
					{
						pDC->Draw3dRect(rcImage,crMenu,crMenu);
					}


					if (bEnab)
					{
						ilList.Draw(pDC, pItem->iImageIdx, CPoint(rcImage.left + ax, rcImage.top +ay), ILD_NORMAL);
					}
					else
					{
						HICON hIcon = ilList.ExtractIcon( pItem->iImageIdx );
						pDC->DrawState( CPoint(rcImage.left + ax, rcImage.top + ay ), szImage, (HICON)hIcon, DST_ICON | DSS_DISABLED, (CBrush *)NULL );
					}
				}
				else
				{
					if (bChecked)
					{
						int ay = (rcImage.Height() - szImage.cy) / 2;
						int ax = (rcImage.Width()  - szImage.cx) / 2;

						ilOther.Draw(pDC, 0, CPoint(rcImage.left + ax, rcImage.top + ay - 2), ILD_NORMAL);
					}
				}

				CString cs(pItem->cText), cs1;
				CSize sz;
				sz = pDC->GetTextExtent(cs);
				int ay1 = (rcText.Height() - sz.cy) / 2;
				rcText.top += ay1;
				rcText.left += 2;
				rcText.right -= 15;

				int tf = cs.Find('\t');
				if (tf >= 0)
				{
					cs1 = cs.Right(cs.GetLength() - tf - 1);
					cs = cs.Left(tf);
					if (!bEnab)
					{
						if (!bSelect)
						{
							CRect rcText1(rcText);
							rcText1.InflateRect(-1,-1);
							pDC->SetTextColor(cr3dHilight);
							pDC->DrawText(cs, rcText1, DT_VCENTER|DT_LEFT);
							pDC->DrawText(cs1, rcText1, DT_VCENTER|DT_RIGHT);
							pDC->SetTextColor(crGrayText);
							pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT);
							pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT);
						}
						else
						{
							pDC->SetTextColor(crMenu);
							pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT);
							pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT);
						}
					}
					else
					{
						pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT);
						pDC->DrawText(cs1, rcText, DT_VCENTER|DT_RIGHT);
					}
				}
				else 
				{
					if (!bEnab)
					{
						if (!bSelect)
						{
							CRect rcText1(rcText);
							rcText1.InflateRect(-1,-1);
							pDC->SetTextColor(cr3dHilight);
							pDC->DrawText(cs, rcText1, DT_VCENTER|DT_LEFT|DT_EXPANDTABS);
							pDC->SetTextColor(crGrayText);
							pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS);
						}
						else
						{
							pDC->SetTextColor(crMenu);
							pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS);
						}
					}
					else
						pDC->DrawText(cs, rcText, DT_VCENTER|DT_LEFT|DT_EXPANDTABS);
				}
				pDC->SetTextColor(ocr);
				pDC->SetBkMode(obk);
			}

			pDC->SelectObject(of);
		}
	}
}
Example #2
0
/**
 * For a given query, get a runner.
 */
Status getRunner(Collection* collection,
                 CanonicalQuery* rawCanonicalQuery,
                 Runner** out,
                 size_t plannerOptions) {

    verify(rawCanonicalQuery);
    auto_ptr<CanonicalQuery> canonicalQuery(rawCanonicalQuery);

    // This can happen as we're called by internal clients as well.
    if (NULL == collection) {
        const string& ns = canonicalQuery->ns();
        LOG(2) << "Collection " << ns << " does not exist."
               << " Using EOF runner: " << canonicalQuery->toStringShort();
        *out = new EOFRunner(canonicalQuery.release(), ns);
        return Status::OK();
    }

    // If we have an _id index we can use the idhack runner.
    if (IDHackRunner::supportsQuery(*canonicalQuery) &&
            collection->getIndexCatalog()->findIdIndex()) {
        LOG(2) << "Using idhack: " << canonicalQuery->toStringShort();
        *out = new IDHackRunner(collection, canonicalQuery.release());
        return Status::OK();
    }

    // Tailable: If the query requests tailable the collection must be capped.
    if (canonicalQuery->getParsed().hasOption(QueryOption_CursorTailable)) {
        if (!collection->isCapped()) {
            return Status(ErrorCodes::BadValue,
                          "error processing query: " + canonicalQuery->toString() +
                          " tailable cursor requested on non capped collection");
        }

        // If a sort is specified it must be equal to expectedSort.
        const BSONObj expectedSort = BSON("$natural" << 1);
        const BSONObj& actualSort = canonicalQuery->getParsed().getSort();
        if (!actualSort.isEmpty() && !(actualSort == expectedSort)) {
            return Status(ErrorCodes::BadValue,
                          "error processing query: " + canonicalQuery->toString() +
                          " invalid sort specified for tailable cursor: "
                          + actualSort.toString());
        }
    }

    // Fill out the planning params.  We use these for both cached solutions and non-cached.
    QueryPlannerParams plannerParams;
    plannerParams.options = plannerOptions;
    fillOutPlannerParams(collection, rawCanonicalQuery, &plannerParams);

    // Try to look up a cached solution for the query.

    CachedSolution* rawCS;
    if (PlanCache::shouldCacheQuery(*canonicalQuery) &&
            collection->infoCache()->getPlanCache()->get(*canonicalQuery, &rawCS).isOK()) {
        // We have a CachedSolution.  Have the planner turn it into a QuerySolution.
        boost::scoped_ptr<CachedSolution> cs(rawCS);
        QuerySolution *qs, *backupQs;
        QuerySolution*& chosenSolution=qs; // either qs or backupQs
        Status status = QueryPlanner::planFromCache(*canonicalQuery, plannerParams, *cs,
                        &qs, &backupQs);

        if (status.isOK()) {
            // the working set will be shared by the root and backupRoot plans
            // and owned by the containing single-solution-runner
            //
            WorkingSet* sharedWs = new WorkingSet();

            PlanStage *root, *backupRoot=NULL;
            verify(StageBuilder::build(collection, *qs, sharedWs, &root));
            if ((plannerParams.options & QueryPlannerParams::PRIVATE_IS_COUNT)
                    && turnIxscanIntoCount(qs)) {
                LOG(2) << "Using fast count: " << canonicalQuery->toStringShort()
                       << ", planSummary: " << getPlanSummary(*qs);

                if (NULL != backupQs) {
                    delete backupQs;
                }
            }
            else if (NULL != backupQs) {
                verify(StageBuilder::build(collection, *backupQs, sharedWs, &backupRoot));
            }

            // add a CachedPlanStage on top of the previous root
            root = new CachedPlanStage(collection, rawCanonicalQuery, root, backupRoot);

            *out = new SingleSolutionRunner(collection,
                                            canonicalQuery.release(),
                                            chosenSolution, root, sharedWs);
            return Status::OK();
        }
    }

    if (internalQueryPlanOrChildrenIndependently
            && SubplanRunner::canUseSubplanRunner(*canonicalQuery)) {

        QLOG() << "Running query as sub-queries: " << canonicalQuery->toStringShort();
        LOG(2) << "Running query as sub-queries: " << canonicalQuery->toStringShort();

        SubplanRunner* runner;
        Status runnerStatus = SubplanRunner::make(collection, plannerParams,
                              canonicalQuery.release(), &runner);
        if (!runnerStatus.isOK()) {
            return runnerStatus;
        }

        *out = runner;
        return Status::OK();
    }

    return getRunnerAlwaysPlan(collection, canonicalQuery.release(), plannerParams, out);
}
Example #3
0
 int Lock() {
    CriticalSection cs(&_mutex);
    int old = _u._a._lock;
    _u._a._lock = 1; 
    return old;
 }
Example #4
0
CNode* VariableEliminator::eliminate_var_conjunct(CNode* node, VariableTerm* evar)
{

	if(DEBUG) {
		cout << "IN ELIMINATE VAR FROM CONJUNCT " << node->to_string()<< endl;
		cout << "Trying to eliminate: " << evar->to_string() <<endl;
	}

	int initial_count = fresh_var_counter;
	assert(node->is_conjunct());


	Clause cl(node);
	map<Term*, Term*> denestings;
	cl.denest( &denestings);



	if(DEBUG) {
		cout << "DENESTINGS: " << endl;
		map<Term*, Term*>::iterator it = denestings.begin();
		for(; it!= denestings.end(); it++)
		{
			cout << "\t " << it->first->to_string() <<
			"-> " << it->second->to_string() << endl;
		}
	}


	ClauseSolve cs(&cl, NULL);
	bool res = cs.is_sat();



	/*
	 * If the clause is UNSAT, the SNC is false.
	 * We call sat to ensure that all relevant interactions
	 * are propagated between the ILP and EQ domains. After calling
	 * sat, eq_members, var_to_cols etc are properly initialized.
	 */
	if(!res){
		return False::make();
	}

	Term* rep = cs.find_representative(evar);



	Term* valid_rep = NULL;
	if(rep!=NULL && !rep->contains_term(evar) && denestings.count(rep)==0) {
		valid_rep = rep;
	}
	else {
		set<Term*>& eq_class = cs.eq_members[rep];
		set<Term*>::iterator it = eq_class.begin();
		for(; it!= eq_class.end(); it++) {
			Term* cur_t = *it;
			if(!cur_t->contains_term(evar)&&denestings.count(cur_t)==0){
				valid_rep = cur_t;
				break;
			}
		}
	}


	/*
	 * We found one member in the equivalence class of this variable
	 * that does not contain that variable.
	 */
	if(valid_rep != NULL) {
		map<Term*, Term*> subs;
		subs[evar] = valid_rep;
		CNode* res = node->substitute(subs);
		node = node->substitute(denestings);
		return res;
	}


	set<FunctionTerm*> direct_parents;
	get_direct_parents(evar, direct_parents, cs.eq_members);

	if(!over_approximate) {
			if(direct_parents.size() > 0) return False::make();
		}


	/*
	 * Base case: If this term does not contain any parent terms,
	 * eliminate it from the ILP domain
	 */
	if(direct_parents.size() == 0 && cs.ilp_vars.count(evar->get_var_id()) > 0 ){
		set<CNode*> mod_constraints;
		if(DEBUG) {
			cout << "ELIMINATING FROM ILP: " << cl.to_string("&") << endl;
		}
		CNode* res= eliminate_var_from_ilp_domain(cl, evar, mod_constraints);
		if(DEBUG) {
			cout << "AFTER ELIMINATING FROM ILP: " << res->to_string() << endl;
		}
		res = eliminate_denestings(res, denestings, evar, initial_count, false);
		return res;
	}
	else if(direct_parents.size() == 0)
	{
		CNode* res = remove_eq_var_with_no_parents(cl, evar);
		return eliminate_denestings(res, denestings, evar, initial_count,
				false);
	}




	/*
	 * We want to replace each function term in which the variable appears with
	 * a fresh term u, u' etc. and then introduce conditional equality
	 * constraints.
	 * For example, if we have f(x, a) = f(x, b), introduce a=b->u1=u2
	 * where u1 and u2 are the replacements for f(x,a) and f(x,b) respectively.
	 */
	map<VariableTerm*, FunctionTerm*> fresh_vars_to_functions;
	map<FunctionTerm*, VariableTerm*> functions_to_fresh_vars;




	/*
	 * A map from function id's (e.g. f) to all the function terms containing x
	 * as an argument to this function id.
	 */
	map<int, set<FunctionTerm*> > function_id_to_functions;

	{
		introduce_fresh_vars_for_function_terms(cl, evar, direct_parents,
				fresh_vars_to_functions, functions_to_fresh_vars,
				function_id_to_functions);


		if(DEBUG) {
			cout << "FUNCTION ID TO FUNCTIONS: " << endl;
			map<int, set<FunctionTerm*> >::iterator it2 = function_id_to_functions.begin();
			for(; it2 != function_id_to_functions.end(); it2++){
				cout << "Function: " << CNode::get_varmap().get_name(it2->first);
				set<FunctionTerm*>::iterator it3 = it2->second.begin();
				for(; it3!= it2->second.end(); it3++) {
					cout << "\t " << (*it3)->to_string() << endl;
				}
			}
		}
	}



	/*
	 * Introduce conditional equalities
	 * First, introduce conditional equalities between u terms
	 */
	map<CNode*, CNode*> conditional_equalities;
	map<int, set<FunctionTerm*> >::iterator it = function_id_to_functions.begin();
	for(; it!= function_id_to_functions.end(); it++) {
		set<FunctionTerm*>& s1 = it->second;
		set<FunctionTerm*>::iterator it2 = s1.begin();


		for(; it2!= s1.end(); it2++) {
			FunctionTerm* ft1 = *it2;
			set<FunctionTerm*>::iterator it3 = it2;
			it3++;
			for(; it3 != s1.end(); it3++) {
				set<CNode*> ops;
				FunctionTerm* ft2 = *it3;
				assert(ft1->get_args().size()  == ft2->get_args().size());
				for(unsigned int i=0; i< ft1->get_args().size(); i++)
				{
					Term* cur_arg1 = ft1->get_args()[i];
					Term* cur_arg2 = ft2->get_args()[i];
					if(cur_arg1 == evar && cur_arg2 == evar) continue;
					if(cur_arg1 == evar || cur_arg2 == evar) {
						if(cs.ilp_vars.count(evar->get_var_id()) == 0) continue;
					}


					CNode* eq = EqLeaf::make(cur_arg1, cur_arg2);
					ops.insert(eq);
				}
				if(ops.size() == 0) continue;
				CNode* precedent = Connective::make_and(ops);
				assert(functions_to_fresh_vars.count(ft1) > 0);
				assert(functions_to_fresh_vars.count(ft2) > 0);
				VariableTerm* fresh1 = functions_to_fresh_vars[ft1];
				VariableTerm* fresh2 = functions_to_fresh_vars[ft2];
				CNode* antecedent = EqLeaf::make(fresh1, fresh2);
				conditional_equalities[precedent] = antecedent;

			}
		}
	}


	/*
	 * If the variable to be eliminated is a shared variable, also need to
	 * add conditional equalities with non-u terms.
	 */
	 if(cs.ilp_vars.count(evar->get_var_id()) > 0) {
		 map<int, set<FunctionTerm*> > functions_in_clause;
		 get_function_terms_in_clause(cl, functions_in_clause);
		 it = function_id_to_functions.begin();
		 for(; it!= function_id_to_functions.end(); it++) {
			 set<FunctionTerm*>& evar_terms = it->second;
			 if(functions_in_clause.count(it->first)==0) continue;
			 set<FunctionTerm*>& clause_terms = functions_in_clause[it->first];
			 set<FunctionTerm*>::iterator it2 = evar_terms.begin();
			 for(; it2 != evar_terms.end(); it2++) {
				 FunctionTerm* ft1 = *it2;
				 set<FunctionTerm*>::iterator it3 = clause_terms.begin();
				 for(; it3 != clause_terms.end(); it3++) {
					set<CNode*> ops;
					FunctionTerm* ft2 = *it3;
					assert(ft1->get_args().size()  == ft2->get_args().size());
					for(unsigned int i=0; i< ft1->get_args().size(); i++)
					{
						Term* cur_arg1 = ft1->get_args()[i];
						Term* cur_arg2 = ft2->get_args()[i];
						CNode* eq = EqLeaf::make(cur_arg1, cur_arg2);
						ops.insert(eq);
					}
					if(ops.size() == 0) continue;
					CNode* precedent = Connective::make_and(ops);
					assert(functions_to_fresh_vars.count(ft1) > 0);
					VariableTerm* fresh1 = functions_to_fresh_vars[ft1];
					CNode* antecedent = EqLeaf::make(fresh1, ft2);
					conditional_equalities[precedent] = antecedent;

				}

			 }

		 }
	 }


	if(DEBUG)
	{
		cout << "CONDITIONAL EQUALITIES: " << endl;
		map<CNode*, CNode*>::iterator it = conditional_equalities.begin();
		for(; it!= conditional_equalities.end(); it++) {
			CNode* precedent = it->first;
			CNode* antecedent = it->second;
			cout << precedent->to_string() << " => " << antecedent->to_string()
				<< endl;
		}
	}


	/*
	 * Make the new formula anded with the conditional constraints
	 */
	set<CNode*> new_ops;
	CNode* original = cl.to_cnode();
	new_ops.insert(original);
	map<CNode*, CNode*>::iterator cond_it = conditional_equalities.begin();
	for(; cond_it != conditional_equalities.end(); cond_it++)
	{
		CNode* cur_cond = Connective::make_implies(cond_it->first,
				cond_it->second);
		new_ops.insert(cur_cond);
	}
	CNode* new_node = Connective::make_and(new_ops);


	new_node = eliminate_denestings(new_node, denestings, evar, initial_count,
			true);
	return new_node;
}
Example #5
0
/*!
	\brief Sets all the cursors from a specified CursorSet
	\param path Path to the cursor set
	
	All cursors in the set will be assigned. If the set does not specify a cursor for a
	particular cursor specifier, it will remain unchanged. This function will fail if passed
	a NULL path, an invalid path, or the path to a non-CursorSet file.
*/
void CursorManager::SetCursorSet(const char *path)
{
	Lock();
	CursorSet cs(NULL);
	
	if(!path || cs.Load(path)!=B_OK)
		return;
	ServerCursor *csr;
	
	if(cs.FindCursor(B_CURSOR_DEFAULT,&csr)==B_OK)
	{
		if(fDefaultCursor)
			delete fDefaultCursor;
		fDefaultCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_TEXT,&csr)==B_OK)
	{
		if(fTextCursor)
			delete fTextCursor;
		fTextCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_MOVE,&csr)==B_OK)
	{
		if(fMoveCursor)
			delete fMoveCursor;
		fMoveCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_DRAG,&csr)==B_OK)
	{
		if(fDragCursor)
			delete fDragCursor;
		fDragCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_RESIZE,&csr)==B_OK)
	{
		if(fResizeCursor)
			delete fResizeCursor;
		fResizeCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_RESIZE_NWSE,&csr)==B_OK)
	{
		if(fNWSECursor)
			delete fNWSECursor;
		fNWSECursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_RESIZE_NESW,&csr)==B_OK)
	{
		if(fNESWCursor)
			delete fNESWCursor;
		fNESWCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_RESIZE_NS,&csr)==B_OK)
	{
		if(fNSCursor)
			delete fNSCursor;
		fNSCursor=csr;
	}
	
	if(cs.FindCursor(B_CURSOR_RESIZE_EW,&csr)==B_OK)
	{
		if(fEWCursor)
			delete fEWCursor;
		fEWCursor=csr;
	}
	Unlock();
	
}
Example #6
0
unsigned long CSysSolve::FGMRES(const CSysVector & b, CSysVector & x, CMatrixVectorProduct & mat_vec,
                               CPreconditioner & precond, double tol, unsigned long m, bool monitoring) {
	
int rank = 0;

#ifndef NO_MPI
#ifdef WINDOWS
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
	rank = MPI::COMM_WORLD.Get_rank();
#endif
#endif
  
  /*---  Check the subspace size ---*/
  if (m < 1) {
    if (rank == 0) cerr << "CSysSolve::FGMRES: illegal value for subspace size, m = " << m << endl;
#ifdef NO_MPI
    exit(1);
#else
#ifdef WINDOWS
	MPI_Abort(MPI_COMM_WORLD,1);
    MPI_Finalize();
#else
    MPI::COMM_WORLD.Abort(1);
    MPI::Finalize();
#endif
#endif
  }

  /*---  Check the subspace size ---*/
  if (m > 1000) {
    if (rank == 0) cerr << "CSysSolve::FGMRES: illegal value for subspace size (too high), m = " << m << endl;
#ifdef NO_MPI
    exit(1);
#else
#ifdef WINDOWS
	MPI_Abort(MPI_COMM_WORLD,1);
    MPI_Finalize();
#else
    MPI::COMM_WORLD.Abort(1);
    MPI::Finalize();
#endif
#endif
  }
  
  /*---  Define various arrays
	 Note: elements in w and z are initialized to x to avoid creating
	 a temporary CSysVector object for the copy constructor ---*/
  vector<CSysVector> w(m+1, x);
  vector<CSysVector> z(m+1, x);
  vector<double> g(m+1, 0.0);
  vector<double> sn(m+1, 0.0);
  vector<double> cs(m+1, 0.0);
  vector<double> y(m, 0.0);
  vector<vector<double> > H(m+1, vector<double>(m, 0.0));
  
  /*---  Calculate the norm of the rhs vector ---*/
  double norm0 = b.norm();
  
  /*---  Calculate the initial residual (actually the negative residual)
	 and compute its norm ---*/
  mat_vec(x,w[0]);
  w[0] -= b;
  
  double beta = w[0].norm();
  
  if ( (beta < tol*norm0) || (beta < eps) ) {
    /*---  System is already solved ---*/
    if (rank == 0) cout << "CSysSolve::FGMRES(): system solved by initial guess." << endl;
    return 0;
  }
  
  /*---  Normalize residual to get w_{0} (the negative sign is because w[0]
	 holds the negative residual, as mentioned above) ---*/
  w[0] /= -beta;
  
  /*---  Initialize the RHS of the reduced system ---*/
  g[0] = beta;
  
  /*--- Set the norm to the initial initial residual value ---*/
  norm0 = beta;

  /*---  Output header information including initial residual ---*/
  int i = 0;
  if ((monitoring) && (rank == 0)) {
    writeHeader("FGMRES", tol, beta);
    writeHistory(i, beta, norm0);
  }
  
  /*---  Loop over all serach directions ---*/
  for (i = 0; i < m; i++) {
    
    /*---  Check if solution has converged ---*/
    if (beta < tol*norm0) break;
    
    /*---  Precondition the CSysVector w[i] and store result in z[i] ---*/
    precond(w[i], z[i]);
    
    /*---  Add to Krylov subspace ---*/
    mat_vec(z[i], w[i+1]);
    
    /*---  Modified Gram-Schmidt orthogonalization ---*/
    modGramSchmidt(i, H, w);
    
    /*---  Apply old Givens rotations to new column of the Hessenberg matrix
		 then generate the new Givens rotation matrix and apply it to
		 the last two elements of H[:][i] and g ---*/
    for (int k = 0; k < i; k++)
      applyGivens(sn[k], cs[k], H[k][i], H[k+1][i]);
    generateGivens(H[i][i], H[i+1][i], sn[i], cs[i]);
    applyGivens(sn[i], cs[i], g[i], g[i+1]);
    
    /*---  Set L2 norm of residual and check if solution has converged ---*/
    beta = fabs(g[i+1]);
    
    /*---  Output the relative residual if necessary ---*/
    if ((((monitoring) && (rank == 0)) && ((i+1) % 100 == 0)) && (rank == 0)) writeHistory(i+1, beta, norm0);
  }

  /*---  Solve the least-squares system and update solution ---*/
  solveReduced(i, H, g, y);
  for (int k = 0; k < i; k++) {
    x.Plus_AX(y[k], z[k]);
  }
  
  if ((monitoring) && (rank == 0)) {
    cout << "# FGMRES final (true) residual:" << endl;
    cout << "# Iteration = " << i << ": |res|/|res0| = " << beta/norm0 << endl;
  }
  
//  /*---  Recalculate final (neg.) residual (this should be optional) ---*/
//  mat_vec(x, w[0]);
//  w[0] -= b;
//  double res = w[0].norm();
//  
//  if (fabs(res - beta) > tol*10) {
//    if (rank == 0) {
//      cout << "# WARNING in CSysSolve::FGMRES(): " << endl;
//      cout << "# true residual norm and calculated residual norm do not agree." << endl;
//      cout << "# res - beta = " << res - beta << endl;
//    }
//  }
	
	return i;
  
}
void CQuotesProviderBase::Run()
{
	CQuotesProviderVisitorDbSettings visitor;
	Accept(visitor);

	DWORD nTimeout = get_refresh_timeout_miliseconds(visitor);
	m_sContactListFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbDisplayNameFormat,visitor.m_pszDefDisplayFormat);
	m_sStatusMsgFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbStatusMsgFormat,visitor.m_pszDefStatusMsgFormat);
	m_sTendencyFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbTendencyFormat,visitor.m_pszDefTendencyFormat);

	enum{
		STOP_THREAD = 0,
		SETTINGS_CHANGED = 1,
		REFRESH_CONTACT = 2,
		COUNT_SYNC_OBJECTS = 3
	};

	HANDLE anEvents[COUNT_SYNC_OBJECTS];
	anEvents[STOP_THREAD] = g_hEventWorkThreadStop;
	anEvents[SETTINGS_CHANGED] = m_hEventSettingsChanged;
	anEvents[REFRESH_CONTACT] = m_hEventRefreshContact;

	TContracts anContacts;
	{
		CGuard<CLightMutex> cs(m_cs);
		anContacts = m_aContacts;
	}

	bool bGoToBed = false;

	while(false == bGoToBed)
	{		
		{
			CBoolGuard bg(m_bRefreshInProgress);
// 			LogIt(Info,_T("Begin contacts refreshing"));
			RefreshQuotes(anContacts);
// 			LogIt(Info,_T("End contacts refreshing"));
		}
		anContacts.clear();

		DWORD dwBegin = ::GetTickCount();
		DWORD dwResult = ::WaitForMultipleObjects(COUNT_SYNC_OBJECTS,anEvents,FALSE,nTimeout);
		switch(dwResult)
		{
		case WAIT_FAILED:
			assert(!"WaitForMultipleObjects failed");
			bGoToBed = true;
			break;
		case WAIT_ABANDONED_0+STOP_THREAD:
		case WAIT_ABANDONED_0+SETTINGS_CHANGED:
		case WAIT_ABANDONED_0+REFRESH_CONTACT:
			assert(!"WaitForMultipleObjects abandoned");
		case WAIT_OBJECT_0+STOP_THREAD:
			bGoToBed = true;
			break;
		case WAIT_OBJECT_0+SETTINGS_CHANGED:
			nTimeout = get_refresh_timeout_miliseconds(visitor);
			m_sContactListFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbDisplayNameFormat,visitor.m_pszDefDisplayFormat);
			m_sStatusMsgFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbStatusMsgFormat,visitor.m_pszDefStatusMsgFormat);
			m_sTendencyFormat = Quotes_DBGetStringT(NULL,QUOTES_PROTOCOL_NAME,visitor.m_pszDbTendencyFormat,visitor.m_pszDefTendencyFormat);

			{
				CGuard<CLightMutex> cs(m_cs);
				anContacts = m_aContacts;
			}
			break;
		case WAIT_OBJECT_0+REFRESH_CONTACT:
			{
				DWORD dwTimeRest = ::GetTickCount()-dwBegin;
				if(dwTimeRest < nTimeout)
					nTimeout -= dwTimeRest;

				CGuard<CLightMutex> cs(m_cs);
				anContacts = m_aRefreshingContacts;
				m_aRefreshingContacts.clear();
			}
			break;
		case WAIT_TIMEOUT:
			nTimeout = get_refresh_timeout_miliseconds(visitor);
			{
				CGuard<CLightMutex> cs(m_cs);
				anContacts = m_aContacts;
			}
			break;
		default:
			assert(!"What is the hell?");
		}
	}

	OnEndRun();
}
		int operator()(void) const
		{
			os::CriticalSection cs("OGLplus example");
			Application::ParseCommandLineOptions(argc, argv);
			return main_func(argc, argv);
		}
void LinkLocal::Stream::processNext()
{
	while(1) {
//		printf("################# %s\n", (proto->c2c_local) ? "Client" : "Server" );
		bool ok = proto->processStep();
		if(!ok && proto->need!=CoreProtocol::NSASLMechs && state!=WaitTLS) {
//			printf("pased: %d\n", ok ? 1 : 0);
			int need = proto->need;
//			printf("need: %d\n", need);
			if(need == CoreProtocol::NSASLMechs) {
				QStringList list;
				proto->setSASLMechList(list);
				return;
			}

			if(!in.isEmpty()) {
// 				printf("in not empty\n");
				QTimer::singleShot(0, this, SLOT(doReadyRead()));
			}

		return;
		}

		int event = proto->event;
// 		printf("event: %d\n", event);
		switch(event) {
			case CoreProtocol::EError: {
// 				printf("Error! Code=%d\n", proto->errorCode);
//				handleError();
				return;
			}
			case CoreProtocol::ESend: {
				QByteArray a = proto->takeOutgoingData();
				QByteArray cs(a.size()+1,'\0');
				memcpy(cs.data(), a.data(), a.size());
// 				printf("Need Send: {%s}\n", cs.data());
				bs_->write(a);
				break;
			}
			case CoreProtocol::ERecvOpen: {
// 				printf("Break (RecvOpen)\n");
				if(proto->old) {
					state = WaitVersion;
// 					printf("WarnOldVersion\n");
					return;
				}
				break;
			}
			case CoreProtocol::EFeatures: {
// 				printf("Break (Features)\n");
				if(state == WaitTLS)
					state = Active;
				else
					state = WaitTLS;
				break;
			}
			case CoreProtocol::ESASLSuccess: {
// 				printf("Break SASL Success\n");
				break;
			}
			case CoreProtocol::EReady: {
// 				printf("Done!\n");
				state = Active;
				ready();
				break;
			}
			case CoreProtocol::EPeerClosed: {
//				printf("DocumentClosed\n");
//				reset();
//				connectionClosed();
				return;
			}
			case CoreProtocol::EStanzaReady: {
//				printf("StanzaReady\n");
				// store the stanza for now, announce after processing all events
				Stanza s = createStanza(proto->recvStanza());
				if(s.isNull())
					break;
				in.append(new Stanza(s));
				break;
			}
			case CoreProtocol::EStanzaSent: {
//				printf("StanzasSent\n");
//				stanzaWritten();
//				if(!self)
//					return;
				break;
			}
			case CoreProtocol::EClosed: {
//				printf("Closed\n");
//				reset();
//				delayedCloseFinished();
				return;
			}
		}
	}
}
Example #10
0
void CallTargetFinder<dsa>::findIndTargets(Module &M)
{
  dsa* T = &getAnalysis<dsa>();
  const DSCallGraph & callgraph = T->getCallGraph();
  DSGraph* G = T->getGlobalsGraph();
  DSGraph::ScalarMapTy& SM = G->getScalarMap();
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    if (!I->isDeclaration())
      for (Function::iterator F = I->begin(), FE = I->end(); F != FE; ++F)
        for (BasicBlock::iterator B = F->begin(), BE = F->end(); B != BE; ++B)
          if (isa<CallInst>(B) || isa<InvokeInst>(B)) {
            CallSite cs(B);
            AllSites.push_back(cs);
            Function* CF = cs.getCalledFunction();

            if (isa<UndefValue>(cs.getCalledValue())) continue;
            if (isa<InlineAsm>(cs.getCalledValue())) continue;

            //
            // If the called function is casted from one function type to
            // another, peer into the cast instruction and pull out the actual
            // function being called.
            //
            if (!CF)
              CF = dyn_cast<Function>(cs.getCalledValue()->stripPointerCasts());

            if (!CF) {
              Value * calledValue = cs.getCalledValue()->stripPointerCasts();
              if (isa<ConstantPointerNull>(calledValue)) {
                ++DirCall;
                CompleteSites.insert(cs);
              } else {
                IndCall++;

                DSCallGraph::callee_iterator csi = callgraph.callee_begin(cs),
                                   cse = callgraph.callee_end(cs);
                while(csi != cse) {
                  const Function *F = *csi;
                  DSCallGraph::scc_iterator sccii = callgraph.scc_begin(F),
                    sccee = callgraph.scc_end(F);
                  for(;sccii != sccee; ++sccii) {
                    DSGraph::ScalarMapTy::const_iterator I = SM.find(SM.getLeaderForGlobal(*sccii));
                    if (I != SM.end()) {
                      IndMap[cs].push_back (*sccii);
                    }
                  }
                  ++csi;
                }
                const Function *F1 = (cs).getInstruction()->getParent()->getParent();
                F1 = callgraph.sccLeader(&*F1);
                
                DSCallGraph::scc_iterator sccii = callgraph.scc_begin(F1),
                  sccee = callgraph.scc_end(F1);
                for(;sccii != sccee; ++sccii) {
                  DSGraph::ScalarMapTy::const_iterator I = SM.find(SM.getLeaderForGlobal(*sccii));
                  if (I != SM.end()) {
                    IndMap[cs].push_back (*sccii);
                  }
                }

                DSNode* N = T->getDSGraph(*cs.getCaller())
                  ->getNodeForValue(cs.getCalledValue()).getNode();
                assert (N && "CallTarget: findIndTargets: No DSNode!");

                if (!N->isIncompleteNode() && !N->isExternalNode() && IndMap[cs].size()) {
                  CompleteSites.insert(cs);
                  ++CompleteInd;
                } 
                if (!N->isIncompleteNode() && !N->isExternalNode() && !IndMap[cs].size()) {
                  ++CompleteEmpty;
                  DEBUG(errs() << "Call site empty: '"
                                << cs.getInstruction()->getName()
                                << "' In '"
                                << cs.getInstruction()->getParent()->getParent()->getName()
                                << "'\n");
                }
              }
            } else {
              ++DirCall;
              IndMap[cs].push_back(CF);
              CompleteSites.insert(cs);
            }
          }
}
Example #11
0
	void LogToFile :: SignalStop()
	{
		CriticalSection cs(&mLock);
		cs.Signal();
	}
Example #12
0
File: itutil.cpp Project: simul/icu
// Exercise almost every LocalPointer and LocalPointerBase method.
void LocalPointerTest::TestLocalPointer() {
    // constructor
    LocalPointer<UnicodeString> s(new UnicodeString((UChar32)0x50005));
    // isNULL(), isValid(), operator==(), operator!=()
    if(s.isNull() || !s.isValid() || s==NULL || !(s!=NULL)) {
        errln("LocalPointer constructor or NULL test failure");
        return;
    }
    // getAlias(), operator->, operator*
    if(s.getAlias()->length()!=2 || s->length()!=2 || (*s).length()!=2) {
        errln("LocalPointer access failure");
    }
    // adoptInstead(), orphan()
    s.adoptInstead(new UnicodeString((UChar)0xfffc));
    if(s->length()!=1) {
        errln("LocalPointer adoptInstead(U+FFFC) failure");
    }
    UnicodeString *orphan=s.orphan();
    if(orphan==NULL || orphan->length()!=1 || s.isValid() || s!=NULL) {
        errln("LocalPointer orphan() failure");
    }
    delete orphan;
    s.adoptInstead(new UnicodeString());
    if(s->length()!=0) {
        errln("LocalPointer adoptInstead(empty) failure");
    }

    // LocalPointer(p, errorCode) sets U_MEMORY_ALLOCATION_ERROR if p==NULL.
    UErrorCode errorCode = U_ZERO_ERROR;
    LocalPointer<CharString> cs(new CharString("some chars", errorCode), errorCode);
    if(cs.isNull() && U_SUCCESS(errorCode)) {
        errln("LocalPointer(p, errorCode) failure");
        return;
    }
    errorCode = U_ZERO_ERROR;
    cs.adoptInsteadAndCheckErrorCode(new CharString("different chars", errorCode), errorCode);
    if(cs.isNull() && U_SUCCESS(errorCode)) {
        errln("adoptInsteadAndCheckErrorCode(p, errorCode) failure");
        return;
    }
    // Incoming failure: Keep the current object and delete the input object.
    errorCode = U_ILLEGAL_ARGUMENT_ERROR;
    cs.adoptInsteadAndCheckErrorCode(new CharString("unused", errorCode), errorCode);
    if(cs.isValid() && strcmp(cs->data(), "different chars") != 0) {
        errln("adoptInsteadAndCheckErrorCode(p, U_FAILURE) did not retain the old object");
        return;
    }
    errorCode = U_ZERO_ERROR;
    cs.adoptInsteadAndCheckErrorCode(NULL, errorCode);
    if(errorCode != U_MEMORY_ALLOCATION_ERROR) {
        errln("adoptInsteadAndCheckErrorCode(NULL, errorCode) did not set U_MEMORY_ALLOCATION_ERROR");
        return;
    }
    if(cs.isValid()) {
        errln("adoptInsteadAndCheckErrorCode(NULL, errorCode) kept the object");
        return;
    }
    errorCode = U_ZERO_ERROR;
    LocalPointer<CharString> null(NULL, errorCode);
    if(errorCode != U_MEMORY_ALLOCATION_ERROR) {
        errln("LocalPointer(NULL, errorCode) did not set U_MEMORY_ALLOCATION_ERROR");
        return;
    }

    // destructor
}
    virtual void tryAgain() {
        // All exits of the method must emit the ready signal
        // so all exits go through a goto ready;
        if(step == 0) {
            out_mech = mechanism_;

#ifdef SIMPLESASL_PLAIN
            // PLAIN
            if (out_mech == "PLAIN") {
                // First, check if we have everything
                if(need.user || need.pass) {
                    qWarning("simplesasl.cpp: Did not receive necessary auth parameters");
                    result_ = Error;
                    goto ready;
                }
                if(!have.user)
                    need.user = true;
                if(!have.pass)
                    need.pass = true;
                if(need.user || need.pass) {
                    result_ = Params;
                    goto ready;
                }

                // Continue with authentication
                QByteArray plain;
                if (!authz.isEmpty())
                    plain += authz.toUtf8();
                plain += '\0' + user.toUtf8() + '\0' + pass.toByteArray();
                out_buf.resize(plain.length());
                memcpy(out_buf.data(), plain.data(), out_buf.size());
            }
#endif
            ++step;
            if (out_mech == "PLAIN")
                result_ = Success;
            else
                result_ = Continue;
        }
        else if(step == 1) {
            // if we still need params, then the app has failed us!
            if(need.user || need.authzid || need.pass || need.realm) {
                qWarning("simplesasl.cpp: Did not receive necessary auth parameters");
                result_ = Error;
                goto ready;
            }
            // see if some params are needed
            if(!have.user)
                need.user = true;
            //if(!have.authzid)
            //	need.authzid = true;
            if(!have.pass)
                need.pass = true;
            if(need.user || need.authzid || need.pass) {
                result_ = Params;
                goto ready;
            }

            // get props
            QByteArray cs(in_buf);
            PropList in;
            if(!in.fromString(cs)) {
                authCondition_ = QCA::SASL::BadProtocol;
                result_ = Error;
                goto ready;
            }
            //qDebug() << (QString("simplesasl.cpp: IN: %1").arg(QString(in.toString())));

            // make a cnonce
            QByteArray a(32,'\0');
            for(int n = 0; n < (int)a.size(); ++n)
                a[n] = (char)(256.0*rand()/(RAND_MAX+1.0));
            QByteArray cnonce = QCA::Base64().arrayToString(a).toLatin1();

            // make other variables
            if (realm.isEmpty())
                realm = QString::fromUtf8(in.get("realm"));
            QByteArray nonce = in.get("nonce");
            QByteArray nc = "00000001";
            QByteArray uri = service.toUtf8() + '/' + host.toUtf8();
            QByteArray qop = "auth";

            // build 'response'
            QByteArray X = user.toUtf8() + ':' + realm.toUtf8() + ':' + pass.toByteArray();
            QByteArray Y = QCA::Hash("md5").hash(X).toByteArray();
            QByteArray tmp = ':' + nonce + ':' + cnonce;
            if (!authz.isEmpty())
                tmp += ':' + authz.toUtf8();
            //qDebug() << (QString(tmp));

            QByteArray A1(Y + tmp);
            QByteArray A2 = QByteArray("AUTHENTICATE:") + uri;
            QByteArray HA1 = QCA::Hash("md5").hashToString(A1).toLatin1();
            QByteArray HA2 = QCA::Hash("md5").hashToString(A2).toLatin1();
            QByteArray KD = HA1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + HA2;
            QByteArray Z = QCA::Hash("md5").hashToString(KD).toLatin1();

            //qDebug() << (QString("simplesasl.cpp: A1 = %1").arg(QString(A1)).toAscii());
            //qDebug() << (QString("simplesasl.cpp: A2 = %1").arg(QString(A2)).toAscii());
            //qDebug() << (QString("simplesasl.cpp: KD = %1").arg(QString(KD)).toAscii());

            // build output
            PropList out;
            out.set("username", user.toUtf8());
            if (!realm.isEmpty())
                out.set("realm", realm.toUtf8());
            out.set("nonce", nonce);
            out.set("cnonce", cnonce);
            out.set("nc", nc);
            //out.set("serv-type", service.utf8());
            //out.set("host", host.utf8());
            out.set("digest-uri", uri);
            out.set("qop", qop);
            out.set("response", Z);
            out.set("charset", "utf-8");
            if (!authz.isEmpty())
                out.set("authzid", authz.toUtf8());
            QByteArray s(out.toString());
            //qDebug() << (QString("OUT: %1").arg(QString(out.toString())));

            // done
            out_buf.resize(s.length());
            memcpy(out_buf.data(), s.data(), out_buf.size());
            ++step;
            result_ = Continue;
        }
        /*		else if (step == 2) {
        			out_buf.resize(0);
        			result_ = Continue;
        			++step;
        		}*/
        else {
            out_buf.resize(0);
            result_ = Success;
        }
ready:
        QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
    }
Example #14
0
nsresult
nsExpatDriver::HandleError()
{
  int32_t code = XML_GetErrorCode(mExpatParser);
  NS_ASSERTION(code > XML_ERROR_NONE, "unexpected XML error code");

  // Map Expat error code to an error string
  // XXX Deal with error returns.
  nsAutoString description;
  nsParserMsgUtils::GetLocalizedStringByID(XMLPARSER_PROPERTIES, code,
                                           description);

  if (code == XML_ERROR_TAG_MISMATCH) {
    /**
     *  Expat can send the following:
     *    localName
     *    namespaceURI<separator>localName
     *    namespaceURI<separator>localName<separator>prefix
     *
     *  and we use 0xFFFF for the <separator>.
     *
     */
    const PRUnichar *mismatch = MOZ_XML_GetMismatchedTag(mExpatParser);
    const PRUnichar *uriEnd = nullptr;
    const PRUnichar *nameEnd = nullptr;
    const PRUnichar *pos;
    for (pos = mismatch; *pos; ++pos) {
      if (*pos == kExpatSeparatorChar) {
        if (uriEnd) {
          nameEnd = pos;
        }
        else {
          uriEnd = pos;
        }
      }
    }

    nsAutoString tagName;
    if (uriEnd && nameEnd) {
      // We have a prefix.
      tagName.Append(nameEnd + 1, pos - nameEnd - 1);
      tagName.Append(PRUnichar(':'));
    }
    const PRUnichar *nameStart = uriEnd ? uriEnd + 1 : mismatch;
    tagName.Append(nameStart, (nameEnd ? nameEnd : pos) - nameStart);
    
    nsAutoString msg;
    nsParserMsgUtils::GetLocalizedStringByName(XMLPARSER_PROPERTIES,
                                               "Expected", msg);

    // . Expected: </%S>.
    PRUnichar *message = nsTextFormatter::smprintf(msg.get(), tagName.get());
    if (!message) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    description.Append(message);

    nsTextFormatter::smprintf_free(message);
  }

  // Adjust the column number so that it is one based rather than zero based.
  uint32_t colNumber = XML_GetCurrentColumnNumber(mExpatParser) + 1;
  uint32_t lineNumber = XML_GetCurrentLineNumber(mExpatParser);

  nsAutoString errorText;
  CreateErrorText(description.get(), XML_GetBase(mExpatParser), lineNumber,
                  colNumber, errorText);

  NS_ASSERTION(mSink, "no sink?");

  nsAutoString sourceText(mLastLine);
  AppendErrorPointer(colNumber, mLastLine.get(), sourceText);

  // Try to create and initialize the script error.
  nsCOMPtr<nsIScriptError> serr(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
  nsresult rv = NS_ERROR_FAILURE;
  if (serr) {
    rv = serr->InitWithWindowID(description.get(),
                                mURISpec.get(),
                                mLastLine.get(),
                                lineNumber, colNumber,
                                nsIScriptError::errorFlag, "malformed-xml",
                                mInnerWindowID);
  }

  // If it didn't initialize, we can't do any logging.
  bool shouldReportError = NS_SUCCEEDED(rv);

  if (mSink && shouldReportError) {
    rv = mSink->ReportError(errorText.get(), 
                            sourceText.get(), 
                            serr, 
                            &shouldReportError);
    if (NS_FAILED(rv)) {
      shouldReportError = true;
    }
  }

  if (shouldReportError) {
    nsCOMPtr<nsIConsoleService> cs
      (do_GetService(NS_CONSOLESERVICE_CONTRACTID));  
    if (cs) {
      cs->LogMessage(serr);
    }
  }

  return NS_ERROR_HTMLPARSER_STOPPARSING;
}
void CCredentialsManager::loadCA(const std::string& strPath)
{
	std::shared_ptr<Botan::Certificate_Store> cs(new Botan::Certificate_Store_In_Memory(strPath));
	m_vCerts.push_back(cs);
}
void 												
World::build(void) {
	int num_samples = 100;
	
	vp.set_hres(600);
	vp.set_vres(400);
	vp.set_samples(num_samples);
		
	tracer_ptr = new AreaLighting(this);	
		
	AmbientOccluder* ambient_occluder_ptr = new AmbientOccluder;
	ambient_occluder_ptr->set_sampler(new MultiJittered(num_samples));
	ambient_occluder_ptr->set_min_amount(0.5);
	set_ambient_light(ambient_occluder_ptr);

			
	Pinhole* pinhole_ptr = new Pinhole;
	pinhole_ptr->set_eye(100, 45, 100);  
	pinhole_ptr->set_lookat(-10, 40, 0);  
	pinhole_ptr->set_view_distance(400);  
	pinhole_ptr->compute_uvw(); 
	set_camera(pinhole_ptr);

	
	Emissive* emissive_ptr = new Emissive;
	emissive_ptr->scale_radiance(0.90);
	emissive_ptr->set_ce(white);   	
		
	ConcaveSphere* sphere_ptr = new ConcaveSphere;
	sphere_ptr->set_radius(1000000.0);
	sphere_ptr->set_material(emissive_ptr);
	sphere_ptr->set_shadows(false);
	add_object(sphere_ptr);
	
	EnvironmentLight* environment_light_ptr = new EnvironmentLight;
	environment_light_ptr->set_material(emissive_ptr);
	environment_light_ptr->set_sampler(new MultiJittered(num_samples));
	environment_light_ptr->set_shadows(true);
	add_light(environment_light_ptr);
	
	
	float ka = 0.2;  		// commom ambient reflection coefficient
	float ks = 1.0;  		// commom specular reflection coefficient
	float exp = 10.0;   	// for Figure 18.11(a)
//	float exp = 50.0;   	// for Figure 18.11(b)
//	float exp = 200.0;   	// for Figure 18.11(c)
	RGBColor cs(1, 0, 0); 	// common specular color
	
	// large sphere
	
	Phong* phong_ptr1 = new Phong;			
	phong_ptr1->set_ka(ka); 
	phong_ptr1->set_kd(0.6);
	phong_ptr1->set_cd(0.75);
	phong_ptr1->set_ks(ks);
	phong_ptr1->set_exp(exp);
	phong_ptr1->set_cs(cs);
	
	Sphere* sphere_ptr1 = new Sphere(Point3D(38, 20, -24), 20);
	sphere_ptr1->set_material(phong_ptr1);
	add_object(sphere_ptr1);
	
	
	// small sphere
		
	Phong* phong_ptr2 = new Phong;			
	phong_ptr2->set_ka(ka); 
	phong_ptr2->set_kd(0.5);
	phong_ptr2->set_cd(0.95);
	phong_ptr2->set_ks(ks);
	phong_ptr2->set_exp(exp);
	phong_ptr2->set_cs(cs);
	
	Sphere* sphere_ptr2 = new Sphere(Point3D(34, 12, 13), 12);
	sphere_ptr2->set_material(phong_ptr2);
	add_object(sphere_ptr2);
	
	
	// medium sphere
	
	Phong* phong_ptr3 = new Phong;			
	phong_ptr3->set_ka(ka); 
	phong_ptr3->set_kd(0.5);
	phong_ptr3->set_cd(0.75);
	phong_ptr3->set_ks(ks);
	phong_ptr3->set_exp(exp);
	phong_ptr3->set_cs(cs);
	
	Sphere* sphere_ptr3 = new Sphere(Point3D(-7, 15, 42), 16);
	sphere_ptr3->set_material(phong_ptr3);
	add_object(sphere_ptr3);
	
	
	// cylinder
	
	Phong* phong_ptr4 = new Phong;			
	phong_ptr4->set_ka(ka); 
	phong_ptr4->set_kd(0.5);
	phong_ptr4->set_cd(0.60);
	phong_ptr4->set_ks(ks);
	phong_ptr4->set_exp(exp);
	phong_ptr4->set_cs(cs);
	
	float bottom 	= 0.0;
	float top 		= 85; 
	float radius	= 22;
	SolidCylinder* cylinder_ptr = new SolidCylinder(bottom, top, radius);
	cylinder_ptr->set_material(phong_ptr4);
	add_object(cylinder_ptr);

	
	// box
	
	Phong* phong_ptr5 = new Phong;			
	phong_ptr5->set_ka(ka); 
	phong_ptr5->set_kd(0.5);
	phong_ptr5->set_cd(0.95);
	phong_ptr5->set_ks(ks);
	phong_ptr5->set_exp(exp);
	phong_ptr5->set_cs(cs);
	
	Box* box_ptr = new Box(Point3D(-35, 0, -110), Point3D(-25, 60, 65));
	box_ptr->set_material(phong_ptr5);
	add_object(box_ptr);
	
				
	// ground plane
		
	Matte* matte_ptr6 = new Matte;			
	matte_ptr6->set_ka(0.15); 
	matte_ptr6->set_kd(0.5);	
	matte_ptr6->set_cd(0.7);    
	
	Plane* plane_ptr = new Plane(Point3D(0, 0.01, 0), Normal(0, 1, 0));
	plane_ptr->set_material(matte_ptr6);
	add_object(plane_ptr);
}
Example #17
0
File: main.cpp Project: E-LLP/trick
/**

Most of the main program is pieced together from examples on the web. We are doing the following.

-# Creating lists of include directories, defines, and input files from the command line arguments.
-# Initializing the compiler to read C++ code, and setting the compiler to think we are creating
   code for the default target architecture.
-# Creating the necessary source and file managers as well as the preprocessor.
-# Adding search directories and creating #define statements for -D command line arguments.
-# Telling clang to use our ICGASTConsumer as an ASTConsumer.
-# Parse the input file.

*/
int main( int argc , char * argv[] ) {

#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 5))
    clang::TargetOptions to;
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    clang::TargetOptions * to = new clang::TargetOptions() ;
#else
    clang::TargetOptions to;
#endif
    clang::CompilerInstance ci;

    /* Gather all of the command line arguments into lists of include directories, defines, and input files.
       All other arguments will be ignored. */
    llvm::cl::SetVersionPrinter(ICG_version) ;
    llvm::cl::ParseCommandLineOptions(argc , argv) ;

    if ( ! validAttributesVersion(attr_version) ) {
        return -1 ;
    }

/*
    if ( show_units ) {
        list_units() ;
        return 0 ;
    }
*/

    if ( input_file_names.empty() ) {
        std::cerr << "No header file specified" << std::endl ;
        return 1 ;
    }

    ci.createDiagnostics();
    clang::DiagnosticOptions & diago = ci.getDiagnosticOpts() ;
    diago.ShowColors = 1 ;
    ci.getDiagnostics().setIgnoreAllWarnings(true) ;
#if ( GCC_MAJOR == 4 ) && ( GCC_MINOR <= 2 )
    ci.getDiagnostics().setSuppressAllDiagnostics() ;
#endif

    // Set all of the defaults to c++
    clang::CompilerInvocation::setLangDefaults(ci.getLangOpts() , clang::IK_CXX) ;
    ci.getLangOpts().CXXExceptions = true ;

    // Activate C++11 parsing
    ci.getLangOpts().CPlusPlus11 = true ;

    // Set the default target architecture
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    to.Triple = llvm::sys::getDefaultTargetTriple();
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    to->Triple = llvm::sys::getDefaultTargetTriple();
#else
    to.Triple = llvm::sys::getDefaultTargetTriple();
#endif

#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    std::shared_ptr<clang::TargetOptions> shared_to  = std::make_shared<clang::TargetOptions>(to) ;
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), shared_to);
#else
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), to);
#endif
    ci.setTarget(pti);

    // Create all of the necessary managers.
    ci.createFileManager();
    ci.createSourceManager(ci.getFileManager());
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    ci.createPreprocessor(clang::TU_Complete);
#else
    ci.createPreprocessor();
#endif

    clang::HeaderSearch & hs = ci.getPreprocessor().getHeaderSearchInfo() ;
    clang::HeaderSearchOptions & hso = ci.getHeaderSearchOpts() ;
    clang::Preprocessor & pp = ci.getPreprocessor() ;

    // Add all of the include directories to the preprocessor
    HeaderSearchDirs hsd(hs , hso , pp, sim_services_flag) ;
    hsd.addSearchDirs ( include_dirs ) ;

    // Tell the preprocessor to use its default predefines
    clang::PreprocessorOptions & ppo = ci.getPreprocessorOpts() ;
    ppo.UsePredefines = true;
#if (__clang_major__ == 3) && (__clang_minor__ >= 8)
    pp.getBuiltinInfo().initializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
#else
    pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
#endif
    // Add all of the #define from the command line to the default predefines.
    hsd.addDefines ( defines ) ;

    // Add our comment saver as a comment handler in the preprocessor
    CommentSaver cs(ci, hsd) ;
    pp.addCommentHandler(&cs) ;

    PrintAttributes pa( attr_version, hsd, cs, ci, force, sim_services_flag, output_dir) ;

    // create new class and enum map files
    if ( create_map ) {
        pa.createMapFiles() ;
    }

    // Tell the compiler to use our ICGASTconsumer
    ICGASTConsumer *astConsumer = new ICGASTConsumer(ci, hsd, cs, pa);
#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 6))
    std::unique_ptr<clang::ASTConsumer> unique_ast(astConsumer) ;
    ci.setASTConsumer(std::move(unique_ast));
#else
    ci.setASTConsumer(astConsumer);
#endif
    ci.createASTContext();
    ci.createSema(clang::TU_Prefix, NULL);

    // Get the full path of the file to be read.
    char * input_file_cp = strdup(input_file_names[0].c_str()) ;
    char * input_file_file = basename(input_file_cp) ;
    char * input_file_dir = dirname(input_file_cp) ;
    char * input_file_full_path = NULL ;
    std::stringstream os ;
    os << input_file_dir << "/" << input_file_file ;
    input_file_full_path = almostRealPath( os.str().c_str() ) ;
    //std::cout << input_file_full_path << std::endl ;

    struct stat buffer ;
    if ( stat ( input_file_full_path , &buffer) != 0 ) {
        std::cerr << "Could not open file " << input_file_full_path << std::endl ;
        exit(-1) ;
    }
    // Open up the input file and parse it.
    const clang::FileEntry *pFile = ci.getFileManager().getFile(input_file_full_path);
#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 5))
    ci.getSourceManager().setMainFileID(ci.getSourceManager().createFileID(pFile, clang::SourceLocation(), clang::SrcMgr::C_User));
#else
    ci.getSourceManager().createMainFileID(pFile);
#endif
    ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(), &ci.getPreprocessor());
    clang::ParseAST(ci.getSema());
    ci.getDiagnosticClient().EndSourceFile();

    free(input_file_cp) ;
    free(input_file_full_path) ;

    if ( ! sim_services_flag ) {
        pa.printIOMakefile() ;
    }

    // Close the map files
    pa.closeMapFiles() ;

    // Print the list of headers that have the ICG:(No) comment
    pa.printICGNoFiles() ;

    return 0;
}
Example #18
0
DWORD WINAPI CheckImages(LPVOID pData)
{
	iMode=0;
	bStopCheck=0;
	bStopLoad=0;
	lDeletedFiles=0;
	// Первый этап - сбор дибов
	CSize aMins(100,100);
	CDesktopDC dcDesk;
	int iSize=sListOfImages.GetSize();
	for(int zi=0;zi<iSize;zi++){
		aClosestImage.SetAtGrow(zi,-1);
		aClosestImageTaken.SetAtGrow(zi,0);
	}
	/*CSplashParams* sp=0;
	CSplashWindow* sw=0;
	if(!hDiag){
		sp=new CSplashParams();
		sp->szText="Reading...";
		sp->bgColor=0;
		sp->txColor=RGB(255,255,255);
		sp->dwTextParams|=TXSHADOW_VCENT|TXSHADOW_FILLBG|TXSHADOW_WIDE|TXSHADOW_GLOW|TXSHADOW_MIXBG;////TXSHADOW_SHCOL
		sp->dwSplashAlign=SPLASH_OPACITY;
		sp->dwSplashAlign|=SPLASH_HLEFT;
		sp->dwSplashAlign|=SPLASH_VTOP;
		sw=new CSplashWindow(sp);
	}*/
	{
		CDesktopDC dcDesk;
		CDC dc;
		dc.CreateCompatibleDC(&dcDesk);
		CDC dc2;
		dc2.CreateCompatibleDC(&dcDesk);
		dc.SetStretchBltMode(HALFTONE);
		dc2.SetStretchBltMode(HALFTONE);
		CSmartLock cs(csCheck,TRUE);
		for(int i=0;i<iSize;i++){
			if(bStopCheck){
				break;
			}
			if(bStopLoad){
				iMode=1;
				break;
			}
			if(hDiag){
				::SetWindowText(hDiag,Format("%i%%, %s",long(100*i/double(iSize)),_l("Preparations")));
				::SetWindowText(GetDlgItem(hDiag,IDC_STATUS),Format(" %s #%i/%i...",_l("Preparing image"),i,iSize));
			}
			sListOfImageDibs.SetAtGrow(i,0);
			CBitmap* bmp=_bmpX()->LoadBmpFromPath(sListOfImages[i]);
			CSize size2=GetBitmapSize(bmp);
			if(bmp){
				{// Занести обратно
					//HBITMAP hSmall=0;
					// CopyBitmapToBitmap(*bmp,hSmall,CSize(0,0),&aMins,-1);
					CBitmap bmpSmall;
					bmpSmall.CreateCompatibleBitmap(&dc,aMins.cx,aMins.cy);
					CBitmap* bmpTmp=dc.SelectObject(bmp);
					CBitmap* bmpTmp2=dc2.SelectObject(&bmpSmall);
					dc2.StretchBlt(0,0,aMins.cx,aMins.cy,&dc,0,0,size2.cx,size2.cy,SRCCOPY);
					dc2.SelectObject(&bmpTmp2);
					dc.SelectObject(&bmpTmp);
					CDib* pDib=new CDib();
					if(pDib){
						pDib->Create(aMins.cx,aMins.cy);
						pDib->SetBitmap(&dc2,bmpSmall);
						sListOfImageDibs.SetAtGrow(i,pDib);
					}
					//DeleteObject(hSmall);
				}
				_bmpX()->ReleaseBmp(bmp);
			}
		}
		if(!bStopCheck){
			iMode=1;
			if(hDiag){
				::SetWindowText(GetDlgItem(hDiag,ID_NEXT),_l("Next image pair"));
				::EnableWindow(GetDlgItem(hDiag,ID_NEXT),TRUE);
				::SetWindowText(GetDlgItem(hDiag,IDC_STATUS),CString(" ")+_l("Looking for duplicates")+"...");
				::EnableWindow(GetDlgItem(hDiag,IDC_IMGR_DEL_ALL),TRUE);
				::PostMessage(hDiag,WM_COMMAND,ID_NEXT,0);
			}
		}
	}
	/*
	if(sp){
		delete sp;
	}
	if(sw){
		delete sw;
	}
	*/
	return 0;
};
Example #19
0
HRESULT CreateScavengerThread(BOOL bSynchronous)
{
    HRESULT hr=S_OK;
    HRESULT hrCS=S_OK;
    HANDLE hThread=0;
    DWORD dwThreadId=0;
    DWORD Error = 0;
    CCriticalSection cs(&g_csInitClb);

    hrCS = cs.Lock();
    if (FAILED(hrCS)) {
        return hrCS;
    }

    if(g_ScavengingThreadId)
    {
        /*                                                                                   
               */
        hr = S_FALSE;
        goto exit;
    }

    if( bSynchronous )
    {
        g_ScavengingThreadId = GetCurrentThreadId();
        cs.Unlock();
        hr = StartScavenging( (LPVOID)TRUE );
        
        hrCS = cs.Lock();
        if (FAILED(hrCS)) {
            return hrCS;
        }

        g_ScavengingThreadId = 0;
    }
    else
    {
        g_hFusionMod = LoadLibrary(g_FusionDllPath);

        hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) StartScavenging, (LPVOID)FALSE,  0, &dwThreadId);

        if (hThread == NULL)
        {
            Error = GetLastError();
            FreeLibrary(g_hFusionMod);
        }
        else
        {
            g_ScavengingThreadId = dwThreadId;
        }
    }

exit :

    cs.Unlock();

    if(hThread)
        CloseHandle(hThread);

    return hr;
}
Example #20
0
DWORD WINAPI ContinueCheck(LPVOID p)
{
	static long l=0;
	if(l>0){
		return 0;
	}
	SimpleTracker cl(l);
	HWND hwndDlg=(HWND)p;
	CString sTmp;
	{
		CSmartLock cs(csCheck,TRUE);
		while(iBegin<sListOfImageDibs.GetSize()){
			if(bStopCheck==1){
				return TRUE;
			}
			static DWORD dwPTime=0;
			if(GetTickCount()-dwPTime>500){
				int iSize=sListOfImageDibs.GetSize();
				::SetWindowText(hDiag,Format("%i%%, %s. %s: %i",long(100*iBegin/double(iSize)),_l("Searching"),_l("Found"),sListOfImagesToDelete.GetSize()));
				::SetWindowText(GetDlgItem(hwndDlg,IDC_STATUS),Format(" %s %i-%i/%i",_l("Checking images"),iBegin,iBegin2,iSize));
				dwPTime=GetTickCount();
			}
			if(iBegin2>=sListOfImageDibs.GetSize()){
				iBegin++;
				iBegin2=iBegin;
				if(bReplaceMode){// иначе циклится одинаковости
					iBegin2=0;
				}
				dMaxAffinity=DMAXAFF;
			}
			if(iBegin>=sListOfImageDibs.GetSize()){
				break;
			}
			if(iBegin!=iBegin2){
				BOOL bAlreadyDeleted=0;
				CString sPathInLeftTmp=sListOfImages[iBegin];
				sPathInLeftTmp.TrimRight();
				sPathInLeftTmp.TrimLeft();
				CString sPathInRightTmp=sListOfImages[iBegin2];
				sPathInRightTmp.TrimRight();
				sPathInRightTmp.TrimLeft();
				BOOL bForceAff=0;
				if(sListOfImageDibs[iBegin]==0 || sListOfImageDibs[iBegin2]==0){
					bAlreadyDeleted=1;
				}else{
					for(int k=0;k<sListOfImagesToDelete.GetSize();k++){
						if(sPathInLeftTmp.CompareNoCase(sListOfImagesToDelete[k])==0){
							bAlreadyDeleted=1;
							break;
						}
						if(sPathInRightTmp.CompareNoCase(sListOfImagesToDelete[k])==0){
							bAlreadyDeleted=1;
							break;
						}
					}
				}
				if(!bAlreadyDeleted){
					CDib* dbL=sListOfImageDibs[iBegin];
					CDib* dbR=sListOfImageDibs[iBegin2];
					if(bReplaceMode){
						if(aClosestImageTaken[iBegin2]==0)//0-первый,особенный
						{
							double lAffinity=dbL->CalcDistance(dbR);
							//long lRenameOrder;//sListOfImagesToRename
							if(lAffinity<dMaxAffinity || fabs(dMaxAffinity-DMAXAFF)<1.0f){
								dMaxAffinity=lAffinity;
								if(aClosestImage[iBegin]!=-1){
									aClosestImageTaken[aClosestImage[iBegin]]--;
								}
								aClosestImage[iBegin]=iBegin2;
								aClosestImageTaken[iBegin2]++;
							}
						}
					}else {
						double lAffinity=dbL->CalcAffinity(dbR);
						if(lAffinity>.89 || bForceAff){
							sPathInLeft=sPathInLeftTmp;
							sPathInRight=sPathInRightTmp;
							if(sPathInLeft.CompareNoCase(sPathInRight)!=0){
								::SetWindowText(GetDlgItem(hwndDlg,IDC_LI_ST),sPathInLeft);
								sTmp=sPathInLeft;
								sTmp.MakeLower();
								if(sTmp.Find(".zip")==-1 && !IsFileHTML(sTmp)){
									::EnableWindow(GetDlgItem(hwndDlg,IDC_IMGL_DEL),TRUE);
								}
								::SetWindowText(GetDlgItem(hwndDlg,IDC_RI_ST),sPathInRight);
								sTmp=sPathInRight;
								sTmp.MakeLower();
								if(sTmp.Find(".zip")==-1 && !IsFileHTML(sTmp)){
									::EnableWindow(GetDlgItem(hwndDlg,IDC_IMGR_DEL),TRUE);
								}
								if(btLeft){
									_bmpX()->ReleaseBmp(btLeft);
									btLeft=0;
								}
								if(btLeft==0){
									btLeft=_bmpX()->LoadBmpFromPath(sPathInLeft);
									szLeftSize=GetBitmapSize(btLeft);
									::SetWindowText(GetDlgItem(hwndDlg,IDC_LI_ST),Format("%ix%i; %s; %s; %s:%i%%",szLeftSize.cx,szLeftSize.cy,GetSizeStrFrom(GetFileSize(sPathInLeft),0),sPathInLeft,_l("Similarity"),int(100*lAffinity)));
									dwPathInLeftRes=szLeftSize.cx*szLeftSize.cy;
								}
								if(btRight){
									_bmpX()->ReleaseBmp(btRight);
									btRight=0;
								}
								if(btRight==0){
									btRight=_bmpX()->LoadBmpFromPath(sPathInRight);
									szRightSize=GetBitmapSize(btRight);
									::SetWindowText(GetDlgItem(hwndDlg,IDC_RI_ST),Format("%ix%i; %s; %s; %s:%i%%",szRightSize.cx,szRightSize.cy,GetSizeStrFrom(GetFileSize(sPathInRight),0),sPathInRight,_l("Similarity"),int(100*lAffinity)));
									dwPathInRightRes=szRightSize.cx*szRightSize.cy;
								}
								if(dwPathInRightRes>dwPathInLeftRes){
									SendMessage(hwndDlg,DM_SETDEFID,IDC_IMGL_DEL,0);
									::SetFocus(GetDlgItem(hwndDlg,IDC_IMGL_DEL));
									::SetWindowText(GetDlgItem(hwndDlg,IDC_IMGR_DEL),_l("Delete this image"));
									::SetWindowText(GetDlgItem(hwndDlg,IDC_IMGL_DEL),_l("Delete this image")+"*");
								}else{
									SendMessage(hwndDlg,DM_SETDEFID,IDC_IMGR_DEL,0);
									::SetFocus(GetDlgItem(hwndDlg,IDC_IMGR_DEL));
									::SetWindowText(GetDlgItem(hwndDlg,IDC_IMGR_DEL),_l("Delete this image")+"*");
									::SetWindowText(GetDlgItem(hwndDlg,IDC_IMGL_DEL),_l("Delete this image"));
								}
								::InvalidateRect(hwndDlg,0,TRUE);
								break;
							}
						}
					}
				}
			}
			iBegin2++;
		}
	}
	::EnableWindow(GetDlgItem(hwndDlg,ID_NEXT),TRUE);
	if(iBegin>=sListOfImageDibs.GetSize()){
		::EnableWindow(GetDlgItem(hwndDlg,IDC_IMGL_DEL),FALSE);
		::EnableWindow(GetDlgItem(hwndDlg,IDC_IMGR_DEL),FALSE);
		::EnableWindow(GetDlgItem(hwndDlg,ID_NEXT),FALSE);
		PostMessage(hwndDlg,WM_COMMAND,IDOK,0);
	}else{
		::SetWindowText(GetDlgItem(hwndDlg,IDC_STATUS),Format(" %s: %i-%i/%i",_l("Choose one"),iBegin,iBegin2,sListOfImageDibs.GetSize()));
	}
	if(bAutoDelRight){
		if(bStopCheck==0){
			PostMessage(hwndDlg,WM_COMMAND,WM_USER,0);
		}
	}
	return 0;
}
int main(int argc, char** argv)
{
#if defined(_MSC_VER)
    compile_msvc compile_policy;
#else
    compile_bjam compile_policy;
#endif


    typedef std::vector<algorithm> v_a_type;
    v_a_type algorithms;
    algorithms.push_back(algorithm("area"));
    algorithms.push_back(algorithm("length"));
    algorithms.push_back(algorithm("perimeter"));
    algorithms.push_back(algorithm("correct"));
    algorithms.push_back(algorithm("distance", 2));
    algorithms.push_back(algorithm("centroid", 2));
    algorithms.push_back(algorithm("intersects", 2));
    algorithms.push_back(algorithm("within", 2));
    algorithms.push_back(algorithm("equals", 2));

    typedef std::vector<cs> cs_type;
    cs_type css;
    css.push_back(cs("cartesian"));
    // css.push_back(cs("spherical<bg::degree>"));
    // css.push_back(cs("spherical<bg::radian>"));


    boost::timer timer;

    for (v_a_type::const_iterator it = algorithms.begin(); it != algorithms.end(); ++it)
    {
/*([heading Behavior]
[table
[[Case] [Behavior] ]
[[__2dim__][All combinations of: box, ring, polygon, multi_polygon]]
[[__other__][__nyiversion__]]
[[__sph__][__nyiversion__]]
[[Three dimensional][__nyiversion__]]
]*/

        std::ostringstream name;
        name << "../../../../generated/" << it->name << "_status.qbk";

        std::ofstream out(name.str().c_str());
        out << "[heading Supported geometries]" << std::endl;

        cs_type::const_iterator cit = css.begin();

        {
            // Construct the table

            std::vector<std::vector<int> > table;

            for (int type = point; type < geometry_count; type++)
            {
                table.push_back(report(compile_policy, type, *it, true, true, 2, cit->name));
            }


            // Detect red rows/columns

            std::vector<int> lines_status(table.size(), false);
            std::vector<int> columns_status(table[0].size(), false);

            for (unsigned int i = 0; i != table.size(); ++i)
            {
                for (unsigned int j = 0; j != table[i].size(); ++j)
                {
                    lines_status[i] |= table[i][j];
                    columns_status[j] |= table[i][j];
                }
            }


            // Display the table

            out << "[table" << std::endl << "[";

            if (it->arity > 1)
            {
                out << "[ ]";
                for (int type = point; type < geometry_count; type++)
                {
                    if (!columns_status[type]) continue;
                    out << "[" << geometry_string(type) << "]";
                }
            }
            else
            {
                out << "[Geometry][Status]";
            }

            out << "]" << std::endl;

            for (unsigned int i = 0; i != table.size(); ++i)
            {
                if (!lines_status[i]) continue;
                out << "[";
                out << "[" << geometry_string(i) << "]";
                for (unsigned int j = 0; j != table[i].size(); ++j)
                {
                    if (!columns_status[j]) continue;
                    out << "[[$img/" << (table[i][j] ? "ok" : "nyi") << ".png]]";
                }
                out << "]" << std::endl;
            }

            out << "]" << std::endl;
        }
    }

    std::cout << "TIME: " << timer.elapsed() << std::endl;

    return 0;
}
int main(int argc, char* argv[])
{

  // COMMENT: For dealing with dataset in int format. Comment out the next line and 
  //          uncomment the line after that.
  typedef adj_list<std::string, int, ALLOCATOR > PAT_ST;
  // typedef adj_list<int, int, ALLOCATOR > PAT_ST;
  typedef pattern<GRAPH_PR, GRAPH_MINE_PR, PAT_ST, canonical_code, ALLOCATOR > GRAPH_PAT;
  typedef vat<GRAPH_PR, GRAPH_MINE_PR, ALLOCATOR, std::vector> GRAPH_VAT;

  level_one_hmap<GRAPH_PAT::VERTEX_T, GRAPH_PAT::EDGE_T, ALLOCATOR > l1_map;

  parse_args(argc, argv);
  pat_fam<GRAPH_PAT> level_one_pats;
  pat_fam<GRAPH_PAT> freq_pats;

  storage_manager<GRAPH_PAT, GRAPH_VAT, ALLOCATOR, memory_storage> vat_map;

  tt_db_read.start();
  tt_total.start();
  db_reader<GRAPH_PAT, DMTL_TKNZ_PR, ALLOCATOR > dbr(infile);
  tt_db_read.stop();

  dbr.get_length_one(level_one_pats, vat_map, minsup);

  cout<<endl<<level_one_pats.size()<<" frequent single-edged patterns found"<<endl;
  freq_pats=level_one_pats;

  populate_level_one_map(freq_pats, l1_map);
  count_support<GRAPH_PR, GRAPH_MINE_PR, PAT_ST, canonical_code, ALLOCATOR, memory_storage > cs(vat_map);

  pat_fam<GRAPH_PAT>::const_iterator pit;
  for(pit=level_one_pats.begin(); pit!=level_one_pats.end(); pit++)
    cand_gen(*pit, l1_map, minsup, freq_pats, cs);
  tt_total.stop();

  if(print)
    cout<<freq_pats<<endl;
  cout<<endl<<"TIMING STATISTICS"<<endl;
  cout<<"Time taken to read db in: "<<tt_db_read.print()<<"sec"<<endl;
  cout<<"Time taken in isomorphism checks: "<<tt_iso_chk.print()<<"sec"<<endl;
  cout<<"Time taken in VAT intersection: "<<tt_vat.print()<<"sec"<<endl;
  cout<<"Total time taken: "<<tt_total.print()<<"sec"<<endl;
  cout<<endl<<endl<<freq_pats_count+level_one_pats.size()<<" total frequent graphs found"<<endl;

}//main()
Example #23
0
bool CExtraImages::SetContactExtraImage(HANDLE hContact,EImageIndex nIndex)const
{
// 	tstring s = Quotes_DBGetStringT(hContact,LIST_MODULE_NAME,CONTACT_LIST_NAME);
// 	tostringstream o;
// 	o << _T("SetContactExtraImage for ") << s << _T("\nExtra image list init: ") << m_bExtraImagesInit << _T("\n");
	
	bool bResult = false;
	if(m_hExtraIcons)
	{
// 		o << "Using extra icon interface\n";
		std::string sIconName;
		switch(nIndex)
		{
		case eiUp:
			sIconName = Quotes_MakeIconName(ICON_STR_QUOTE_UP);
			break;
		case eiDown:
			sIconName = Quotes_MakeIconName(ICON_STR_QUOTE_DOWN);
			break;
		case eiNotChanged:
			sIconName = Quotes_MakeIconName(ICON_STR_QUOTE_NOT_CHANGED);
			break;
		}
		bResult = (0 == ExtraIcon_SetIcon(m_hExtraIcons,hContact,sIconName.c_str()));
	}
	else if(m_bExtraImagesInit && ServiceExists(MS_CLIST_EXTRA_ADD_ICON))
	{
// 		o << "Using contact list interface index is ";
		IconExtraColumn iec = {0};
		iec.cbSize = sizeof(iec);
		iec.ColumnType = m_nSlot;

		{
			CGuard<CLightMutex> cs(m_lmExtraImages);
			switch(nIndex)
			{
			case eiUp:
// 				o << "up\n";
				iec.hImage = m_ahExtraImages[eiUp];
				break;
			case eiDown:
// 				o << "down\n";
				iec.hImage = m_ahExtraImages[eiDown];
				break;
			case eiNotChanged:
// 				o << "not changed\n";
				iec.hImage = m_ahExtraImages[eiNotChanged];
				break;
			default:
// 				o << "invalid\n";
				iec.hImage = INVALID_IMAGE_HANDLE;
				break;
			}
		}

		bResult = (0 == CallService(MS_CLIST_EXTRA_SET_ICON,reinterpret_cast<WPARAM>(hContact),reinterpret_cast<LPARAM>(&iec)));
	}

// 	o << "Result is " << bResult;
// 	LogIt(Info,o.str());
	return bResult;
}
void PushManagerTask::AddPushHandle(PushHandle::Ptr handle) {
    CritScope cs(&crit_);
    ASSERT(handle.get() != NULL);
    push_handles_.push_back(handle);
    push_handle_keys_.insert(handle->cmd_key());
}
Example #25
0
int main(int argc, char * argv[])
{
	try
	{
		testBorderArray();
		testSuccinctBorderArray();

		::libmaus2::util::ArgInfo const arginfo(argc,argv);
		std::string const fn = arginfo.getRestArg<std::string>(0);

		// std::string const fn = "1";
		uint64_t const n = ::libmaus2::util::GetFileSize::getFileSize(fn);
		uint64_t const tpacks = 128;
		uint64_t const packsize = (n+tpacks-1)/tpacks;
		uint64_t const packs = (n + packsize-1)/packsize;

		#if 0 && defined(_OPENMP)
		#pragma omp parallel for
		#endif
		for ( uint64_t i = 0; i < packs; ++i )
		{
			uint64_t const low = std::min(i * packsize,n);
			uint64_t const high = std::min(low+packsize,n);
			findSplitCommon(fn,low,high);
		}
	}
	catch(std::exception const & ex)
	{
		std::cerr << ex.what() << std::endl;
		return EXIT_FAILURE;
	}

	#if 0
	std::string const fn = "X";
	uint64_t const n = ::libmaus2::util::GetFileSize::getFileSize(fn);

	uint64_t const p = n/2;
	uint64_t const m = n-p;

	std::ifstream istrn(fn.c_str(),std::ios::binary);
	std::ifstream istrm(fn.c_str(),std::ios::binary);
	istrm.seekg(p);
	::libmaus2::util::KMP::BestPrefix<std::istream> BP(istrm,m);
	::libmaus2::util::KMP::BestPrefix<std::istream>::BestPrefixXAdapter xadapter = BP.getXAdapter();

	std::pair<uint64_t, uint64_t> Q =
		::libmaus2::util::KMP::PREFIX_SEARCH_INTERNAL_RESTRICTED(
			xadapter,m,BP,
			istrn,n,
			n-m
		);

	uint64_t const printmax = 30;
	if ( Q.second <= printmax )
		std::cerr
			<< "pos " << Q.first << " len " << Q.second << " p=" << p << " m=" << m
			<< " common prefix " << std::string(BP.x.begin(),BP.x.begin()+Q.second)
			<< std::endl;
	else
		std::cerr
			<< "pos " << Q.first << " len " << Q.second << " p=" << p << " m=" << m
			<< " common length " << Q.second
			<< std::endl;

	istrn.clear(); istrn.seekg(Q.first);
	istrm.clear(); istrm.seekg(p);

	for ( uint64_t i = 0; i < Q.second /* std::min(Q.second, static_cast<uint64_t>(20)) */; ++i )
	{
		int const cn = istrn.get();
		int const cm = istrm.get();
		assert ( cn == cm );
		//std::cerr.put(cn);
		//std::cerr.put(cm);
	}
	// std::cerr << std::endl;
	int const cn = istrn.get();
	int const cm = istrm.get();

	assert ( (cn < 0 && cm < 0) || (cn != cm) );

	if ( Q.second+1 <= m )
	{
		istrm.clear(); istrm.seekg(p);
		::libmaus2::autoarray::AutoArray<char> cs(Q.second+1);
		istrm.read(cs.begin(),cs.size());
		std::string s(cs.begin(),cs.begin()+cs.size());
		if ( Q.second <= printmax )
		std::cerr << "extending common prefix by next character in pattern: " << s << std::endl;

		istrn.clear(); istrn.seekg(0);
		::libmaus2::autoarray::AutoArray<char> cc(n);
		istrn.read(cc.begin(),n);
		std::string t(cc.begin(),cc.begin()+cc.size());

		size_t pos = 0;
		while ( pos != std::string::npos )
		{
			pos = t.find(s,pos);
			if ( pos != std::string::npos )
			{
				std::cerr << "found " << pos << std::endl;
				pos += 1;
			}
		}
	}

	return 0;

	testLazyFailureFunctionRandom("abaabaababaabab");
	testLazyFailureFunctionRandom("alabar_a_la_alabarda");
	#endif
}
Example #26
0
void tql2(matrix_base<SCALARTYPE, F> & Q,
          VectorType & d,
          VectorType & e)
{
    vcl_size_t n = static_cast<vcl_size_t>(viennacl::traits::size1(Q));

    //boost::numeric::ublas::vector<SCALARTYPE> cs(n), ss(n);
    std::vector<SCALARTYPE> cs(n), ss(n);
    viennacl::vector<SCALARTYPE> tmp1(n), tmp2(n);

    for (vcl_size_t i = 1; i < n; i++)
        e[i - 1] = e[i];

    e[n - 1] = 0;

    SCALARTYPE f = 0;
    SCALARTYPE tst1 = 0;
    SCALARTYPE eps = static_cast<SCALARTYPE>(viennacl::linalg::detail::EPS);

    for (vcl_size_t l = 0; l < n; l++)
    {
        // Find small subdiagonal element.
        tst1 = std::max<SCALARTYPE>(tst1, std::fabs(d[l]) + std::fabs(e[l]));
        vcl_size_t m = l;
        while (m < n)
        {
            if (std::fabs(e[m]) <= eps * tst1)
                break;
            m++;
        }

        // If m == l, d[l) is an eigenvalue, otherwise, iterate.
        if (m > l)
        {
            vcl_size_t iter = 0;
            do
            {
                iter = iter + 1;  // (Could check iteration count here.)

                // Compute implicit shift
                SCALARTYPE g = d[l];
                SCALARTYPE p = (d[l + 1] - g) / (2 * e[l]);
                SCALARTYPE r = viennacl::linalg::detail::pythag<SCALARTYPE>(p, 1);
                if (p < 0)
                {
                    r = -r;
                }

                d[l] = e[l] / (p + r);
                d[l + 1] = e[l] * (p + r);
                SCALARTYPE dl1 = d[l + 1];
                SCALARTYPE h = g - d[l];
                for (vcl_size_t i = l + 2; i < n; i++)
                {
                    d[i] -= h;
                }

                f = f + h;

                // Implicit QL transformation.
                p = d[m];
                SCALARTYPE c = 1;
                SCALARTYPE c2 = c;
                SCALARTYPE c3 = c;
                SCALARTYPE el1 = e[l + 1];
                SCALARTYPE s = 0;
                SCALARTYPE s2 = 0;
                for (int i = int(m - 1); i >= int(l); i--)
                {
                    c3 = c2;
                    c2 = c;
                    s2 = s;
                    g = c * e[vcl_size_t(i)];
                    h = c * p;
                    r = viennacl::linalg::detail::pythag(p, e[vcl_size_t(i)]);
                    e[vcl_size_t(i) + 1] = s * r;
                    s = e[vcl_size_t(i)] / r;
                    c = p / r;
                    p = c * d[vcl_size_t(i)] - s * g;
                    d[vcl_size_t(i) + 1] = h + s * (c * g + s * d[vcl_size_t(i)]);


                    cs[vcl_size_t(i)] = c;
                    ss[vcl_size_t(i)] = s;
                }


                p = -s * s2 * c3 * el1 * e[l] / dl1;
                e[l] = s * p;
                d[l] = c * p;

                viennacl::copy(cs, tmp1);
                viennacl::copy(ss, tmp2);

                viennacl::linalg::givens_next(Q, tmp1, tmp2, int(l), int(m));

                // Check for convergence.
            }
            while (std::fabs(e[l]) > eps * tst1);
        }
        d[l] = d[l] + f;
        e[l] = 0;
    }

    // Sort eigenvalues and corresponding vectors.
/*
       for (int i = 0; i < n-1; i++) {
          int k = i;
          SCALARTYPE p = d[i];
          for (int j = i+1; j < n; j++) {
             if (d[j] > p) {
                k = j;
                p = d[j);
             }
          }
          if (k != i) {
             d[k] = d[i];
             d[i] = p;
             for (int j = 0; j < n; j++) {
                p = Q(j, i);
                Q(j, i) = Q(j, k);
                Q(j, k) = p;
             }
          }
       }

*/

}
Example #27
0
static inline long rs(root_block *root){
  if(!root)return(-1);
  if(!root->vector)return(-1);
  return(cs(root->vector));
}
Example #28
0
void nmethod::flush() {
  BlockProfilerTicks bpt(exclude_nmethod_flush);
  CSect cs(profilerSemaphore);          // for profiler
# if GENERATE_DEBUGGING_AIDS
    if (CheckAssertions) {
      // for debugging
      if (nmethodFlushCount  &&  --nmethodFlushCount == 0)
        warning("nmethodFlushCount");
      if (this == (nmethod*)catchThisOne) warning("caught nmethod");
    }
# endif
  
  // EventMarker em("flushing nmethod %#lx %s", this, "");
  if (PrintMethodFlushing) {
    ResourceMark m;
    char *compilerName = VMString[compiler()]->copy_null_terminated();
    lprintf("*flushing %s%s%s-nmethod 0x%lx %d\t(",
           isZombie() ? "zombie " : "", 
           isAccess() ? "access " : "",
           compilerName, (void*)(long unsigned)this, (void*)useCount[id]);
    printName(0, key.selector);
    lprintf(")");
  }

  // always check the following - tests are really cheap
  if (flags.flushed) fatal1("nmethod %#lx already flushed", this);
  if (zone::frame_chain_nesting == 0) fatal("frames must be chained when flushing");

  if (frame_chain != NoFrameChain) {
    // Can't remove an nmethod from deps chains now, because later
    // programming changes may need to invalidate it.
    // That is, don't unlink() now.
   
    // See comment for makeZombie routine. The comment above is the 
    // "original comment" referred to there.
    // -- dmu 1/12/03

    if (this == recompilee) {
      // nmethod is being recompiled; cannot really flush yet
      // em.event.args[1] = "(being recompiled)";
      if (PrintMethodFlushing) {
        lprintf(" (being recompiled)\n");
      }
    } else {
      // nmethod is currently being executed; cannot flush yet
      // em.event.args[1] = "(currently active)";
      if (PrintMethodFlushing) {
        lprintf(" (currently active)\n");
      }
    }
    makeZombie(false);
  } else {
    unlink();
  
    // nmethod is not being executed; completely throw away
    // em.event.args[1] = "(not currently active)";
    if (PrintMethodFlushing) {
      lprintf("\n");
    }
    flatProfiler->flush((char*)this, instsEnd());
    zoneLink.remove();
    rememberLink.remove();
    for (addrDesc* p = locs(), *pend = locsEnd(); p < pend; p++) {
      if (p->isSendDesc()) {
        p->asSendDesc(this)->unlink();
      } else if (p->isDIDesc()) {
        p->asDIDesc(this)->dependency()->flush();
      }
    }
    flags.flushed = 1;                        // to detect flushing errors
#   if GENERATE_DEBUGGING_AIDS
    if (CheckAssertions) {
      set_oops((oop*)insts(), instsLen()/oopSize, 0); // for quicker detection
    }
#   endif
    Memory->code->free_nmethod(this);
  }
  MachineCache::flush_instruction_cache_for_debugging();
}
Example #29
0
 void Unlock() {
    CriticalSection cs(&_mutex);
    _u._a._lock = 0;
 }
Example #30
0
    void run() {
        // Run the update.
        {
            Client::WriteContext ctx(&_txn, ns());

            // Populate the collection.
            for (int i = 0; i < 10; ++i) {
                insert(BSON("_id" << i << "foo" << i));
            }
            ASSERT_EQUALS(10U, count(BSONObj()));

            Client& c = cc();
            CurOp& curOp = *c.curop();
            OpDebug* opDebug = &curOp.debug();
            UpdateDriver driver( (UpdateDriver::Options()) );
            Database* db = ctx.ctx().db();
            Collection* coll = db->getCollection(&_txn, ns());

            // Get the DiskLocs that would be returned by an in-order scan.
            vector<DiskLoc> locs;
            getLocs(coll, CollectionScanParams::FORWARD, &locs);

            UpdateRequest request(&_txn, nsString());
            UpdateLifecycleImpl updateLifecycle(false, nsString());
            request.setLifecycle(&updateLifecycle);

            // Update is a multi-update that sets 'bar' to 3 in every document
            // where foo is less than 5.
            BSONObj query = fromjson("{foo: {$lt: 5}}");
            BSONObj updates = fromjson("{$set: {bar: 3}}");

            request.setMulti();
            request.setQuery(query);
            request.setUpdates(updates);

            ASSERT_OK(driver.parse(request.getUpdates(), request.isMulti()));

            // Configure the scan.
            CollectionScanParams collScanParams;
            collScanParams.collection = coll;
            collScanParams.direction = CollectionScanParams::FORWARD;
            collScanParams.tailable = false;

            // Configure the update.
            UpdateStageParams updateParams(&request, &driver, opDebug);
            scoped_ptr<CanonicalQuery> cq(canonicalize(query));
            updateParams.canonicalQuery = cq.get();

            scoped_ptr<WorkingSet> ws(new WorkingSet());
            auto_ptr<CollectionScan> cs(
                new CollectionScan(&_txn, collScanParams, ws.get(), cq->root()));

            scoped_ptr<UpdateStage> updateStage(
                new UpdateStage(updateParams, ws.get(), db, cs.release()));

            const UpdateStats* stats =
                static_cast<const UpdateStats*>(updateStage->getSpecificStats());

            const size_t targetDocIndex = 3;

            while (stats->nModified < targetDocIndex) {
                WorkingSetID id = WorkingSet::INVALID_ID;
                PlanStage::StageState state = updateStage->work(&id);
                ASSERT_EQUALS(PlanStage::NEED_TIME, state);
            }

            // Remove locs[targetDocIndex];
            updateStage->saveState();
            updateStage->invalidate(locs[targetDocIndex], INVALIDATION_DELETION);
            BSONObj targetDoc = coll->docFor(&_txn, locs[targetDocIndex]);
            ASSERT(!targetDoc.isEmpty());
            remove(targetDoc);
            updateStage->restoreState(&_txn);

            // Do the remaining updates.
            while (!updateStage->isEOF()) {
                WorkingSetID id = WorkingSet::INVALID_ID;
                PlanStage::StageState state = updateStage->work(&id);
                ASSERT(PlanStage::NEED_TIME == state || PlanStage::IS_EOF == state);
            }

            ctx.commit();

            // 4 of the 5 matching documents should have been modified (one was deleted).
            ASSERT_EQUALS(4U, stats->nModified);
            ASSERT_EQUALS(4U, stats->nMatched);
        }

        // Check the contents of the collection.
        {
            Client::ReadContext ctx(&_txn, ns());
            Collection* collection = ctx.ctx().db()->getCollection(&_txn, ns());

            vector<BSONObj> objs;
            getCollContents(collection, &objs);

            // Verify that the collection now has 9 docs (one was deleted).
            ASSERT_EQUALS(9U, objs.size());

            // Make sure that the collection has certain documents.
            assertHasDoc(objs, fromjson("{_id: 0, foo: 0, bar: 3}"));
            assertHasDoc(objs, fromjson("{_id: 1, foo: 1, bar: 3}"));
            assertHasDoc(objs, fromjson("{_id: 2, foo: 2, bar: 3}"));
            assertHasDoc(objs, fromjson("{_id: 4, foo: 4, bar: 3}"));
            assertHasDoc(objs, fromjson("{_id: 5, foo: 5}"));
            assertHasDoc(objs, fromjson("{_id: 6, foo: 6}"));
        }
    }