• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ std::string类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中std::string的典型用法代码示例。如果您正苦于以下问题:C++ string类的具体用法?C++ string怎么用?C++ string使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了string类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: operator

 inline void operator() (const std::string& s)
 {
    if (s.empty()) return;
    strtk::split(p_,s,*this,strtk::split_options::compress_delimiters);
 }
开发者ID:Ane2,项目名称:InfiniteSky,代码行数:5,代码来源:strtk_wordfreq.cpp


示例2: error

bool
TIFFOutput::open (const std::string &name, const ImageSpec &userspec,
                  OpenMode mode)
{
    if (mode == AppendMIPLevel) {
        error ("%s does not support MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_spec = userspec;  // Stash the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.tile_width) {
       if (m_spec.tile_width  % 16 != 0 ||
           m_spec.tile_height % 16 != 0 ||
           m_spec.tile_height == 0) {
          error("Tile size must be a multiple of 16, you asked for %d x %d", m_spec.tile_width, m_spec.tile_height);
          return false;
       }
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;

    // Open the file
#ifdef _WIN32
    std::wstring wname = Strutil::utf8_to_utf16 (name);
    m_tif = TIFFOpenW (wname.c_str(), mode == AppendSubimage ? "a" : "w");
#else
    m_tif = TIFFOpen (name.c_str(), mode == AppendSubimage ? "a" : "w");
#endif
    if (! m_tif) {
        error ("Can't open \"%s\" for output.", name.c_str());
        return false;
    }

    // N.B. Clamp position at 0... TIFF is internally incapable of having
    // negative origin.
    TIFFSetField (m_tif, TIFFTAG_XPOSITION, (float)std::max (0, m_spec.x));
    TIFFSetField (m_tif, TIFFTAG_YPOSITION, (float)std::max (0, m_spec.y));

    TIFFSetField (m_tif, TIFFTAG_IMAGEWIDTH, m_spec.width);
    TIFFSetField (m_tif, TIFFTAG_IMAGELENGTH, m_spec.height);
    if ((m_spec.full_width != 0 || m_spec.full_height != 0) &&
        (m_spec.full_width != m_spec.width || m_spec.full_height != m_spec.height)) {
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLWIDTH, m_spec.full_width);
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLLENGTH, m_spec.full_height);
    }
    if (m_spec.tile_width) {
        TIFFSetField (m_tif, TIFFTAG_TILEWIDTH, m_spec.tile_width);
        TIFFSetField (m_tif, TIFFTAG_TILELENGTH, m_spec.tile_height);
    } else {
        // Scanline images must set rowsperstrip
        TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 32);
    }
    TIFFSetField (m_tif, TIFFTAG_SAMPLESPERPIXEL, m_spec.nchannels);
    int orientation = m_spec.get_int_attribute("Orientation", 1);
    TIFFSetField (m_tif, TIFFTAG_ORIENTATION, orientation);
    
    int bps, sampformat;
    switch (m_spec.format.basetype) {
    case TypeDesc::INT8:
        bps = 8;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT8:
        bps = 8;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::INT16:
        bps = 16;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT16:
        bps = 16;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::HALF:
        // Silently change requests for unsupported 'half' to 'float'
        m_spec.set_format (TypeDesc::FLOAT);
    case TypeDesc::FLOAT:
        bps = 32;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    case TypeDesc::DOUBLE:
        bps = 64;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    default:
        // Everything else, including UNKNOWN -- default to 8 bit
        bps = 8;
        sampformat = SAMPLEFORMAT_UINT;
        m_spec.set_format (TypeDesc::UINT8);
        break;
    }
//.........这里部分代码省略.........
开发者ID:gmarcusm,项目名称:oiio,代码行数:101,代码来源:tiffoutput.cpp


示例3: escapeString

std::string DatabaseODBC::escapeString(const std::string &s)
{
	return escapeBlob( s.c_str(), s.length() );
}
开发者ID:cp1337,项目名称:devland,代码行数:4,代码来源:databaseodbc.cpp


示例4: addEffect

void Animation::addEffect(const std::string &model, int effectId, bool loop, const std::string &bonename, std::string texture)
{
    // Early out if we already have this effect
    for (std::vector<EffectParams>::iterator it = mEffects.begin(); it != mEffects.end(); ++it)
        if (it->mLoop && loop && it->mEffectId == effectId && it->mBoneName == bonename)
            return;

    // fix texture extension to .dds
    if (texture.size() > 4)
    {
        texture[texture.size()-3] = 'd';
        texture[texture.size()-2] = 'd';
        texture[texture.size()-1] = 's';
    }

    EffectParams params;
    params.mModelName = model;
    if (bonename.empty())
        params.mObjects = NifOgre::Loader::createObjects(mInsert, model);
    else
        params.mObjects = NifOgre::Loader::createObjects(mSkelBase, bonename, mInsert, model);

    // TODO: turn off shadow casting
    setRenderProperties(params.mObjects, RV_Misc,
                        RQG_Main, RQG_Alpha, 0.f, false, NULL);

    params.mLoop = loop;
    params.mEffectId = effectId;
    params.mBoneName = bonename;

    for(size_t i = 0;i < params.mObjects->mControllers.size();i++)
    {
        if(params.mObjects->mControllers[i].getSource().isNull())
            params.mObjects->mControllers[i].setSource(Ogre::SharedPtr<EffectAnimationTime> (new EffectAnimationTime()));
    }

    if (!texture.empty())
    {
        for(size_t i = 0;i < params.mObjects->mParticles.size(); ++i)
        {
            Ogre::ParticleSystem* partSys = params.mObjects->mParticles[i];

            Ogre::MaterialPtr mat = params.mObjects->mMaterialControllerMgr.getWritableMaterial(partSys);

            for (int t=0; t<mat->getNumTechniques(); ++t)
            {
                Ogre::Technique* tech = mat->getTechnique(t);
                for (int p=0; p<tech->getNumPasses(); ++p)
                {
                    Ogre::Pass* pass = tech->getPass(p);
                    for (int tex=0; tex<pass->getNumTextureUnitStates(); ++tex)
                    {
                        Ogre::TextureUnitState* tus = pass->getTextureUnitState(tex);
                        tus->setTextureName("textures\\" + texture);
                    }
                }
            }
        }
    }

    mEffects.push_back(params);
}
开发者ID:Chiur,项目名称:openmw,代码行数:62,代码来源:animation.cpp


示例5: play

void Animation::play(const std::string &groupname, int priority, int groups, bool autodisable, float speedmult, const std::string &start, const std::string &stop, float startpoint, size_t loops)
{
    if(!mSkelBase || mAnimSources.empty())
        return;

    if(groupname.empty())
    {
        resetActiveGroups();
        return;
    }

    priority = std::max(0, priority);

    AnimStateMap::iterator stateiter = mStates.begin();
    while(stateiter != mStates.end())
    {
        if(stateiter->second.mPriority == priority)
            mStates.erase(stateiter++);
        else
            ++stateiter;
    }

    stateiter = mStates.find(groupname);
    if(stateiter != mStates.end())
    {
        stateiter->second.mPriority = priority;
        resetActiveGroups();
        return;
    }

    /* Look in reverse; last-inserted source has priority. */
    AnimSourceList::reverse_iterator iter(mAnimSources.rbegin());
    for(;iter != mAnimSources.rend();iter++)
    {
        const NifOgre::TextKeyMap &textkeys = (*iter)->mTextKeys;
        AnimState state;
        if(reset(state, textkeys, groupname, start, stop, startpoint))
        {
            state.mSource = *iter;
            state.mSpeedMult = speedmult;
            state.mLoopCount = loops;
            state.mPlaying = (state.mTime < state.mStopTime);
            state.mPriority = priority;
            state.mGroups = groups;
            state.mAutoDisable = autodisable;
            mStates[groupname] = state;

            NifOgre::TextKeyMap::const_iterator textkey(textkeys.lower_bound(state.mTime));
            while(textkey != textkeys.end() && textkey->first <= state.mTime)
            {
                handleTextKey(state, groupname, textkey);
                textkey++;
            }

            if(state.mTime >= state.mLoopStopTime && state.mLoopCount > 0)
            {
                state.mLoopCount--;
                state.mTime = state.mLoopStartTime;
                state.mPlaying = true;
                if(state.mTime >= state.mLoopStopTime)
                    break;

                textkey = textkeys.lower_bound(state.mTime);
                while(textkey != textkeys.end() && textkey->first <= state.mTime)
                {
                    handleTextKey(state, groupname, textkey);
                    textkey++;
                }
            }

            break;
        }
    }
    if(iter == mAnimSources.rend())
        std::cerr<< "Failed to find animation "<<groupname<<" for "<<mPtr.getCellRef().mRefID <<std::endl;

    resetActiveGroups();
}
开发者ID:Chiur,项目名称:openmw,代码行数:78,代码来源:animation.cpp


示例6: printTag

void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
  if (Policy.SuppressTag)
    return;

  std::string Buffer;
  bool HasKindDecoration = false;

  // bool SuppressTagKeyword
  //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;

  // We don't print tags unless this is an elaborated type.
  // In C, we just assume every RecordType is an elaborated type.
  if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
        D->getTypedefNameForAnonDecl())) {
    HasKindDecoration = true;
    Buffer += D->getKindName();
    Buffer += ' ';
  }

  // Compute the full nested-name-specifier for this type.
  // In C, this will always be empty except when the type
  // being printed is anonymous within other Record.
  if (!Policy.SuppressScope)
    AppendScope(D->getDeclContext(), Buffer);

  if (const IdentifierInfo *II = D->getIdentifier())
    Buffer += II->getNameStart();
  else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
    assert(Typedef->getIdentifier() && "Typedef without identifier?");
    Buffer += Typedef->getIdentifier()->getNameStart();
  } else {
    // Make an unambiguous representation for anonymous types, e.g.
    //   <anonymous enum at /usr/include/string.h:120:9>
    llvm::raw_string_ostream OS(Buffer);
    OS << "<anonymous";

    if (Policy.AnonymousTagLocations) {
      // Suppress the redundant tag keyword if we just printed one.
      // We don't have to worry about ElaboratedTypes here because you can't
      // refer to an anonymous type with one.
      if (!HasKindDecoration)
        OS << " " << D->getKindName();

      PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
          D->getLocation());
      if (PLoc.isValid()) {
        OS << " at " << PLoc.getFilename()
           << ':' << PLoc.getLine()
           << ':' << PLoc.getColumn();
      }
    }
    
    OS << '>';
  }

  // If this is a class template specialization, print the template
  // arguments.
  if (ClassTemplateSpecializationDecl *Spec
        = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
    const TemplateArgument *Args;
    unsigned NumArgs;
    if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
      const TemplateSpecializationType *TST =
        cast<TemplateSpecializationType>(TAW->getType());
      Args = TST->getArgs();
      NumArgs = TST->getNumArgs();
    } else {
      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
      Args = TemplateArgs.data();
      NumArgs = TemplateArgs.size();
    }
    IncludeStrongLifetimeRAII Strong(Policy);
    Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
                                                                    NumArgs,
                                                                    Policy);
  }

  if (!InnerString.empty()) {
    Buffer += ' ';
    Buffer += InnerString;
  }

  std::swap(Buffer, InnerString);
}
开发者ID:ACSOP,项目名称:android_external_clang,代码行数:84,代码来源:TypePrinter.cpp


示例7: switch

void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
  if (!T) {
    buffer += "NULL TYPE";
    return;
  }
  
  if (Policy.SuppressSpecifiers && T->isSpecifierType())
    return;
  
  // Print qualifiers as appropriate.
  
  // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
  // so that we get "const int" instead of "int const", but we can't do this if
  // the type is complex.  For example if the type is "int*", we *must* print
  // "int * const", printing "const int *" is different.  Only do this when the
  // type expands to a simple string.
  bool CanPrefixQualifiers = false;
  bool NeedARCStrongQualifier = false;
  Type::TypeClass TC = T->getTypeClass();
  if (const AutoType *AT = dyn_cast<AutoType>(T))
    TC = AT->desugar()->getTypeClass();
  if (const SubstTemplateTypeParmType *Subst
                                      = dyn_cast<SubstTemplateTypeParmType>(T))
    TC = Subst->getReplacementType()->getTypeClass();
  
  switch (TC) {
    case Type::Builtin:
    case Type::Complex:
    case Type::UnresolvedUsing:
    case Type::Typedef:
    case Type::TypeOfExpr:
    case Type::TypeOf:
    case Type::Decltype:
    case Type::UnaryTransform:
    case Type::Record:
    case Type::Enum:
    case Type::Elaborated:
    case Type::TemplateTypeParm:
    case Type::SubstTemplateTypeParmPack:
    case Type::TemplateSpecialization:
    case Type::InjectedClassName:
    case Type::DependentName:
    case Type::DependentTemplateSpecialization:
    case Type::ObjCObject:
    case Type::ObjCInterface:
    case Type::Atomic:
      CanPrefixQualifiers = true;
      break;
      
    case Type::ObjCObjectPointer:
      CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
        T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
      break;
      
    case Type::ConstantArray:
    case Type::IncompleteArray:
    case Type::VariableArray:
    case Type::DependentSizedArray:
      NeedARCStrongQualifier = true;
      // Fall through
      
    case Type::Pointer:
    case Type::BlockPointer:
    case Type::LValueReference:
    case Type::RValueReference:
    case Type::MemberPointer:
    case Type::DependentSizedExtVector:
    case Type::Vector:
    case Type::ExtVector:
    case Type::FunctionProto:
    case Type::FunctionNoProto:
    case Type::Paren:
    case Type::Attributed:
    case Type::PackExpansion:
    case Type::SubstTemplateTypeParm:
    case Type::Auto:
      CanPrefixQualifiers = false;
      break;
  }
  
  if (!CanPrefixQualifiers && !Quals.empty()) {
    std::string qualsBuffer;
    if (NeedARCStrongQualifier) {
      IncludeStrongLifetimeRAII Strong(Policy);
      Quals.getAsStringInternal(qualsBuffer, Policy);
    } else {
      Quals.getAsStringInternal(qualsBuffer, Policy);
    }
    
    if (!qualsBuffer.empty()) {
      if (!buffer.empty()) {
        qualsBuffer += ' ';
        qualsBuffer += buffer;
      }
      std::swap(buffer, qualsBuffer);
    }
  }
  
  switch (T->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, PARENT)
//.........这里部分代码省略.........
开发者ID:ACSOP,项目名称:android_external_clang,代码行数:101,代码来源:TypePrinter.cpp


示例8: Connect

bool Client::Connect(std::string ip, std::string port, std::string ownPort, std::string ownName)
{
	server.address = ip;
	server.port = std::stoi(port);

	ownData.name = ownName;

	if (ownPort.length() > 0)
	{
		ownData.port = std::stoi(ownPort);
		status = socket.bind(ownData.port);
		switch (status)
		{
		case sf::Socket::Done:
			break;
		default:
			std::cout << "error: socket.bind" << std::endl;
			return false;
		}
	}
	else
	{
		status = socket.bind(sf::Socket::AnyPort);
		switch (status)
		{
		case sf::Socket::Done:
			break;
		default:
			std::cout << "error: socket.bind anyport" << std::endl;
			return false;
		}
	}

	packet.clear();
	MakeConnectPacket(packet, ownData.name);
	status = socket.send(packet, server.address, server.port);
	switch (status)
	{
	case sf::Socket::Done:
		break;
	default:
		std::cout << "error: socket.send" << std::endl;
		return false;
	}

	for (int i = 0; i < 100; i++)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(20));
		packet.clear();
		status = socket.receive(packet, remote.address, remote.port);
		switch (status)
		{
		case sf::Socket::Done:
			packet >> pType;
			switch (pType)
			{
			case 17:
				packet >> ServerTimeDif;
				packet >> ownData.ID;
				if (server.port == remote.port)
					server.address = remote.address;

				ownData.disconnected = false;
				return true;
			default:
				std::cout << "error: unexpected packet type at connect " << pType << std::endl;
				return false;
			}
			return false;
		case sf::Socket::NotReady:
			break;
		default:
			return false;
		}
	}

	return false;
}
开发者ID:Eracage,项目名称:Verkkopeliohjelmointi,代码行数:78,代码来源:Client.cpp


示例9: write_explicit_surface_opendx

    void write_explicit_surface_opendx(const levelset<GridTraitsType, LevelSetTraitsType>& l, const std::string& filename, const DataType& Data, typename LevelSetTraitsType::value_type eps=0.) {
        //this function etracts the surface using the marching cubes algorithm and writes it to the specified file using OpenDX-file format
        //the parameter eps is forwarded to the surface extraction function

        const int D=GridTraitsType::dimensions;

        Surface<D> s;

        typename GetActivePointType<typename LevelSetTraitsType::size_type, DataType>::result ActivePointList;

        extract(l, s, eps, ActivePointList);

        std::ofstream f(filename.c_str());

        //!print positions
        f<< "object \"positions\" class array type float rank 1 shape " << D << " items "<< s.Nodes.size() <<" data follows" << std::endl;
        for (unsigned int i=0;i<s.Nodes.size();i++) {
            for (int j=0;j<D;j++) f << static_cast<float>(s.Nodes[i][j]) << " ";
            f<< std::endl;
        }

        //! print connections
        f << "object \"connections\" class array type int rank 1 shape " << D << " items "<< s.Elements.size() <<" data follows" << std::endl;
        for (unsigned int i=0;i<s.Elements.size();i++) {
            for (int j=0;j<D;j++) f<< s.Elements[i][j] << " ";
            f << std::endl;
        }

        if (D==2)
            f << "attribute \"element type\" string \"lines\"" << std::endl;
        else if (D==3)
            f << "attribute \"element type\" string \"triangles\"" << std::endl;
        f << "attribute \"ref\" string \"positions\"" << std::endl;


        //output data
        for (int k=0;k<Data.number_of_series();++k) {
            if (Data.get_series_output(k)) {
                f << "object \"" << Data.get_series_label(k) << "_data\" class array type " << Data.get_series_type(k) << " rank 0 items " << s.Nodes.size() << " data follows" << std::endl;
                for (unsigned int i=0;i<s.Nodes.size();i++) {
                    f << Data.get_series_data(ActivePointList[i],k) << std::endl;
                }
                f << "attribute \"dep\" string \"positions\"" << std::endl;
            }
        }

        //! print profile
        f << "object \"profile\" class field" << std::endl;
        f << "  component \"positions\" value \"positions\"" << std::endl;
        f << "  component \"connections\" value \"connections\"" << std::endl;

        for (int k=0;k<Data.number_of_series();++k) {
            if (Data.get_series_output(k)) {
                f << "object \""<< Data.get_series_label(k) << "\" class field" << std::endl;
                f << "  component \"positions\" value \"positions\"" << std::endl;
                f << "  component \"connections\" value \"connections\"" << std::endl;
                f << "  component \"data\" value \"" << Data.get_series_label(k) << "_data\"" << std::endl;
            }
        }

        f << "end" << std::endl;




        f.close();
    }
开发者ID:viennats,项目名称:viennats-dev,代码行数:67,代码来源:output.hpp


示例10: NC_create

// NetcdfFile::NC_create()
int NetcdfFile::NC_create(std::string const& Name, NCTYPE type, int natomIn,
                          CoordinateInfo const& coordInfo, std::string const& title) 
{
  if (Name.empty()) return 1;
  int dimensionID[NC_MAX_VAR_DIMS];
  int NDIM;
  nc_type dataType;

  if (ncdebug_>1)
    mprintf("DEBUG: NC_create: %s  natom=%i V=%i F=%i box=%i  temp=%i  time=%i\n",
            Name.c_str(),natomIn,(int)coordInfo.HasVel(),
            (int)coordInfo.HasForce(),(int)coordInfo.HasBox(),
            (int)coordInfo.HasTemp(),(int)coordInfo.HasTime());

  if ( NC::CheckErr( nc_create( Name.c_str(), NC_64BIT_OFFSET, &ncid_) ) )
    return 1;

  ncatom_ = natomIn;
  ncatom3_ = ncatom_ * 3;
  
  // Set number of dimensions based on file type
  switch (type) {
    case NC_AMBERENSEMBLE:
      NDIM = 4;
      dataType = NC_FLOAT;
      break;
    case NC_AMBERTRAJ: 
      NDIM = 3;
      dataType = NC_FLOAT;
      break;
    case NC_AMBERRESTART: 
      NDIM = 2; 
      dataType = NC_DOUBLE;
      break;
    default:
      mprinterr("Error: NC_create (%s): Unrecognized type (%i)\n",Name.c_str(),(int)type);
      return 1;
  }

  if (type == NC_AMBERENSEMBLE) {
    // Ensemble dimension for ensemble
    if (coordInfo.EnsembleSize() < 1) {
      mprinterr("Internal Error: NetcdfFile: ensembleSize < 1\n");
      return 1;
    }
    if ( NC::CheckErr(nc_def_dim(ncid_, NCENSEMBLE, coordInfo.EnsembleSize(), &ensembleDID_)) ) {
      mprinterr("Error: Defining ensemble dimension.\n");
      return 1;
    }
    dimensionID[1] = ensembleDID_;
  }
  ncframe_ = 0;
  if (type == NC_AMBERTRAJ || type == NC_AMBERENSEMBLE) {
    // Frame dimension for traj
    if ( NC::CheckErr( nc_def_dim( ncid_, NCFRAME, NC_UNLIMITED, &frameDID_)) ) {
      mprinterr("Error: Defining frame dimension.\n");
      return 1;
    }
    // Since frame is UNLIMITED, it must be lowest dim.
    dimensionID[0] = frameDID_;
  }
  // Time variable and units
  if (coordInfo.HasTime()) {
    if ( NC::CheckErr( nc_def_var(ncid_, NCTIME, dataType, NDIM-2, dimensionID, &timeVID_)) ) {
      mprinterr("Error: Defining time variable.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text(ncid_, timeVID_, "units", 10, "picosecond")) ) {
      mprinterr("Error: Writing time VID units.\n");
      return 1;
    }
  }
  // Spatial dimension and variable
  if ( NC::CheckErr( nc_def_dim( ncid_, NCSPATIAL, 3, &spatialDID_)) ) {
    mprinterr("Error: Defining spatial dimension.\n");
    return 1;
  }
  dimensionID[0] = spatialDID_;
  if ( NC::CheckErr( nc_def_var( ncid_, NCSPATIAL, NC_CHAR, 1, dimensionID, &spatialVID_)) ) {
    mprinterr("Error: Defining spatial variable.\n"); 
    return 1;
  }
  // Atom dimension
  if ( NC::CheckErr( nc_def_dim( ncid_, NCATOM, ncatom_, &atomDID_)) ) {
    mprinterr("Error: Defining atom dimension.\n");
    return 1;
  }
  // Setup dimensions for Coords/Velocity
  // NOTE: THIS MUST BE MODIFIED IF NEW TYPES ADDED
  if (type == NC_AMBERENSEMBLE) {
    dimensionID[0] = frameDID_;
    dimensionID[1] = ensembleDID_;
    dimensionID[2] = atomDID_;
    dimensionID[3] = spatialDID_;
  } else if (type == NC_AMBERTRAJ) {
    dimensionID[0] = frameDID_;
    dimensionID[1] = atomDID_;
    dimensionID[2] = spatialDID_;
  } else {
//.........这里部分代码省略.........
开发者ID:hainm,项目名称:cpptraj,代码行数:101,代码来源:NetcdfFile.cpp


示例11: MakeCache

static void
MakeCache(const std::string &prefix, int argc, char *argv[], bool _doEmbedded)
{
	MPI_Status status;
	int xi;
 	std::map<std::string, std::list<std::string> >::const_iterator pIter;
	int np, me; 

	cachePath = prefix;

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &np);
	MPI_Comm_rank(MPI_COMM_WORLD, &me);

	doEmbedded = _doEmbedded;

	LoadEverything();
//	outputFormat = CLONEWISE_OUTPUT_XML;
	printf("# loaded everything\n");
	fflush(stdout);

	if (embeddedOnly) {
		std::map<std::string, std::set<std::string> >::const_iterator eIter;

		if (embeddedList.size() == 0) {
			char s[1024];

		        snprintf(s, sizeof(s), "/var/lib/Clonewise/clones/distros/%s/embedded-code-copies", distroString);
		        LoadEmbeddedCodeCopiesList(s);
		}
		for (	eIter  = embeddedList.begin(), xi = 0;
			eIter != embeddedList.end();
			eIter++)
		{
			vPackages.push_back(eIter->first);
			packageQueue.push_back(xi++);
		}
	} else {
		for (	pIter  = packages.begin(), xi = 0;
			pIter != packages.end();
			pIter++)
		{
			vPackages.push_back(pIter->first);
			packageQueue.push_back(xi++);
		}
	}

	printf("# going to scan %i packages\n", xi);
	fflush(stdout);
	if (me == 0) {
		while (packageQueue.size() != 0) {
			int index, which;

			MPI_Recv(&which, 1, MPI_INT, MPI_ANY_SOURCE, TAG1, MPI_COMM_WORLD, &status); 
			index = packageQueue.front();
			packageQueue.pop_front();
			MPI_Send(&index, 1, MPI_INT, which, TAG1, MPI_COMM_WORLD); 
		}
		for (int i = 1; i < np; i++) {
			int which, neg = -1;

			MPI_Recv(&which, 1, MPI_INT, i, TAG1, MPI_COMM_WORLD, &status); 
			MPI_Send(&neg, 1, MPI_INT, i, TAG1, MPI_COMM_WORLD); 
		}
		for (size_t i = 0; i < vPackages.size(); i++) { 
			int which;
			int r[2], size;
			char *result;
			FILE *f;
			char s[1024];

			MPI_Recv(&which, 1, MPI_INT, MPI_ANY_SOURCE, TAG1, MPI_COMM_WORLD, &status); 
			MPI_Recv(r, 2, MPI_INT, which, TAG1, MPI_COMM_WORLD, &status); 

			size = r[1];
			result = new char[size];

			MPI_Recv(result, size, MPI_CHAR, which, TAG1, MPI_COMM_WORLD, &status); 

			snprintf(s, sizeof(s), "/var/lib/Clonewise/clones/distros/%s/%s/%s", distroString, prefix.c_str(), vPackages[r[0]].c_str());
			f = fopen(s, "w");
			fwrite(result, 1, size, f);
			fclose(f), f = NULL;

			delete [] result;
		}
	} else {
		DoWorkLoop(me);
	}

	MPI_Finalize(); 
	exit(0); 
}
开发者ID:grimreaper,项目名称:Clonewise,代码行数:93,代码来源:Clonewise-MakeCache.cpp


示例12: NC_openWrite

// NetcdfFile::NC_openWrite()
int NetcdfFile::NC_openWrite(std::string const& Name) {
  if (Name.empty()) return 1;
  if ( NC::CheckErr( nc_open( Name.c_str(), NC_WRITE, &ncid_ ) ) )
    return 1;
  return 0;
}
开发者ID:hainm,项目名称:cpptraj,代码行数:7,代码来源:NetcdfFile.cpp


示例13: rsa_enc_pass

bool rsa_enc_pass(const std::string & pass, std::string & enc_pass)
{
    static const char * n_str =
    "00ac3a16cd5c00e7e36bd67ec973322a5f3e3525d4152d84b984f7ea40dc82f33"
    "70658df7e2b833987a5b7945e8f5cb2c8ab9623cf81d9c3b89ac1c72dc470295b"
    "82fe940fe2611e5aa98433c669ff29a25ba4018c3ed501f56578d79f7f53dd2a7"
    "3180847671ecefcfd720f1d5d5fb9b6840fc3060501ea376e36549e865f3e0957"
    "f35cc02c8398ee753dc75cf7e922049b7e8d08d982fef2e72a2267cb261f418a7"
    "fac0e4cbdf027e2e9154d8c0d8146fdd55eed65c5f0ba8d8e894f626a7df9ed5c"
    "addd4cc120948ff384a36364eb966b8abe4fb09b39833446a4f12ec84238f3eef"
    "faa3f2dc6849a4f5f6c01894e4f5294de5445c93386f68e0a161f716611";

    RSA *rsa = NULL;
    BIGNUM *n = NULL;
    BIGNUM *e = NULL;
    int pass_len = 0;
    int i = 0;
    bool success = false;
    char * enc_pass_buffer = NULL;
    char * enc_pass_str = NULL;

    n = BN_new();
    e = BN_new();

    if(!n || !e)
        goto err;

    if(!BN_hex2bn(&n, n_str))
        goto err;

    if(!BN_set_word(e, 65537))
        goto err;

    if((rsa = RSA_new()) == NULL)
        goto err;

    rsa->n = n;
    rsa->e = e;

    pass_len = RSA_size(rsa);

    if(!(enc_pass_buffer = (char *)malloc(pass_len)))
        goto err;
    memset(enc_pass_buffer, 0, pass_len);

    if((pass_len = RSA_public_encrypt(pass.size(), (const unsigned char*)pass.data(), 
        (unsigned char*)enc_pass_buffer, rsa, RSA_PKCS1_PADDING)) < 0)
        goto err;

    if(!(enc_pass_str = (char *)malloc(pass_len*2+1)))
        goto err;
    memset(enc_pass_str, 0, pass_len*2+1);

    for(i = 0; i < pass_len; i ++) {
        sprintf(enc_pass_str+i*2, "%02hhx", (unsigned char)enc_pass_buffer[i]);
    }

    enc_pass = enc_pass_str;

    success = true;
err:
    if(n) BN_free(n);
    if(e) BN_free(e); 
    if(rsa) {
        rsa->n = NULL;
        rsa->e = NULL;
        RSA_free(rsa);
    }
    if(enc_pass_buffer) free(enc_pass_buffer);
    if(enc_pass_str) free(enc_pass_str);
    return success;
}
开发者ID:hefangshi,项目名称:hack-of-zhunru,代码行数:72,代码来源:enc.cpp


示例14: StringFrom

SimpleString StringFrom(const std::string& value)
{
	return SimpleString(value.c_str());
}
开发者ID:Berrrry,项目名称:android_Kernel_sony_msm8974,代码行数:4,代码来源:SimpleString.cpp


示例15: BitsetsToFile

///Writes v to file
void BitsetsToFile(
  const std::string& filename)
{
  std::ofstream f(filename.c_str());
  for (int i=0; i!=n_bitsets; ++i) { f << v_global[i] << '\n'; }
}
开发者ID:richelbilderbeek,项目名称:CppTests,代码行数:7,代码来源:main.cpp


示例16: write_levelset_opendx

    void write_levelset_opendx(const levelset<GridTraitsType, LevelSetTraitsType>& l, std::string FileName,  bool only_defined_grid_points, float limit, bool only_signs) {
        //this functions writes all defined grid points including their level set values
        //      to file using the OpenDX (Open Data Explorer)-file format
        //limit specifies the range of values assigned to the grid points,
        //      if the level set value of a grid point is
        //      out of this range the value is set to +/- limit
        //if only_defined_grid_points is set to false then also the start and end grid points
        //      of undefined runs are written to file, their values are then set to +/-limit
        //if only_signs is set to true then only the signs of the grid points are written to file,
        //      the grid point values are then set either to +1 or -1

        typedef levelset<GridTraitsType, LevelSetTraitsType> LevelSetType;
//        typedef typename LevelSetType::value_type value_type;
        typedef typename LevelSetType::size_type size_type;
        const int D=LevelSetType::dimensions;


        std::ofstream f(FileName.c_str());

        size_type num=0;

        for (typename LevelSetType::const_iterator_runs it(l);
            !it.is_finished();it.next()) {
            if (only_defined_grid_points) if (!it.is_defined()) continue;
            if (!l.grid().is_at_infinity(it.start_indices())) num++;
            if (it.start_indices()!=it.end_indices()) if (!l.grid().is_at_infinity(it.end_indices())) num++;
        }


        f<< "object 1 class array type float rank 1 shape " << D << " items "<< num <<" data follows" << std::endl;

        for (typename LevelSetType::const_iterator_runs it(l);
                !it.is_finished();it.next()) {
            if (only_defined_grid_points) if (!it.is_defined()) continue;
            if (!l.grid().is_at_infinity(it.start_indices())) {
                for (int j=0;j<D;j++) f << (it.start_indices()[j]) << " ";
                f << std::endl;
            }
            if (!l.grid().is_at_infinity(it.end_indices())) {
                if (it.start_indices()!=it.end_indices()) {
                    for (int j=0;j<D;j++) f << (it.end_indices()[j]) << " ";
                    f << std::endl;
                }
            }

        }

        f << "object 2 class array type float rank 0 items "<< num<<" data follows" <<std::endl;
        for (typename LevelSetType::const_iterator_runs it(l);
                !it.is_finished();it.next()) {
            if (only_defined_grid_points) if (!it.is_defined()) continue;

            float dist;
            if (only_signs) {
                if (it.sign()==POS_SIGN) dist=limit; else dist=-limit;
            } else {
                dist=static_cast<float>(it.value());
                dist=std::min(limit,dist);
                dist=std::max(-limit,dist);
            }
            if (!l.grid().is_at_infinity(it.start_indices())) f << dist << std::endl;
            if (it.start_indices()!=it.end_indices()) if (!l.grid().is_at_infinity(it.end_indices())) f << dist << std::endl;
        }

        f << "attribute \"dep\" string \"positions\"" << std::endl;

        f << "object \"data\" class field" << std::endl;
        f << "component \"positions\" value 1" << std::endl;
        f << "component \"data\" value 2" << std::endl;
        f << "end" << std::endl;

        f.close();
    }
开发者ID:viennats,项目名称:viennats-dev,代码行数:73,代码来源:output.hpp


示例17: ParamPolicy

void TypePrinter::printFunctionProto(const FunctionProtoType *T, 
                                     std::string &S) { 
  // If needed for precedence reasons, wrap the inner part in grouping parens.
  if (!S.empty())
    S = "(" + S + ")";
  
  S += "(";
  std::string Tmp;
  PrintingPolicy ParamPolicy(Policy);
  ParamPolicy.SuppressSpecifiers = false;
  for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
    if (i) S += ", ";
    print(T->getArgType(i), Tmp);
    S += Tmp;
    Tmp.clear();
  }
  
  if (T->isVariadic()) {
    if (T->getNumArgs())
      S += ", ";
    S += "...";
  } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
    // Do not emit int() if we have a proto, emit 'int(void)'.
    S += "void";
  }
  
  S += ")";

  FunctionType::ExtInfo Info = T->getExtInfo();
  switch(Info.getCC()) {
  case CC_Default:
  default: break;
  case CC_C:
    S += " __attribute__((cdecl))";
    break;
  case CC_X86StdCall:
    S += " __attribute__((stdcall))";
    break;
  case CC_X86FastCall:
    S += " __attribute__((fastcall))";
    break;
  case CC_X86ThisCall:
    S += " __attribute__((thiscall))";
    break;
  case CC_X86Pascal:
    S += " __attribute__((pascal))";
    break;
  case CC_AAPCS:
    S += " __attribute__((pcs(\"aapcs\")))";
    break;
  case CC_AAPCS_VFP:
    S += " __attribute__((pcs(\"aapcs-vfp\")))";
    break;
  }
  if (Info.getNoReturn())
    S += " __attribute__((noreturn))";
  if (Info.getRegParm())
    S += " __attribute__((regparm (" +
        llvm::utostr_32(Info.getRegParm()) + ")))";
  
  AppendTypeQualList(S, T->getTypeQuals());

  switch (T->getRefQualifier()) {
  case RQ_None:
    break;
    
  case RQ_LValue:
    S += " &";
    break;
    
  case RQ_RValue:
    S += " &&";
    break;
  }

  if (T->hasDynamicExceptionSpec()) {
    S += " throw(";
    if (T->getExceptionSpecType() == EST_MSAny)
      S += "...";
    else
      for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
        if (I)
          S += ", ";

        std::string ExceptionType;
        print(T->getExceptionType(I), ExceptionType);
        S += ExceptionType;
      }
    S += ")";
  } else if (isNoexceptExceptionSpec(T->getExceptionSpecType())) {
    S += " noexcept";
    if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
      S += "(";
      llvm::raw_string_ostream EOut(S);
      T->getNoexceptExpr()->printPretty(EOut, 0, Policy);
      EOut.flush();
      S += EOut.str();
      S += ")";
    }
  }
//.........这里部分代码省略.........
开发者ID:ACSOP,项目名称:android_external_clang,代码行数:101,代码来源:TypePrinter.cpp


示例18: doAll

void doAll() {

    //
    // the looper
    //

    gSystem->Load("libTree.so");
    gSystem->Load("libPhysics.so");
    gSystem->Load("libEG.so");
    gSystem->Load("libMathCore.so");

    gSystem->Load("/tas/dlevans/HWW2012/CMSSW_5_2_3/src/LHAPDF-5.8.92b/lib/libLHAPDF.so");
    gSystem->Load("libCMS2NtupleMacrosLooper.so");

    //
    // create looper
    //

    // create a looper for a sample that was generated by using
    // CTEQ6LL.  Check if this is the case for your sample!
    // generally, LO samples are generated with CTEQ6LL and 
    // NLO samples are generated with CT10.  Note that in the 
    // CT10 case the central subset is at index 5, not 0.
    MyScanChain *looper_cteq6ll = new MyScanChain("cteq6ll.LHpdf", 0);

    //
    // run all pdf sets
    //

    std::vector<std::string> pdfSets;

    // CT10
    pdfSets.push_back("CT10");
    pdfSets.push_back("CT10as");
    // MSTW
    pdfSets.push_back("MSTW2008nlo68cl");
    pdfSets.push_back("MSTW2008nlo68cl_asmz+68cl");
    pdfSets.push_back("MSTW2008nlo68cl_asmz+68clhalf");
    pdfSets.push_back("MSTW2008nlo68cl_asmz-68cl");
    pdfSets.push_back("MSTW2008nlo68cl_asmz-68clhalf");
    // NNPDF
    pdfSets.push_back("NNPDF20_as_0116_100");
    pdfSets.push_back("NNPDF20_as_0117_100");
    pdfSets.push_back("NNPDF20_as_0118_100");
    pdfSets.push_back("NNPDF20_100");
    pdfSets.push_back("NNPDF20_as_0120_100");
    pdfSets.push_back("NNPDF20_as_0121_100");
    pdfSets.push_back("NNPDF20_as_0122_100");

    // data sample
    TChain *chain_ttbar = new TChain("Events");
    chain_ttbar->Add("/tas/dlevans_data/MCNtupling/CMSSW/CMSSW_5_3_2_patch4_V05-03-23/crab/makecms2ntuple/post_processed_ntuple.root");
 
    // do gensets 
    // the variation of the genset with respect to itself
    // is by definition 1.0, but we'll need this number later
    // stored just like all the others
    looper_cteq6ll->ScanChain("ttbar", chain_ttbar, "cteq6ll");

    // do other sets
    for (unsigned int i = 0; i < pdfSets.size(); ++i) {
        std::cout << "===== Doing =====> " << pdfSets[i] << std::endl;
        looper_cteq6ll->ScanChain("ttbar", chain_ttbar, pdfSets[i]);
    }

    //
    // write histograms
    // 

    const std::string outFile = "results.root";
    saveHist(outFile.c_str());
    deleteHistos();

    //
    // tidy up
    //

    delete looper_cteq6ll;
    delete chain_ttbar;
}
开发者ID:magania,项目名称:CMS2,代码行数:80,代码来源:doAll.C


示例19: printParen

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ tr1::shared_ptr类代码示例发布时间:2022-06-01
下一篇:
C++ std::streambuf类代码示例发布时间:2022-06-01
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap