void Foam::cyclicGgiPolyPatch::checkDefinition() const
{
    // A little bit of sanity check The rotation angle/axis is
    // specified in both the master and slave patch of the
    // cyclicGgi.  This is a pain, but the other alternatives
    // would be:
    //
    //   - Specify in only of the two patches boundary
    //   definition : - which one to chose?  - which default
    //   value to chose for the non-initialized value - Use a
    //   specific dictionary for this... Nope, too cumbersome.
    //
    // So, we impose that the boundary definition of both
    // patches must specify the same information If not, well,
    // we stop the simulation and ask for a fix.

    if (!active())
    {
        // No need to check anything, the shadow is not initialized properly.
        // This will happen with blockMesh when defining cyclicGGI patches.
        // Return quietly
        return;
    }

    if
    (
        (mag(rotationAngle()) - mag(cyclicShadow().rotationAngle())) > SMALL
     || cmptSum(rotationAxis() - cyclicShadow().rotationAxis()) > SMALL
    )
    {
        FatalErrorIn("void cyclicGgiPolyPatch::check() const")
            << "    Rotation angle for patch name           : "
            << name() << " is: " << rotationAngle()
            << " axis: " << rotationAxis() << nl
            << "    Rotation angle for shadow patch name: "
            << shadowName() << " is: "
            << cyclicShadow().rotationAngle() << " axis: "
            << cyclicShadow().rotationAxis() << nl
            << "    Both values need to be opposite in "
            << "the boundary file. "
            << abort(FatalError);
    }

    if
    (
        (mag(separationOffset() + cyclicShadow().separationOffset())) > SMALL
    )
    {
        FatalErrorIn("void cyclicGgiPolyPatch::check() const")
            << "Separation offset for patch name           : "
            << name() << " is: " << separationOffset()
            << "    Separation offset for shadow patch name: "
            << shadowName() << " is: "
            << cyclicShadow().separationOffset() << " axis: "
            << "    Both values need to be opposite in "
            << "the boundary file. "
            << abort(FatalError);
    }

    if (debug > 1 && master())
    {
        Info<< "Writing transformed slave patch as VTK." << nl
            << "Master: " << name()
            << " Slave: " << shadowName()
            << " Angle (master to slave): " << rotationAngle() << " deg"
            << " Axis: " << rotationAxis()
            << " Separation: " << separationOffset() << endl;

            const polyMesh& mesh = boundaryMesh().mesh();

            fileName fvPath(mesh.time().path()/"VTK");
            mkDir(fvPath);

            pointField transformedPoints = cyclicShadow().localPoints();

            tensor rot = RodriguesRotation(rotationAxis_,  -rotationAngle_);

            transform(transformedPoints, rot, transformedPoints);

            // Add separation offset to transformed points.  HJ, 24/Nov/2009
            transformedPoints += cyclicShadow().separationOffset();

            standAlonePatch::writeVTK
            (
                fvPath/fileName("cyclicGgi" + name() + cyclicShadow().name()),
                cyclicShadow().localFaces(),
                transformedPoints
            );
    }
}
Example #2
0
    Status ProjectionExec::transform(WorkingSetMember* member) const {
        if (_hasReturnKey) {
            BSONObj keyObj;

            if (member->hasComputed(WSM_INDEX_KEY)) {
                const IndexKeyComputedData* key
                    = static_cast<const IndexKeyComputedData*>(member->getComputed(WSM_INDEX_KEY));
                keyObj = key->getKey();
            }

            member->state = WorkingSetMember::OWNED_OBJ;
            member->obj = keyObj;
            member->keyData.clear();
            member->loc = DiskLoc();
            return Status::OK();
        }

        BSONObjBuilder bob;
        if (!requiresDocument()) {
            // Go field by field.
            if (_includeID) {
                BSONElement elt;
                // Sometimes the _id field doesn't exist...
                if (member->getFieldDotted("_id", &elt) && !elt.eoo()) {
                    bob.appendAs(elt, "_id");
                }
            }

            BSONObjIterator it(_source);
            while (it.more()) {
                BSONElement specElt = it.next();
                if (mongoutils::str::equals("_id", specElt.fieldName())) {
                    continue;
                }

                BSONElement keyElt;
                // We can project a field that doesn't exist.  We just ignore it.
                if (member->getFieldDotted(specElt.fieldName(), &keyElt) && !keyElt.eoo()) {
                    bob.appendAs(keyElt, specElt.fieldName());
                }
            }
        }
        else {
            // Planner should have done this.
            verify(member->hasObj());

            MatchDetails matchDetails;

            // If it's a positional projection we need a MatchDetails.
            if (transformRequiresDetails()) {
                matchDetails.requestElemMatchKey();
                verify(NULL != _queryExpression);
                verify(_queryExpression->matchesBSON(member->obj, &matchDetails));
            }

            Status projStatus = transform(member->obj, &bob, &matchDetails);
            if (!projStatus.isOK()) {
                return projStatus;
            }
        }

        for (MetaMap::const_iterator it = _meta.begin(); it != _meta.end(); ++it) {
            if (META_GEONEAR_DIST == it->second) {
                if (member->hasComputed(WSM_COMPUTED_GEO_DISTANCE)) {
                    const GeoDistanceComputedData* dist
                        = static_cast<const GeoDistanceComputedData*>(
                                member->getComputed(WSM_COMPUTED_GEO_DISTANCE));
                    bob.append(it->first, dist->getDist());
                }
                else {
                    return Status(ErrorCodes::InternalError,
                                  "near loc dist requested but no data available");
                }
            }
            else if (META_GEONEAR_POINT == it->second) {
                if (member->hasComputed(WSM_GEO_NEAR_POINT)) {
                    const GeoNearPointComputedData* point
                        = static_cast<const GeoNearPointComputedData*>(
                                member->getComputed(WSM_GEO_NEAR_POINT));
                    BSONObj ptObj = point->getPoint();
                    if (ptObj.couldBeArray()) {
                        bob.appendArray(it->first, ptObj);
                    }
                    else {
                        bob.append(it->first, ptObj);
                    }
                }
                else {
                    return Status(ErrorCodes::InternalError,
                                  "near loc proj requested but no data available");
                }
            }
            else if (META_TEXT_SCORE == it->second) {
                if (member->hasComputed(WSM_COMPUTED_TEXT_SCORE)) {
                    const TextScoreComputedData* score
                        = static_cast<const TextScoreComputedData*>(
                                member->getComputed(WSM_COMPUTED_TEXT_SCORE));
                    bob.append(it->first, score->getScore());
                }
                else {
                    bob.append(it->first, 0.0);
                }
            }
            else if (META_DISKLOC == it->second) {
                bob.append(it->first, member->loc.toBSONObj());
            }
        }

        BSONObj newObj = bob.obj();
        member->state = WorkingSetMember::OWNED_OBJ;
        member->obj = newObj;
        member->keyData.clear();
        member->loc = DiskLoc();

        return Status::OK();
    }
Example #3
0
void CurrentApp::Update(float dt)
{
	//Update the camera for movement
	m_camera->Update(dt);
	m_particleEmitter->update(dt);

	glm::vec3 pos = glm::vec3(100 * cos(CurrentTime() * 0.05f) + 150, 80, 100 * sin(CurrentTime() * 0.05f) + 150);
	m_fairyEmitter->SetPosition(pos);
	m_light->SetPosition(pos);

	for (int i = 0; i < 5; ++i)
	{
		m_AI[i]->update(dt);
	}

	Input* IM = Input::GetInstance();

	glm::mat4 cameraWorld = m_camera->GetTransform();
	PxVec3 displacement = PxVec3(0, 0, 0);
	bool notZero = false;
	bool m_canFly = false;

	if (IM->IsKeyDown('W'))
	{
		displacement -= PxVec3(cameraWorld[2].x, (m_canFly ? cameraWorld[2].y : 0), cameraWorld[2].z);
		notZero = true;
	}
	if (IM->IsKeyDown('A'))
	{
		displacement -= PxVec3(cameraWorld[0].x, (m_canFly ? cameraWorld[0].y : 0), cameraWorld[0].z);
		notZero = true;
	}
	if (IM->IsKeyDown('S'))
	{
		displacement += PxVec3(cameraWorld[2].x, (m_canFly ? cameraWorld[2].y : 0), cameraWorld[2].z);
		notZero = true;
	}
	if (IM->IsKeyDown('D'))
	{
		displacement += PxVec3(cameraWorld[0].x, (m_canFly ? cameraWorld[0].y : 0), cameraWorld[0].z);
		notZero = true;
	}

	if (notZero)
		displacement = displacement.getNormalized();

	if (m_verticleSpeed > -10.0f && !m_canFly || m_verticleSpeed > 0 && m_canFly)
		m_verticleSpeed -= dt;

	displacement.y += m_verticleSpeed;

	PxControllerFilters filters;
	g_PlayerController->move(displacement, 0.01f, dt, filters);

	PxExtendedVec3 playerPos = g_PlayerController->getPosition();
	PxExtendedVec3 footPos = g_PlayerController->getFootPosition();
	//I do these calculations individually inside this vector constructor because PxEtendedVec3 doesn't contain some of the necessary operators to do this.
	vec3 endPos = vec3(2.0f * playerPos.x - footPos.x, 2.0f * playerPos.y - footPos.y, 2.0f * playerPos.z - footPos.z);
	m_camera->SetPosition(endPos);

	//Freeze the physics
	if (m_freezePhysics == false) 
	{ 
		UpdatePhysx(dt); 
	}
	else 
	{ 
		UpdatePhysx(0); 
	}

	//Generate new map
	if (Input::GetInstance()->IsKeyPressed('R'))
	{
		m_terrain->GenerateFromPerlin();
		m_terrain->AddPhysicsShape(g_PhysicsScene, g_Physics);
		m_nodeMap->GenerateFromTerrain(m_terrain);
		m_world->Generate();

		for (unsigned int i = 0; i < g_PhysXActors.size(); ++i)
		{
			PxTransform transform(PxVec3(150, 5 + (1.1f * i), 150));
			g_PhysXActors[i]->setGlobalPose(transform);
		}
	}

	if (Input::GetInstance()->IsKeyPressed('N'))
	{
		m_nodeMap->GenerateFromTerrain(m_terrain);
		m_nodeMap->Draw();
	}

	//Freeze Physics
	if (Input::GetInstance()->IsKeyPressed(GLFW_KEY_PAUSE)) { m_freezePhysics = !m_freezePhysics; }

	//Hide/Show Cursor
	if (Input::GetInstance()->IsKeyPressed(KEY_ESCAPE)) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); }
	if (Input::GetInstance()->IsMousePressed(MOUSE_BUTTON_LEFT)) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); }

	//Deffered/Forward
	if (Input::GetInstance()->IsKeyPressed(KEY_F5)) { m_isDeffered = !m_isDeffered; }
	if (Input::GetInstance()->IsKeyPressed(KEY_F6)) { m_drawDebug = !m_drawDebug; }
}
Example #4
0
vector<T> operator-(vector<T> v) {
  transform(begin(v), end(v), begin(v), [](T n){ return -n; });
  return v;
}
Example #5
0
void Foam::solidParticle::transformProperties (const tensor& T)
{
    particle::transformProperties(T);
    U_ = transform(T, U_);
}
Example #6
0
inline string& Lower(string& str) {
  transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);
  return str;
}
Example #7
0
IString IString::upperCase(){
	std::string s = this->c_str();
	transform( s.begin(), s.end(), s.begin(), ::toupper );
	return IString(s.c_str());
}
Example #8
0
void Path::translate(const FloatSize& size)
{
    AffineTransform transformation;
    transformation.translate(size.width(), size.height());
    transform(transformation);
}
Example #9
0
void starnt::dictionary::load(const std::wstring file)
{	
	if( !dict.empty())
		if(file == dict_file)
			return;
		else
			dict.clear();
	
	char* word;
	[&file, &word]()->void
	{	
		#if defined _WIN32
			HANDLE FileIn;
			FileIn = CreateFileW( file.c_str(),GENERIC_READ ,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
			if (FileIn == INVALID_HANDLE_VALUE) 
				return;
			LARGE_INTEGER len;
			GetFileSizeEx(FileIn, &len);
			word = new char[len.LowPart + 1];
			DWORD count;
			ReadFile(FileIn, word, len.LowPart, &count, NULL);
			if(count != len.LowPart)
				return;

			word[len.LowPart] = '\0';
			CloseHandle(FileIn);
		#else
			// nix version
		#endif
	}();

	//load individual words into strings
	std::pair<std::string, std::string> dict_entry;	
	char* wordtok;
	wordtok = strtok(word, "\n");
	for(int j = 0 ; wordtok != NULL ; j++ , wordtok = strtok(NULL, "\n"))
	{
		if(type == 1)
		{	// encode
			dict_entry.first = wordtok;		// the word
			transform(j, dict_entry.second);	// code
		}
		else
		{	//decode	
			transform(j, dict_entry.first);	// code
			dict_entry.second = wordtok;		// the word
		}
		dict.insert( dict_entry );	
	}



	// replace LF with \0
/*	for(size_t i=0; i < len ; i++)
	{
		while( (word[i] != '\n') && i < len)
			i++;
		word[i] = '\0';
	}

	// then load individual words into strings
	std::pair<std::string, std::string> dict_entry;

	dict_entry.first= &word[0];
	dict_entry.second = "a";
	dict.insert( dict_entry );
	
	for(int i = 2, j = 1 ; i < len ; i++,j++)
	{
		while(word[i] != '\0')
			i++;
		i++;
		if( i <len)
		{	
			dict_entry.first = &word[i];		// the word
			dict_entry.second = transform(j);	// code

			dict.insert( dict_entry );	
		}
		else
			break;
	}
*/

	delete [] word;

}
Example #10
0
Matrix Matrix::rotation(Vec3f &rotation, Vec3f &pivot)
{
    return transform(-pivot) * Matrix::rotation(rotation) * transform(pivot);
}
Example #11
0
void TestFunctors (void)
{
    vector<int> v;
    v.resize (20);
    fill (v, 2);
    foreach (vector<int>::iterator, i, v)
        *i -= distance(v.begin(), i) & 1;
    vector<int> v1 (v);

    cout << "start:\t\t\t";
    PrintVector (v);

    v = v1;
    cout << "plus:\t\t\t";
    transform (v, v.begin(), v.begin(), plus<int>());
    PrintVector (v);

    v = v1;
    cout << "minus:\t\t\t";
    transform (v, v.begin(), v.begin(), minus<int>());
    PrintVector (v);

    v = v1;
    cout << "divides:\t\t";
    transform (v, v.begin(), v.begin(), divides<int>());
    PrintVector (v);

    v = v1;
    cout << "multiplies:\t\t";
    transform (v, v.begin(), v.begin(), multiplies<int>());
    PrintVector (v);

    v = v1;
    cout << "modulus:\t\t";
    transform (v, v.begin(), v.begin(), modulus<int>());
    PrintVector (v);

    v = v1;
    cout << "logical_and:\t\t";
    transform (v, v.begin(), v.begin(), logical_and<int>());
    PrintVector (v);

    v = v1;
    cout << "logical_or:\t\t";
    transform (v, v.begin(), v.begin(), logical_or<int>());
    PrintVector (v);

    v = v1;
    cout << "equal_to:\t\t";
    transform (v, v.begin(), v.begin(), equal_to<int>());
    PrintVector (v);

    v = v1;
    cout << "not_equal_to:\t\t";
    transform (v, v.begin(), v.begin(), not_equal_to<int>());
    PrintVector (v);

    v = v1;
    cout << "greater:\t\t";
    transform (v, v.begin(), v.begin(), greater<int>());
    PrintVector (v);

    v = v1;
    cout << "less:\t\t\t";
    transform (v, v.begin(), v.begin(), less<int>());
    PrintVector (v);

    v = v1;
    cout << "greater_equal:\t\t";
    transform (v, v.begin(), v.begin(), greater_equal<int>());
    PrintVector (v);

    v = v1;
    cout << "less_equal:\t\t";
    transform (v, v.begin(), v.begin(), less_equal<int>());
    PrintVector (v);

    v = v1;
    cout << "compare:\t\t";
    transform (v, v.begin(), v.begin(), compare<int>());
    PrintVector (v);

    v = v1;
    cout << "negate:\t\t\t";
    transform (v, negate<int>());
    PrintVector (v);

    v = v1;
    cout << "logical_not:\t\t";
    transform (v, logical_not<int>());
    PrintVector (v);

    v = v1;
    cout << "unary_neg(negate):\t";
    transform (v, unary_negator(negate<int>()));
    PrintVector (v);

    v = v1;
    cout << "binder1st(plus,5):\t";
    transform (v, bind1st(plus<int>(), 5));
    PrintVector (v);

    v = v1;
    cout << "binder2nd(minus,1):\t";
    transform (v, bind2nd(minus<int>(), 1));
    PrintVector (v);

    v = v1;
    cout << "compose1(-,+5):\t\t";
    transform (v, compose1 (negate<int>(), bind2nd(plus<int>(), 5)));
    PrintVector (v);

    v = v1;
    cout << "compose1(-,-4):\t\t";
    transform (v, compose1 (negate<int>(), bind2nd(minus<int>(), 4)));
    PrintVector (v);

    v = v1;
    cout << "compose2(/,+6,-4):\t";
    transform (v, compose2 (divides<int>(), bind2nd(plus<int>(), 6), bind2nd(minus<int>(), 4)));
    PrintVector (v);

    cout << "mem_var(plus,6):\t";
    vector<A> av;
    for (uoff_t i = 0; i < 20; ++ i)
        av.push_back (A(i));
    transform (av, mem_var1(&A::m_v, bind2nd(plus<int>(), 6)));
    PrintVector (av);

    vector<A>::iterator found = find_if (av, mem_var_equal_to(&A::m_v, 14));
    cout << "14 found at position " << found - av.begin() << endl;
    found = lower_bound (av.begin(), av.end(), 18, mem_var_less(&A::m_v));
    cout << "18 found at position " << found - av.begin() << endl;

    cout << "add next:\t\t";
    transform (av.begin(), av.end() - 1, av.begin() + 1, av.begin(), mem_var2(&A::m_v, plus<int>()));
    PrintVector (av);
}
Example #12
0
Matrix Matrix::transform(const Vec3f &offset)
{
    return transform(offset.x, offset.y, offset.z);
}
Example #13
0
Matrix Matrix::scale(Vec3f &scale, Vec3f &pivot)
{
    return transform(-pivot) * Matrix::scale(scale) * transform(pivot);
}
void GraphicsLayerTextureMapper::commitLayerChanges()
{
    if (m_changeMask == NoChanges)
        return;

    if (m_changeMask & ChildrenChange)
        m_layer.setChildren(children());

    if (m_changeMask & MaskLayerChange)
        m_layer.setMaskLayer(&downcast<GraphicsLayerTextureMapper>(maskLayer())->layer());

    if (m_changeMask & ReplicaLayerChange)
        m_layer.setReplicaLayer(&downcast<GraphicsLayerTextureMapper>(replicaLayer())->layer());

    if (m_changeMask & PositionChange)
        m_layer.setPosition(position());

    if (m_changeMask & AnchorPointChange)
        m_layer.setAnchorPoint(anchorPoint());

    if (m_changeMask & SizeChange)
        m_layer.setSize(size());

    if (m_changeMask & TransformChange)
        m_layer.setTransform(transform());

    if (m_changeMask & ChildrenTransformChange)
        m_layer.setChildrenTransform(childrenTransform());

    if (m_changeMask & Preserves3DChange)
        m_layer.setPreserves3D(preserves3D());

    if (m_changeMask & ContentsRectChange)
        m_layer.setContentsRect(contentsRect());

    if (m_changeMask & MasksToBoundsChange)
        m_layer.setMasksToBounds(masksToBounds());

    if (m_changeMask & DrawsContentChange)
        m_layer.setDrawsContent(drawsContent());

    if (m_changeMask & ContentsVisibleChange)
        m_layer.setContentsVisible(contentsAreVisible());

    if (m_changeMask & ContentsOpaqueChange)
        m_layer.setContentsOpaque(contentsOpaque());

    if (m_changeMask & BackfaceVisibilityChange)
        m_layer.setBackfaceVisibility(backfaceVisibility());

    if (m_changeMask & OpacityChange)
        m_layer.setOpacity(opacity());

    if (m_changeMask & BackgroundColorChange)
        m_layer.setSolidColor(m_solidColor);

    if (m_changeMask & FilterChange)
        m_layer.setFilters(filters());

    if (m_changeMask & BackingStoreChange)
        m_layer.setBackingStore(m_backingStore);

    if (m_changeMask & DebugVisualsChange)
        m_layer.setDebugVisuals(isShowingDebugBorder(), debugBorderColor(), debugBorderWidth(), isShowingRepaintCounter());

    if (m_changeMask & RepaintCountChange)
        m_layer.setRepaintCount(repaintCount());

    if (m_changeMask & ContentChange)
        m_layer.setContentsLayer(platformLayer());

    if (m_changeMask & AnimationChange)
        m_layer.setAnimations(m_animations);

    if (m_changeMask & AnimationStarted)
        client().notifyAnimationStarted(this, "", m_animationStartTime);

    if (m_changeMask & FixedToViewporChange)
        m_layer.setFixedToViewport(fixedToViewport());

    if (m_changeMask & IsScrollableChange)
        m_layer.setIsScrollable(isScrollable());

    if (m_changeMask & CommittedScrollOffsetChange)
        m_layer.didCommitScrollOffset(m_committedScrollOffset);

    m_changeMask = NoChanges;
}
Example #15
0
void CRegionalMetaModel::Predict( const REAL* prInputs, REAL* prOutputs )
{
	vector< CTrustRegion* >hitRegions;

	//best region or multiple region?
	FindTrustRegions( prInputs, hitRegions );
//	FindBestRegion( prInputs, hitRegions );

	int nOutputs = GetOutputs();
	int nHitRegions = hitRegions.size();
	//for each trusted regional model, predict the result to vcOutputs[i][1...nOutputs]
	vector< vector<REAL> > vcOutputs(nHitRegions);
	for( int i=0; i<nHitRegions; i++ ){
		vcOutputs[i].resize( nOutputs );
		CMetaModel* pModel = m_vcMetaModels[ hitRegions[i]->GetModelId() ];
		pModel->Predict( prInputs, &vcOutputs[i][0] );
	}

	int nInputs = GetInputs();
	REAL rSumWeights = 0;
	vector< REAL > vcSum( nOutputs, 0.0 );
	//modified on 02/012/05 using trust probability
	for( i=0; i<nHitRegions; i++ ){
		ASSERT( nInputs==hitRegions[i]->m_ptCen.size() );
		vector<REAL> vcDistSqr(nInputs, 0.0);
		vector<REAL> vcRadSqr(nInputs, 0.0);
		vector<REAL> vcProbs(nInputs,0.0);
		transform( prInputs, prInputs+nInputs, hitRegions[i]->m_ptCen.begin(), vcDistSqr.begin(), diff_sqr<REAL>() );
//		cout<<"dist sqr:";
//		copy( vcDistSqr.begin(), vcDistSqr.end(), ostream_iterator<REAL>(cout, " ") ); cout<<endl;
		transform( hitRegions[i]->m_vcRadius.begin(), hitRegions[i]->m_vcRadius.end(), hitRegions[i]->m_vcRadius.begin(), vcRadSqr.begin(), multiplies<REAL>() );
//		cout<<"radius sqr:";
//		copy( vcRadSqr.begin(), vcRadSqr.end(), ostream_iterator<REAL>(cout, " ") ); cout<<endl;
		transform( vcDistSqr.begin(), vcDistSqr.end(), vcRadSqr.begin(), vcProbs.begin(), divides<REAL>() );
//		cout<<"probs :";
//		copy( vcProbs.begin(), vcProbs.end(), ostream_iterator<REAL>(cout, " ") ); cout<<endl;
		REAL rProb = accumulate( vcProbs.begin(), vcProbs.end(), 0.0) / nInputs;
		rProb = max( 1-rProb, 0.0 );

		cdump<<"prob "<<i<<" "<<rProb<<"\t";

		REAL rWeight = rProb / hitRegions[i]->GetSphereRadius();
		for( int j=0; j<nOutputs; j++ ){
			vcSum[j] += vcOutputs[i][j]*rWeight;
		}
		rSumWeights += rWeight;
	}
	if( rSumWeights > 0 ){
		transform( vcSum.begin(), vcSum.end(), vcSum.begin(), bind2nd(divides<REAL>(), rSumWeights) );
		copy( vcSum.begin(), vcSum.end(), prOutputs );
	}else{
		copy( vcOutputs[0].begin(), vcOutputs[0].end(), prOutputs );
	}

	//compute the average outputs according to inverse sphere radius
/*	vector< REAL > vcSum( nOutputs, 0.0 );
	REAL rSumInvRadius = 0;
	for( i=0; i<nHitRegions; i++ ){
		REAL rInvRadius = 1.0 / hitRegions[i]->GetSphereRadius();
		for( int j=0; j<nOutputs; j++ ){
			vcSum[j] += vcOutputs[i][j]*rInvRadius;
		}
		rSumInvRadius += rInvRadius;
	}
	transform( vcSum.begin(), vcSum.end(), vcSum.begin(), bind2nd(divides<REAL>(), rSumInvRadius) );
	copy( vcSum.begin(), vcSum.end(), prOutputs );
*/
	cdump<<"pred..."<<nHitRegions<<" nets"<<endl;
}
Example #16
0
int main (int argc, const char * argv[])
{
    std::string listFileName, pcdFileName;
    std::string pcdFileFullName, shotFileFullName;
    std::string pcdFilePath, outputFileName, shotDir;
    std::string kernelType, kernelSize;
    fstream outputFile, listFile, shotFile;

    //argument processing
    if (argc < 5)
    {
        std::cout << "shotFeature: Extracts SHOT features from pdc file." << endl << "Usage:" << endl << "shotFeature listFile outputFile kernelSizeType kernelSize [loadPathPrefix] [saveDirectory]" << endl;
        std::cout << "listFile is the name of file that contains the list of input pointcloud files" << endl;
        std::cout << "outputFile is the name of file where the extracted features will be saved" << endl;
        std::cout << "kernelType : possible values are: metric , knn" << endl;
        std::cout << "kernelSize: size of the kernel, depending on the kernelType it might be either in cm for metric or k for knn" << endl;
        std::cout << "[loadPathPrefix]: path prefix for loading pcd files";
        std::cout << "[saveDirectory]: path prefix of destination directory for saving individual feature files separately.";
        return 0;
    }
    
    listFileName = argv[1];
    outputFileName = argv[2];
    kernelType = argv[3];
    kernelSize = argv[4];
    
    if (argc > 5) { pcdFilePath = argv[5]; }
    if (argc > 6) { shotDir = argv[6]; }
    
    transform (kernelType.begin (), kernelType.end (), kernelType.begin (), (int(*)(int)) tolower);
    
    if ( (kernelType.compare("metric") != 0) && (kernelType.compare("knn") != 0) )
    {
        cout << "Error: Invalid kernelType:" << kernelType << endl;
        return -1;
    }
    
    outputFile.open(outputFileName.c_str(), ios::out);
    listFile.open(listFileName.c_str(), ios::in);
    
    while (!listFile.eof())
    {
        pcl::PointCloud<pcl::PointXYZ>::Ptr cloudIn (new pcl::PointCloud<pcl::PointXYZ>);
        pcl::SHOTEstimation<pcl::PointXYZ,pcl::Normal,pcl::SHOT> shotExtractor;
        pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
        pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZ> ());
        pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree2 (new pcl::KdTreeFLANN<pcl::PointXYZ> ());
        pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
        pcl::PointCloud<pcl::SHOT>::Ptr cloudShot (new pcl::PointCloud<pcl::SHOT> ());
        
        listFile >> pcdFileName;
        cout << "Loading file:" << pcdFileName << endl;
        
        if (argc > 5) { pcdFileFullName = pcdFilePath + "/" + pcdFileName; }
        else { pcdFileFullName = pcdFileName; }
        
        //loading pcd file
        pcl::io::loadPCDFile (pcdFileFullName, *cloudIn);
        
        //estimating input normals
        cout << "calculating normal…" << endl;
        ne.setInputCloud (cloudIn);
        ne.setSearchMethod (tree);
        ne.setRadiusSearch (0.03);// Use all neighbors in a sphere of radius 3cm
        ne.compute (*cloud_normals);
    
        //extract shot features for the input cloud
        cout << "extracting shot features…" << endl;
        shotExtractor.setInputCloud (cloudIn);
        shotExtractor.setInputNormals(cloud_normals);
        shotExtractor.setSearchMethod(tree2);
        
        //if(kernelType.compare("metric")==0)
            shotExtractor.setRadiusSearch(atof(kernelSize.c_str()));
        //else
            //shotExtractor.setKSearch(atof(kernelSize.c_str()));
        
        shotExtractor.compute(*cloudShot);
        
        //save the result to the outputFile
        cout << "saving to file…" << endl;
        for(int i=0;i<cloudShot->size();i++)
        {
            for(int j=0;j<cloudShot->points[i].descriptor.size();j++)
            {
                outputFile << cloudShot->points[i].descriptor[j] << " ";
            }
            outputFile << endl;
        }
        
        if(argc>6)//save individual shot feature files in shotDir
        {
            shotFileFullName = shotDir + "/" + pcdFileName.substr(0,pcdFileName.size()-3) + "txt";
            cout << "saving individual shot file:" << shotFileFullName << endl;
            shotFile.open(shotFileFullName.c_str(),ios::out);
            for(int i=0;i<cloudShot->size();i++)
            {
                for(int j=0;j<cloudShot->points[i].descriptor.size();j++)
                {
                    shotFile << cloudShot->points[i].descriptor[j] << " ";
                }
                shotFile << endl;
            }
            shotFile.close();
        }
        
        cout << " done" << endl;
    }
    listFile.close();
    outputFile.close();

    return 0;
}
void InstruccionLlamadaAFuncion::validarSemantica()
{
    /*
    Implementar lo de XML y Jar
        Hacer testing del jar en Lejos
     */

    /*DENTRO DE FUNCIONES DECLARADAS*/
    /*Ver si existe la funcion*/
    vector<DeclaracionDeFuncion*> *tablaDeFunciones = Programa::obtenerInstancia()->tablaDeFunciones;
    DeclaracionDeFuncion* funcionDeclarada = Programa::obtenerInstancia()->existeEnTablaDeFunciones(this->identificador, lista_parametros);
    bool encontrado = false;

    if( funcionDeclarada )
    {
        funcionDeclarada->validarSemantica(this->identificador, lista_parametros);
        encontrado = true;
    }

    /*DE LAS FUNCIONES BUILT-IN*/
    transform(this->identificador->begin(), this->identificador->end(), this->identificador->begin(), ::tolower);
    Funcion *fun = Programa::obtenerInstancia()->existeFuncionIncorporada(*this->identificador, this->lista_parametros);

    // true -> Funcion Existe
    if( !encontrado ) // Validar que no se haya encontrado ya en las locales
    {
        encontrado = fun!=0;
    }

    if( fun!=0 )
    {
        // Insertarlo a la tabla!
        Programa::obtenerInstancia()->agregarUsoDeFuncionATabla(*this->identificador, this->lista_parametros, fun);
    }

    /*No esta ni en locales ni built-in, buscarlo en xml*/

    Tipo *agregado = Programa::obtenerInstancia()->existeFuncionEnXmls(*this->identificador,this->lista_parametros);

    if( agregado )
    {
        encontrado = true;
    }

    if( !encontrado )
    {
        stringstream error;
        error << "No existe llamada a funcion '";
        error << *this->identificador;
        error << "' con los parametros(";
            /*Lista de los parametros */

        error << parametrosATipos();
        error << ")";
        throw(ExcepcionLegus(error.str(),numeroDeLinea));
    }

    if( obtenerSiguiente() != 0)
    {
        obtenerSiguiente()->validarSemantica();
    }

    /*Siempre revisar que sea distnto de nulo por si es incorporada*/
    if( funcionDeclarada != 0)
    {
        /*Primero ver si los parametros estan correctos! SHIET*/

        /*Segundo validar que las instrucciones esten correctas!*/
        Instruccion *instrucciones = funcionDeclarada->obtenerInstruccion();
        if( instrucciones != 0)
        {
            instrucciones->validarSemantica();
        }
    }
}
Example #18
0
void StitcherView::scaleScene(qreal new_scale){
  if(new_scale * transform().m11() > 0.01 && new_scale * transform().m11() < 100){
    scale(new_scale,new_scale);
  }
}
Example #19
0
/*!
   Redraw the liquid in thermometer pipe.
   \param painter Painter
*/
void QwtThermo::drawThermo( QPainter *painter )
{
    int alarm  = 0, taval = 0;

    QRect fRect;
    QRect aRect;
    QRect bRect;

    int inverted = ( d_data->maxValue < d_data->minValue );

    //
    //  Determine if value exceeds alarm threshold.
    //  Note: The alarm value is allowed to lie
    //        outside the interval (minValue, maxValue).
    //
    if ( d_data->alarmEnabled )
    {
        if ( inverted )
        {
            alarm = ( ( d_data->alarmLevel >= d_data->maxValue )
                 && ( d_data->alarmLevel <= d_data->minValue )
                 && ( d_data->value >= d_data->alarmLevel ) );

        }
        else
        {
            alarm = ( ( d_data->alarmLevel >= d_data->minValue )
                 && ( d_data->alarmLevel <= d_data->maxValue )
                 && ( d_data->value >= d_data->alarmLevel ) );
        }
    }

    //
    //  transform values
    //
    int tval = transform( d_data->value );

    if ( alarm )
        taval = transform( d_data->alarmLevel );

    //
    //  calculate recangles
    //
    if ( d_data->orientation == Qt::Horizontal )
    {
        if ( inverted )
        {
            bRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                  tval - d_data->thermoRect.x(),
                  d_data->thermoRect.height() );

            if ( alarm )
            {
                aRect.setRect( tval, d_data->thermoRect.y(),
                      taval - tval + 1,
                      d_data->thermoRect.height() );
                fRect.setRect( taval + 1, d_data->thermoRect.y(),
                      d_data->thermoRect.x() + d_data->thermoRect.width() - ( taval + 1 ),
                      d_data->thermoRect.height() );
            }
            else
            {
                fRect.setRect( tval, d_data->thermoRect.y(),
                      d_data->thermoRect.x() + d_data->thermoRect.width() - tval,
                      d_data->thermoRect.height() );
            }
        }
        else
        {
            bRect.setRect( tval + 1, d_data->thermoRect.y(),
                  d_data->thermoRect.width() - ( tval + 1 - d_data->thermoRect.x() ),
                  d_data->thermoRect.height() );

            if ( alarm )
            {
                aRect.setRect( taval, d_data->thermoRect.y(),
                      tval - taval + 1,
                      d_data->thermoRect.height() );
                fRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                      taval - d_data->thermoRect.x(),
                      d_data->thermoRect.height() );
            }
            else
            {
                fRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                      tval - d_data->thermoRect.x() + 1,
                      d_data->thermoRect.height() );
            }

        }
    }
    else // Qt::Vertical
    {
        if ( tval < d_data->thermoRect.y() )
            tval = d_data->thermoRect.y();
        else
        {
            if ( tval > d_data->thermoRect.y() + d_data->thermoRect.height() )
                tval = d_data->thermoRect.y() + d_data->thermoRect.height();
        }

        if ( inverted )
        {
            bRect.setRect( d_data->thermoRect.x(), tval + 1,
                d_data->thermoRect.width(),
                d_data->thermoRect.height() - ( tval + 1 - d_data->thermoRect.y() ) );

            if ( alarm )
            {
                aRect.setRect( d_data->thermoRect.x(), taval,
                    d_data->thermoRect.width(),
                    tval - taval + 1 );
                fRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                    d_data->thermoRect.width(),
                    taval - d_data->thermoRect.y() );
            }
            else
            {
                fRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                    d_data->thermoRect.width(),
                    tval - d_data->thermoRect.y() + 1 );
            }
        }
        else
        {
            bRect.setRect( d_data->thermoRect.x(), d_data->thermoRect.y(),
                d_data->thermoRect.width(),
                tval - d_data->thermoRect.y() );
            if ( alarm )
            {
                aRect.setRect( d_data->thermoRect.x(), tval,
                    d_data->thermoRect.width(),
                    taval - tval + 1 );
                fRect.setRect( d_data->thermoRect.x(), taval + 1,
                    d_data->thermoRect.width(),
                    d_data->thermoRect.y() + d_data->thermoRect.height() - ( taval + 1 ) );
            }
            else
            {
                fRect.setRect( d_data->thermoRect.x(), tval,
                    d_data->thermoRect.width(),
                    d_data->thermoRect.y() + d_data->thermoRect.height() - tval );
            }
        }
    }

    //
    // paint thermometer
    //
    const QColor bgColor = palette().color( QPalette::Window );
    painter->fillRect( bRect, bgColor );

    if ( alarm )
        painter->fillRect( aRect, d_data->alarmBrush );

    painter->fillRect( fRect, d_data->fillBrush );
}
Example #20
0
HashReturn Update(hashState *state, const BitSequence *data,
                  DataLength databitlen)
{
  int r;
  __m128i x0;
  __m128i x1;
  __m128i x2;
  __m128i x3;
  __m128i x4;
  __m128i x5;
  __m128i x6;
  __m128i x7;
  __m128i y0;
  __m128i y1;
  __m128i y2;
  __m128i y3;

  while (databitlen >= 8 && state->pos != 0) {
    ((unsigned char *) state->x)[state->pos / 8] ^= *data;
    data += 1;
    databitlen -= 8;
    state->pos += 8;
    if (state->pos == 8 * CUBEHASH_BLOCKBYTES) {
      transform(state,CUBEHASH_ROUNDS);
      state->pos = 0;
    }
  }

  x0 = state->x[0];
  x1 = state->x[1];
  x2 = state->x[2];
  x3 = state->x[3];
  x4 = state->x[4];
  x5 = state->x[5];
  x6 = state->x[6];
  x7 = state->x[7];
    
  while (databitlen >= 8 * CUBEHASH_BLOCKBYTES) {
    x0 = _mm_xor_si128(x0,_mm_set_epi32(0,0,0,(crypto_uint32) *(crypto_uint16 *) data));
    data += CUBEHASH_BLOCKBYTES;
    databitlen -= 8 * CUBEHASH_BLOCKBYTES;
    
    for (r = 0;r < CUBEHASH_ROUNDS;++r) {
      x4 = _mm_add_epi32(x0,x4);
      x5 = _mm_add_epi32(x1,x5);
      x6 = _mm_add_epi32(x2,x6);
      x7 = _mm_add_epi32(x3,x7);
      y0 = x2;
      y1 = x3;
      y2 = x0;
      y3 = x1;
      x0 = _mm_xor_si128(_mm_slli_epi32(y0,7),_mm_srli_epi32(y0,25));
      x1 = _mm_xor_si128(_mm_slli_epi32(y1,7),_mm_srli_epi32(y1,25));
      x2 = _mm_xor_si128(_mm_slli_epi32(y2,7),_mm_srli_epi32(y2,25));
      x3 = _mm_xor_si128(_mm_slli_epi32(y3,7),_mm_srli_epi32(y3,25));
      x0 = _mm_xor_si128(x0,x4);
      x1 = _mm_xor_si128(x1,x5);
      x2 = _mm_xor_si128(x2,x6);
      x3 = _mm_xor_si128(x3,x7);
      x4 = _mm_shuffle_epi32(x4,0x4e);
      x5 = _mm_shuffle_epi32(x5,0x4e);
      x6 = _mm_shuffle_epi32(x6,0x4e);
      x7 = _mm_shuffle_epi32(x7,0x4e);
      x4 = _mm_add_epi32(x0,x4);
      x5 = _mm_add_epi32(x1,x5);
      x6 = _mm_add_epi32(x2,x6);
      x7 = _mm_add_epi32(x3,x7);
      y0 = x1;
      y1 = x0;
      y2 = x3;
      y3 = x2;
      x0 = _mm_xor_si128(_mm_slli_epi32(y0,11),_mm_srli_epi32(y0,21));
      x1 = _mm_xor_si128(_mm_slli_epi32(y1,11),_mm_srli_epi32(y1,21));
      x2 = _mm_xor_si128(_mm_slli_epi32(y2,11),_mm_srli_epi32(y2,21));
      x3 = _mm_xor_si128(_mm_slli_epi32(y3,11),_mm_srli_epi32(y3,21));
      x0 = _mm_xor_si128(x0,x4);
      x1 = _mm_xor_si128(x1,x5);
      x2 = _mm_xor_si128(x2,x6);
      x3 = _mm_xor_si128(x3,x7);
      x4 = _mm_shuffle_epi32(x4,0xb1);
      x5 = _mm_shuffle_epi32(x5,0xb1);
      x6 = _mm_shuffle_epi32(x6,0xb1);
      x7 = _mm_shuffle_epi32(x7,0xb1);
    }
  }
  
  state->x[0] = x0;
  state->x[1] = x1;
  state->x[2] = x2;
  state->x[3] = x3;
  state->x[4] = x4;
  state->x[5] = x5;
  state->x[6] = x6;
  state->x[7] = x7;

  while (databitlen >= 8) {
    ((unsigned char *) state->x)[state->pos / 8] ^= *data;
    data += 1;
    databitlen -= 8;
    state->pos += 8;
    if (state->pos == 8 * CUBEHASH_BLOCKBYTES) {
      transform(state,CUBEHASH_ROUNDS);
      state->pos = 0;
    }
  }
  if (databitlen > 0) {
    ((unsigned char *) state->x)[state->pos / 8] ^= *data;
    state->pos += databitlen;
  }
  return SUCCESS;
}
Example #21
0
void operator-=(vector<T> &l, const vector<T> &r) {
  transform(begin(l), end(l), begin(r), begin(l), minus<T>());
}
Example #22
0
 // Lowercase字符串. 使用lowercase转化字符.
 static void Lowercase(std::string* parameter)
 {
     transform(parameter->begin(), parameter->end(),
         parameter->begin(), tolower);
 }
ScColorTransform ScLcms2ColorMgmtEngineImpl::createProofingTransform(ScColorMgmtEngine& engine,
                                             const ScColorProfile& inputProfile , eColorFormat inputFormat,
	                                         const ScColorProfile& outputProfile, eColorFormat outputFormat,
                                             const ScColorProfile& proofProfile , eRenderIntent renderIntent, 
                                             eRenderIntent proofingIntent, long transformFlags)
{
	ScColorTransform transform(NULL);
	if (inputProfile.isNull() || outputProfile.isNull())
		return transform;
	int inputProfEngineID  = inputProfile.engine().engineID();
	int outputProfEngineID = outputProfile.engine().engineID();
	int proofProfEngineID  = proofProfile.engine().engineID();
	if ((engine.engineID()  != m_engineID) || (inputProfEngineID != m_engineID) || 
		(outputProfEngineID != m_engineID) || (proofProfEngineID != m_engineID))
		return transform;
	const ScLcms2ColorProfileImpl* lcmsInputProf    = dynamic_cast<const ScLcms2ColorProfileImpl*>(inputProfile.data());
	const ScLcms2ColorProfileImpl* lcmsOutputProf   = dynamic_cast<const ScLcms2ColorProfileImpl*>(outputProfile.data());
	const ScLcms2ColorProfileImpl* lcmsProofingProf = dynamic_cast<const ScLcms2ColorProfileImpl*>(proofProfile.data());
	if (!lcmsInputProf || !lcmsOutputProf || !lcmsProofingProf)
		return transform;

	long strategyFlags = 0;
	if (m_strategy.useBlackPointCompensation)
		strategyFlags |= Ctf_BlackPointCompensation;
	if (m_strategy.useBlackPreservation)
		strategyFlags |= Ctf_BlackPreservation;

	ScColorTransformInfo transInfo;
	transInfo.inputProfile    = inputProfile.productDescription();
	transInfo.outputProfile   = outputProfile.productDescription();
	transInfo.proofingProfile = proofProfile.productDescription();
	transInfo.inputFormat     = inputFormat;
	transInfo.outputFormat    = outputFormat;
	transInfo.renderIntent    = renderIntent;
	transInfo.proofingIntent  = proofingIntent;
	transInfo.flags = transformFlags | strategyFlags;

	cmsUInt32Number lcmsFlags     = translateFlagsToLcmsFlags(transformFlags | strategyFlags);
	cmsUInt32Number lcmsInputFmt  = translateFormatToLcmsFormat(inputFormat);
	cmsUInt32Number lcmsOutputFmt = translateFormatToLcmsFormat(outputFormat);
	int   lcmsIntent    = translateIntentToLcmsIntent(renderIntent);
	int   lcmsPrfIntent = translateIntentToLcmsIntent(proofingIntent);

	if (transInfo.inputProfile != transInfo.proofingProfile)
	{
		if (transInfo.proofingProfile == transInfo.outputProfile)
		{
			transInfo.proofingIntent = Intent_Relative_Colorimetric;
			lcmsPrfIntent = translateIntentToLcmsIntent(Intent_Relative_Colorimetric);
		}
		transform = m_transformPool->findTransform(transInfo);
		if (transform.isNull())
		{
			cmsHTRANSFORM hTransform = NULL;
			hTransform = cmsCreateProofingTransform(lcmsInputProf->m_profileHandle , lcmsInputFmt, 
													lcmsOutputProf->m_profileHandle, lcmsOutputFmt,
													lcmsProofingProf->m_profileHandle, lcmsIntent, 
													lcmsPrfIntent, lcmsFlags | cmsFLAGS_SOFTPROOFING);
			if (hTransform)
			{
				ScLcms2ColorTransformImpl* newTrans = new ScLcms2ColorTransformImpl(engine, hTransform);
				newTrans->setTransformInfo(transInfo);
				transform = ScColorTransform(dynamic_cast<ScColorTransformData*>(newTrans));
				m_transformPool->addTransform(transform, true);
			}
		}
	}
	else
	{
		transformFlags  &= (~Ctf_Softproofing);
		transformFlags  &= (~Ctf_GamutCheck);
		lcmsFlags        = translateFlagsToLcmsFlags(transformFlags | strategyFlags);
		transInfo.flags  = transformFlags | strategyFlags;
		transInfo.renderIntent   = proofingIntent;
		transInfo.proofingIntent = (eRenderIntent) 0;
		if (transInfo.inputProfile == transInfo.outputProfile)
		{
			lcmsFlags |= cmsFLAGS_NULLTRANSFORM;
			transInfo.inputProfile    = QString();
			transInfo.outputProfile   = QString();
			transInfo.proofingProfile = QString();
			transInfo.renderIntent    = (eRenderIntent) 0;
			transInfo.proofingIntent  = (eRenderIntent) 0;
			transInfo.flags = 0;
		}
		transform = m_transformPool->findTransform(transInfo);
		if (transform.isNull())
		{
			cmsHTRANSFORM hTransform = NULL;
			hTransform  = cmsCreateTransform(lcmsInputProf->m_profileHandle , lcmsInputFmt, 
										     lcmsOutputProf->m_profileHandle, lcmsOutputFmt, 
											 lcmsPrfIntent, lcmsFlags | cmsFLAGS_LOWRESPRECALC);
			if (hTransform)
			{
				ScLcms2ColorTransformImpl* newTrans = new ScLcms2ColorTransformImpl(engine, hTransform);
				newTrans->setTransformInfo(transInfo);
				transform = ScColorTransform(dynamic_cast<ScColorTransformData*>(newTrans));
				m_transformPool->addTransform(transform, true);
			}
		}
	}
	return transform;
}
Example #24
0
bool IniReader::read(std::istream & is) {
	
	// The current section
	IniSection * section = NULL;
	
	bool ok = true;
	
	bool readline = true;
	
	std::string str;
	
	// While lines remain to be extracted
	for(size_t line = 1; is.good(); line++) {
		
		// Get a line to process
		if(readline) {
			str.clear();
			getline(is, str);
		} else {
			readline = true;
		}
		
		size_t start = str.find_first_not_of(WHITESPACE);
		if(start == std::string::npos) {
			// Empty line (only whitespace)
			continue;
		}
		
		if(str[start] == '#'
		   || (start + 1 < str.length() && str[start] == '/' && str[start+1] == '/')) {
			// Whole line was commented, no need to do anything with it. Continue getting the next line
			continue;
		}
		
		// Section header
		if(str[start] == '[') {
			
			size_t end = str.find(']', start + 1);
			if(end == std::string::npos) {
				LogDebug("invalid header @ line " << line << ": " << str);
				end = str.find_first_not_of(ALPHANUM, start + 1);
				if(end == std::string::npos) {
					end = str.length();
				}
			}
			
			std::string sectionName = str.substr(start + 1, end - start - 1);
			transform(sectionName.begin(), sectionName.end(), sectionName.begin(), ::tolower);
			
			LogDebug("found section: \"" << sectionName << "\"");
			section = &sections[sectionName];
			
			// Ignoring rest of the line, not verifying that it's only whitespace / comment
			
			continue;
		}
		
		if(!section) {
			LogWarning << "Ignoring non-empty line " << line << " outside a section: " << str;
			ok = false;
			continue;
		}
		
		size_t nameEnd = str.find_first_not_of(ALPHANUM, start);
		if(nameEnd == std::string::npos) {
			ok = false;
			LogWarning << "Missing '=' separator @ line " << line << ": " << str;
			continue;
		} else if(nameEnd == start) {
			ok = false;
			LogWarning << "Empty key name @ line " << line << ": " << str;
			continue;
		}
		
		bool quoted = false;
		
		size_t separator = str.find_first_not_of(WHITESPACE, nameEnd);
		if(separator == std::string::npos || str[separator] != '=') {
			if(separator != std::string::npos && separator + 1 < str.length()
			   && str[separator] == '"' && str[separator + 1] == '=') {
				LogDebug("found '\"=' instead of '=\"' @ line " << line << ": " << str);
				quoted = true;
			} else {
				ok = false;
				LogWarning << "Missing '=' separator @ line " << line << ": " << str;
				continue;
			}
		}
		
		size_t valueStart = str.find_first_not_of(WHITESPACE, separator + 1);
		if(valueStart == std::string::npos) {
			// Empty value.
			section->addKey(str.substr(start, nameEnd - start), std::string());
			continue;
		}
		
		std::string key = str.substr(start, nameEnd - start);
		std::string value;
		
		if(quoted || str[valueStart] == '"') {
			valueStart++;
			size_t valueEnd = str.find_last_of('"');
			arx_assert(valueEnd != std::string::npos);
			
			if(valueEnd < valueStart) {
				
				// The localisation files are broken (missing ending quote)
				// But the spanish localisation files hae erroneous newlines in some values
				LogDebug("invalid quoted value @ line " << line << ": " << str);
				
				valueEnd = str.find_last_not_of(WHITESPACE) + 1;
				arx_assert(valueEnd >= valueStart);
				value = str.substr(valueStart, valueEnd - valueStart);
				
				// Add following lines until we find either a terminating quote,
				// an empty or commented line, a new section or a new key
				for(; is.good(); line++) {
					
					str.clear();
					getline(is, str);
					
					size_t start = str.find_first_not_of(WHITESPACE);
					if(start == std::string::npos) {
						// Empty line (only whitespace)
						break;
					}
					
					if(str[start] == '#'
					   || (start + 1 < str.length() && str[start] == '/' && str[start+1] == '/')) {
						// Whole line was commented
						break;
					}
					
					if(str[start] == '[') {
						// New section
						line--, readline = false;
						break;
					}
					
					size_t nameEnd = str.find_first_not_of(ALPHANUM, start);
					if(nameEnd != std::string::npos && nameEnd != start) {
						size_t separator = str.find_first_not_of(WHITESPACE, nameEnd);
						if(separator != std::string::npos && str[separator] == '=') {
							// New key
							line--, readline = false;
							break;
						}
					}
					
					// Replace newlines with spaces!
					value += ' ';
					
					size_t valueEnd = str.find_last_of('"');
					if(valueEnd != std::string::npos) {
						// End of multi-line value
						value += str.substr(start, valueEnd - start);
						break;
					}
					
					valueEnd = str.find_last_not_of(WHITESPACE) + 1;
					arx_assert(valueEnd > start);
					value += str.substr(start, valueEnd - start);
				}
				
			} else {
				value = str.substr(valueStart, valueEnd - valueStart);
			}
			
		} else {
			size_t valueEnd = str.find_last_not_of(WHITESPACE) + 1;
			arx_assert(valueEnd != std::string::npos);
			arx_assert(valueEnd >= valueStart);
			value = str.substr(valueStart, valueEnd - valueStart);
		}
		
		section->addKey(key, value);
		
		// Ignoring rest of the line, not verifying that it's only whitespace / comment
		
	}
	
	return ok;
}
    void GadgetTreeReader::iterate(gadget::Node* parent, libember::glow::GlowElementCollection* collection)
    {
        if (collection != nullptr)
        {
            auto const last = std::end(*collection);
            for(auto it = std::begin(*collection); it != last; ++it)
            {
                auto& child = *it;
                auto const type = ber::Type::fromTag(child.typeTag());
                if (type.isApplicationDefined())
                {
                    if (type.value() == GlowType::Node)
                    {
                        auto& glownode = *dynamic_cast<GlowNode*>(&child);
                        auto node = gadget::NodeFactory::createNode(parent, glownode.identifier());
                        node->setDescription(glownode.description());
                        node->setSchema(glownode.schemaIdentifiers());

                        iterate(node, glownode.children());
                    }
                    else if (type.value() == GlowType::Parameter)
                    {
                        auto& glowparam = dynamic_cast<GlowParameter&>(child);
                        auto identifier = glowparam.identifier();
                        auto paramtype = glowparam.effectiveType();
                        switch(paramtype.value())
                        {
                            case libember::glow::ParameterType::Boolean:
                                transform(gadget::ParameterFactory::create(parent, identifier, false), &glowparam);
                                break;

                            case libember::glow::ParameterType::Enum:
                                transform(gadget::ParameterFactory::create(parent, identifier), &glowparam);
                                break;

                            case libember::glow::ParameterType::Integer:
                                transform(gadget::ParameterFactory::create(parent, identifier, 0, 1000, 0), &glowparam);
                                break;

                            case libember::glow::ParameterType::Octets:
                                break;

                            case libember::glow::ParameterType::Real:
                                transform(gadget::ParameterFactory::create(parent, identifier, 0.0, 1000.0, 0.0), &glowparam);
                                break;

                            case libember::glow::ParameterType::String:
                                transform(gadget::ParameterFactory::create(parent, identifier, std::string("text")), &glowparam);
                                break;

                            case libember::glow::ParameterType::Trigger:
                                break;

                            default:
                                volatile int x = paramtype.value();
                                break;
                        }
                    }
                }
            }
        }
    }
Example #26
0
//---------------------------------------------------------------------------
void File_ApeTag::Data_Parse()
{
    //If footer
    if (Element_Code==(int64u)-1)
    {
        HeaderFooter();
        Finish("ApeTag");
        return;
    }

    //Parsing
    Ztring Value;
    Get_UTF8(Element_Size, Value,                               "Value"); Element_Info(Value);

    //Filling
    transform(Key.begin(), Key.end(), Key.begin(), (int(*)(int))toupper); //(int(*)(int)) is a patch for unix
         if (Key=="ALBUM")          Fill(Stream_General, 0, General_Album, Value);
    else if (Key=="ARTIST")         Fill(Stream_General, 0, General_Performer, Value);
    else if (Key=="AUTHOR")         Fill(Stream_General, 0, General_WrittenBy, Value);
    else if (Key=="BAND")           Fill(Stream_General, 0, General_Performer, Value);
    else if (Key=="COMMENT")        Fill(Stream_General, 0, General_Comment, Value);
    else if (Key=="COMMENTS")       Fill(Stream_General, 0, General_Comment, Value);
    else if (Key=="COMPOSER")       Fill(Stream_General, 0, General_Composer, Value);
    else if (Key=="CONTENTGROUP")   Fill(Stream_General, 0, General_Genre, Value);
    else if (Key=="COPYRIGHT")      Fill(Stream_General, 0, General_Copyright, Value);
    else if (Key=="DISK")
    {
                                    if (Value.find(_T("/"))!=Error)
                                    {
                                        Fill(Stream_General, 0, General_Part_Position_Total, Value.SubString(_T("/"), _T("")));
                                        Fill(Stream_General, 0, General_Part_Position, Value.SubString(_T(""), _T("/")));
                                    }
                                    else
                                        Fill(Stream_General, 0, General_Track_Position, Value);
    }
    else if (Key=="ENCODEDBY")      Fill(Stream_General, 0, General_EncodedBy, Value);
    else if (Key=="GENRE")          Fill(Stream_General, 0, General_Genre, Value);
    else if (Key=="ORIGARTIST")     Fill(Stream_General, 0, General_Original_Performer, Value);
    else if (Key=="TITLE")          Fill(Stream_General, 0, General_Title, Value);
    else if (Key=="TRACK")
    {
                                    if (Value.find(_T("/"))!=Error)
                                    {
                                        Fill(Stream_General, 0, General_Track_Position_Total, Value.SubString(_T("/"), _T("")));
                                        Fill(Stream_General, 0, General_Track_Position, Value.SubString(_T(""), _T("/")));
                                    }
                                    else
                                        Fill(Stream_General, 0, General_Track_Position, Value);
    }
    else if (Key=="UNSYNCEDLYRICS") Fill(Stream_General, 0, General_Lyrics, Value);
    else if (Key=="WWW")            Fill(Stream_General, 0, General_Title_Url, Value);
    else if (Key=="YEAR")           Fill(Stream_General, 0, General_Recorded_Date, Value);
    else if (Key=="CONTENT GROUP DESCRIPTION") Fill(Stream_General, 0, General_Title, Value);
    else if (Key=="ORIGINAL ALBUM/MOVIE/SHOW TITLE") Fill(Stream_General, 0, General_Original_Album, Value);
    else if (Key=="ORIGINAL ARTIST(S)/PERFORMER(S)") Fill(Stream_General, 0, General_Original_Performer, Value);
    else if (Key=="MP3GAIN_MINMAX") Fill(Stream_Audio, 0, "MP3Gain, Min/Max", Value);
    else if (Key=="MP3GAIN_UNDO") Fill(Stream_Audio, 0, "MP3Gain, Undo", Value);
    else if (Key=="REPLAYGAIN_TRACK_GAIN") Fill(Stream_Audio, 0, Audio_ReplayGain_Gain, Value.To_float64(), 2, true);
    else if (Key=="REPLAYGAIN_TRACK_PEAK") Fill(Stream_Audio, 0, Audio_ReplayGain_Peak, Value.To_float64(), 6, true);
    else                            Fill(Stream_General, 0, Key.c_str(), Value);
}