本文整理汇总了C++中std::string类的典型用法代码示例。如果您正苦于以下问题:C++ string类的具体用法?C++ string怎么用?C++ string使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了string类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: operator
inline void operator() (const std::string& s)
{
if (s.empty()) return;
strtk::split(p_,s,*this,strtk::split_options::compress_delimiters);
}
示例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;
}
//.........这里部分代码省略.........
示例3: escapeString
std::string DatabaseODBC::escapeString(const std::string &s)
{
return escapeBlob( s.c_str(), s.length() );
}
示例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);
}
示例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();
}
示例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);
}
示例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)
//.........这里部分代码省略.........
示例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;
}
示例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();
}
示例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 {
//.........这里部分代码省略.........
示例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);
}
示例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;
}
示例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;
}
示例14: StringFrom
SimpleString StringFrom(const std::string& value)
{
return SimpleString(value.c_str());
}
示例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'; }
}