Пример #1
0
 inline void operator() (const std::string& s)
 {
    if (s.empty()) return;
    strtk::split(p_,s,*this,strtk::split_options::compress_delimiters);
 }
Пример #2
0
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;
    }
    TIFFSetField (m_tif, TIFFTAG_BITSPERSAMPLE, bps);
    TIFFSetField (m_tif, TIFFTAG_SAMPLEFORMAT, sampformat);

    int photo = (m_spec.nchannels > 1 ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK);
    TIFFSetField (m_tif, TIFFTAG_PHOTOMETRIC, photo);

    // ExtraSamples tag
    if (m_spec.nchannels > 3) {
        bool unass = m_spec.get_int_attribute("oiio:UnassociatedAlpha", 0);
        short e = m_spec.nchannels-3;
        std::vector<unsigned short> extra (e);
        for (int c = 0;  c < e;  ++c) {
            if (m_spec.alpha_channel == (c+3))
                extra[c] = unass ? EXTRASAMPLE_UNASSALPHA : EXTRASAMPLE_ASSOCALPHA;
            else
                extra[c] = EXTRASAMPLE_UNSPECIFIED;
        }
        TIFFSetField (m_tif, TIFFTAG_EXTRASAMPLES, e, &extra[0]);
    }

    // Default to LZW compression if no request came with the user spec
    if (! m_spec.find_attribute("compression"))
        m_spec.attribute ("compression", "lzw");

    ImageIOParameter *param;
    const char *str = NULL;

    // Did the user request separate planar configuration?
    m_planarconfig = PLANARCONFIG_CONTIG;
    if ((param = m_spec.find_attribute("planarconfig", TypeDesc::STRING)) ||
        (param = m_spec.find_attribute("tiff:planarconfig", TypeDesc::STRING))) {
        str = *(char **)param->data();
        if (str && Strutil::iequals (str, "separate")) {
            m_planarconfig = PLANARCONFIG_SEPARATE;
            if (! m_spec.tile_width) {
                // I can only seem to make separate planarconfig work when
                // rowsperstrip is 1.
                TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 1);
            }
        }
    }
    TIFFSetField (m_tif, TIFFTAG_PLANARCONFIG, m_planarconfig);

    // Automatically set date field if the client didn't supply it.
    if (! m_spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        m_spec.attribute ("DateTime", date);
    }

    // Write ICC profile, if we have anything
    const ImageIOParameter* icc_profile_parameter = m_spec.find_attribute(ICC_PROFILE_ATTR);
    if (icc_profile_parameter != NULL) {
        unsigned char *icc_profile = (unsigned char*)icc_profile_parameter->data();
        uint32 length = icc_profile_parameter->type().size();
        if (icc_profile && length)
            TIFFSetField (m_tif, TIFFTAG_ICCPROFILE, length, icc_profile);
    }

    if (Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace"), "sRGB"))
        m_spec.attribute ("Exif:ColorSpace", 1);

    // Deal with all other params
    for (size_t p = 0;  p < m_spec.extra_attribs.size();  ++p)
        put_parameter (m_spec.extra_attribs[p].name().string(),
                       m_spec.extra_attribs[p].type(),
                       m_spec.extra_attribs[p].data());

    std::vector<char> iptc;
    encode_iptc_iim (m_spec, iptc);
    if (iptc.size()) {
        iptc.resize ((iptc.size()+3) & (0xffff-3));  // round up
        TIFFSetField (m_tif, TIFFTAG_RICHTIFFIPTC, iptc.size()/4, &iptc[0]);
    }

    std::string xmp = encode_xmp (m_spec, true);
    if (! xmp.empty())
        TIFFSetField (m_tif, TIFFTAG_XMLPACKET, xmp.size(), xmp.c_str());
    
    TIFFCheckpointDirectory (m_tif);  // Ensure the header is written early
    m_checkpointTimer.start(); // Initialize the to the fileopen time
    m_checkpointItems = 0; // Number of tiles or scanlines we've written

    m_dither = (m_spec.format == TypeDesc::UINT8) ?
                    m_spec.get_int_attribute ("oiio:dither", 0) : 0;

    return true;
}
Пример #3
0
std::string DatabaseODBC::escapeString(const std::string &s)
{
	return escapeBlob( s.c_str(), s.length() );
}
Пример #4
0
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
0
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
0
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
0
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)
#define TYPE(CLASS, PARENT) case Type::CLASS: \
    print##CLASS(cast<CLASS##Type>(T), buffer); \
    break;
#include "clang/AST/TypeNodes.def"
  }
  
  // If we're adding the qualifiers as a prefix, do it now.
  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);
    }
  }
}
Пример #8
0
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
0
    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
0
// 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 {
    dimensionID[0] = atomDID_;
    dimensionID[1] = spatialDID_;
  }
  // Coord variable
  if (coordInfo.HasCrd()) {
    if ( NC::CheckErr( nc_def_var( ncid_, NCCOORDS, dataType, NDIM, dimensionID, &coordVID_)) ) {
      mprinterr("Error: Defining coordinates variable.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text( ncid_, coordVID_, "units", 8, "angstrom")) ) {
      mprinterr("Error: Writing coordinates variable units.\n");
      return 1;
    }
  }
  // Velocity variable
  if (coordInfo.HasVel()) {
    if ( NC::CheckErr( nc_def_var( ncid_, NCVELO, dataType, NDIM, dimensionID, &velocityVID_)) ) {
      mprinterr("Error: Defining velocities variable.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text( ncid_, velocityVID_, "units", 19, "angstrom/picosecond")) )
    {
      mprinterr("Error: Writing velocities variable units.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_double( ncid_, velocityVID_, "scale_factor", NC_DOUBLE, 1, 
                                        &Constants::AMBERTIME_TO_PS)) )
    {
      mprinterr("Error: Writing velocities scale factor.\n");
      return 1;
    }
  }
  // Force variable
  if (coordInfo.HasForce()) {
    if ( NC::CheckErr( nc_def_var( ncid_, NCFRC, dataType, NDIM, dimensionID, &frcVID_)) ) {
      mprinterr("Error: Defining forces variable\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text( ncid_, frcVID_, "units", 25, "kilocalorie/mole/angstrom")) )
    {
      mprinterr("Error: Writing forces variable units.\n");
      return 1;
    }
  }
  // Replica Temperature
  if (coordInfo.HasTemp()) {
    // NOTE: Setting dimensionID should be OK for Restart, will not be used.
    dimensionID[0] = frameDID_;
    if ( NC_defineTemperature( dimensionID, NDIM-2 ) ) return 1;
  }
  // Replica indices
  int remDimTypeVID = -1;
  if (coordInfo.HasReplicaDims()) {
    // Define number of replica dimensions
    remd_dimension_ = coordInfo.ReplicaDimensions().Ndims();
    int remDimDID = -1;
    if ( NC::CheckErr(nc_def_dim(ncid_, NCREMD_DIMENSION, remd_dimension_, &remDimDID)) ) {
      mprinterr("Error: Defining replica indices dimension.\n");
      return 1;
    }
    dimensionID[0] = remDimDID;
    // For each dimension, store the type
    if ( NC::CheckErr(nc_def_var(ncid_, NCREMD_DIMTYPE, NC_INT, 1, dimensionID, &remDimTypeVID)) ) 
    {
      mprinterr("Error: Defining replica dimension type variable.\n");
      return 1;
    }
    // Need to store the indices of replica in each dimension each frame
    // NOTE: THIS MUST BE MODIFIED IF NEW TYPES ADDED
    if (type == NC_AMBERENSEMBLE) {
      dimensionID[0] = frameDID_;
      dimensionID[1] = ensembleDID_;
      dimensionID[2] = remDimDID;
    } else if (type == NC_AMBERTRAJ) {
      dimensionID[0] = frameDID_;
      dimensionID[1] = remDimDID;
    } else {
      dimensionID[0] = remDimDID;
    }
    if (NC::CheckErr(nc_def_var(ncid_, NCREMD_INDICES, NC_INT, NDIM-1, dimensionID, &indicesVID_)))
    {
      mprinterr("Error: Defining replica indices variable ID.\n");
      return 1;
    }
    // TODO: Determine if groups are really necessary for restarts. If not, 
    // remove from AmberNetcdf.F90.
  }
  // Box Info
  if (coordInfo.HasBox()) {
    // Cell Spatial
    if ( NC::CheckErr( nc_def_dim( ncid_, NCCELL_SPATIAL, 3, &cell_spatialDID_)) ) {
      mprinterr("Error: Defining cell spatial dimension.\n");
      return 1;
    }
    dimensionID[0] = cell_spatialDID_;
    if ( NC::CheckErr( nc_def_var(ncid_, NCCELL_SPATIAL, NC_CHAR, 1, dimensionID, &cell_spatialVID_)))
    {
      mprinterr("Error: Defining cell spatial variable.\n");
      return 1;
    }
    // Cell angular
    if ( NC::CheckErr( nc_def_dim( ncid_, NCLABEL, NCLABELLEN, &labelDID_)) ) {
      mprinterr("Error: Defining label dimension.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_def_dim( ncid_, NCCELL_ANGULAR, 3, &cell_angularDID_)) ) {
      mprinterr("Error: Defining cell angular dimension.\n"); 
      return 1;
    }
    dimensionID[0] = cell_angularDID_;
    dimensionID[1] = labelDID_;
    if ( NC::CheckErr( nc_def_var( ncid_, NCCELL_ANGULAR, NC_CHAR, 2, dimensionID, 
                                 &cell_angularVID_)) )
    {
      mprinterr("Error: Defining cell angular variable.\n");
      return 1;
    }
    // Setup dimensions for Box
    // NOTE: This must be modified if more types added
    int boxdim;
    if (type == NC_AMBERENSEMBLE) {
      dimensionID[0] = frameDID_;
      dimensionID[1] = ensembleDID_;
      boxdim = 2;
    } else if (type == NC_AMBERTRAJ) {
      dimensionID[0] = frameDID_;
      boxdim = 1;
    } else {
      boxdim = 0;
    }
    dimensionID[boxdim] = cell_spatialDID_;
    if ( NC::CheckErr( nc_def_var( ncid_, NCCELL_LENGTHS, NC_DOUBLE, NDIM-1, dimensionID,
                                 &cellLengthVID_)) )
    {
      mprinterr("Error: Defining cell length variable.\n"); 
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text( ncid_, cellLengthVID_, "units", 8, "angstrom")) ) {
      mprinterr("Error: Writing cell length variable units.\n");
      return 1;
    }
    dimensionID[boxdim] = cell_angularDID_;
    if ( NC::CheckErr( nc_def_var( ncid_, NCCELL_ANGLES, NC_DOUBLE, NDIM-1, dimensionID,
                                 &cellAngleVID_)) )
    {
      mprinterr("Error: Defining cell angle variable.\n");
      return 1;
    }
    if ( NC::CheckErr( nc_put_att_text( ncid_, cellAngleVID_, "units", 6, "degree")) ) {
      mprinterr("Error: Writing cell angle variable units.\n");
      return 1;
    }
  }

  // Attributes
  if (NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"title",title.size(),title.c_str())) ) {
    mprinterr("Error: Writing title.\n");
    return 1;
  }
  if (NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"application",5,"AMBER")) ) {
    mprinterr("Error: Writing application.\n");
    return 1;
  }
  if (NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"program",7,"cpptraj")) ) {
    mprinterr("Error: Writing program.\n");
    return 1;
  }
  if (NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"programVersion",
                                 NETCDF_VERSION_STRLEN, NETCDF_VERSION_STRING)) ) 
  {
    mprinterr("Error: Writing program version.\n");
    return 1;
  }
  // TODO: Make conventions a static string
  bool errOccurred = false;
  if ( type == NC_AMBERENSEMBLE )
    errOccurred = NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",13,"AMBERENSEMBLE"));
  else if ( type == NC_AMBERTRAJ )
    errOccurred = NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",5,"AMBER"));
  else
    errOccurred = NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",12,"AMBERRESTART"));
  if (errOccurred) {
    mprinterr("Error: Writing conventions.\n");
    return 1;
  }
  if (NC::CheckErr(nc_put_att_text(ncid_,NC_GLOBAL,"ConventionVersion",3,"1.0")) ) {
    mprinterr("Error: Writing conventions version.\n");
    return 1;
  }
  
  // Set fill mode
  if (NC::CheckErr(nc_set_fill(ncid_, NC_NOFILL, dimensionID))) {
    mprinterr("Error: NetCDF setting fill value.\n");
    return 1;
  }

  // End netcdf definitions
  if (NC::CheckErr(nc_enddef(ncid_))) {
    mprinterr("NetCDF error on ending definitions.");
    return 1;
  }

  // Specify spatial dimension labels
  start_[0] = 0;
  count_[0] = 3;
  char xyz[3];
  xyz[0] = 'x'; 
  xyz[1] = 'y'; 
  xyz[2] = 'z';
  if (NC::CheckErr(nc_put_vara_text(ncid_, spatialVID_, start_, count_, xyz))) {
    mprinterr("Error on NetCDF output of spatial VID 'x', 'y' and 'z'");
    return 1;
  }
  if ( coordInfo.HasBox() ) {
    xyz[0] = 'a'; 
    xyz[1] = 'b'; 
    xyz[2] = 'c';
    if (NC::CheckErr(nc_put_vara_text(ncid_, cell_spatialVID_, start_, count_, xyz))) {
      mprinterr("Error on NetCDF output of cell spatial VID 'a', 'b' and 'c'");
      return 1;
    }
    char abc[15] = { 'a', 'l', 'p', 'h', 'a',
                     'b', 'e', 't', 'a', ' ',
                     'g', 'a', 'm', 'm', 'a' };
    start_[0] = 0; 
    start_[1] = 0;
    count_[0] = 3; 
    count_[1] = NCLABELLEN;
    if (NC::CheckErr(nc_put_vara_text(ncid_, cell_angularVID_, start_, count_, abc))) {
      mprinterr("Error on NetCDF output of cell angular VID 'alpha', 'beta ' and 'gamma'");
      return 1;
    }
  }

  // Store the type of each replica dimension.
  if (coordInfo.HasReplicaDims()) {
    ReplicaDimArray const& remdDim = coordInfo.ReplicaDimensions();
    start_[0] = 0;
    count_[0] = remd_dimension_;
    int* tempDims = new int[ remd_dimension_ ];
    for (int i = 0; i < remd_dimension_; ++i)
      tempDims[i] = remdDim[i];
    if (NC::CheckErr(nc_put_vara_int(ncid_, remDimTypeVID, start_, count_, tempDims))) {
      mprinterr("Error: writing replica dimension types.\n");
      delete[] tempDims;
      return 1;
    }
    delete[] tempDims;
  }

  return 0;
}
Пример #11
0
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
0
// 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
0
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;
}
SimpleString StringFrom(const std::string& value)
{
	return SimpleString(value.c_str());
}
Пример #15
0
///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'; }
}
Пример #16
0
    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();
    }
Пример #17
0
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 += ")";
    }
  }

  print(T->getResultType(), S);
}
Пример #18
0
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;
}
Пример #19
0
void TypePrinter::printParen(const ParenType *T, std::string &S) {
  if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
    S = '(' + S + ')';
  print(T->getInnerType(), S);
}
Пример #20
0
void WorldSession::SendTrainerList(uint64 guid, const std::string &strTitle)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: SendTrainerList");

    Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
    if (!unit)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: SendTrainerList - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid)));
        return;
    }

    // remove fake death
    if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    // trainer list loaded at check;
    if (!unit->isCanTrainingOf(_player, true))
        return;

    CreatureTemplate const *creatureInfo = unit->GetCreatureTemplate();

    if (!creatureInfo)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: SendTrainerList - (GUID: %u) NO CREATUREINFO!", GUID_LOPART(guid));
        return;
    }

    TrainerSpellData const* trainer_spells = unit->GetTrainerSpells();
    if (!trainer_spells)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: SendTrainerList - Training spells not found for creature (GUID: %u Entry: %u)",
            GUID_LOPART(guid), unit->GetEntry());
        return;
    }

    WorldPacket data(SMSG_TRAINER_LIST, 8 + 4 + 4 + trainer_spells->spellList.size() * 38 + strTitle.size() + 1);
    data << guid;
    data << uint32(trainer_spells->trainerType);
    data << uint32(1);

    size_t count_pos = data.wpos();
    data << uint32(trainer_spells->spellList.size());

    // reputation discount
    float fDiscountMod = _player->GetReputationPriceDiscount(unit);

    uint32 count = 0;
    for (TrainerSpellMap::const_iterator itr = trainer_spells->spellList.begin(); itr != trainer_spells->spellList.end(); ++itr)
    {
        TrainerSpell const* tSpell = &itr->second;
        TrainerSpellState state = _player->GetTrainerSpellState(tSpell);

        data << uint32(tSpell->spell);                      // learned spell (or cast-spell in profession case)
        data << uint8(state);
        data << uint32(floor(tSpell->spellCost * fDiscountMod));

        data << uint8(tSpell->reqLevel);
        data << uint32(tSpell->reqSkill);
        data << uint32(tSpell->reqSkillValue);
        data << uint32(0);
        data << uint32(0);
        data << uint32(0);
        data << uint32(0);

        ++count;
    }

    data << strTitle;

    data.put<uint32>(count_pos, count);
    SendPacket(&data);
}
Пример #21
0
static bool LoadDB2_assert_print(uint32 fsize, uint32 rsize, const std::string& filename)
{
    sLog->outError("Size of '%s' setted by format string (%u) not equal size of C++ structure (%u).", filename.c_str(), fsize, rsize);

    // ASSERT must fail after function call
    return false;
}
Пример #22
0
 bool dir_exists(const std::string& path) {
     fsnsp::path p(path.c_str());
     return (fsnsp::exists(p) && fsnsp::is_directory(p));
 }
Пример #23
0
void Animation::handleTextKey(AnimState &state, const std::string &groupname, const NifOgre::TextKeyMap::const_iterator &key)
{
    //float time = key->first;
    const std::string &evt = key->second;

    if(evt.compare(0, 7, "sound: ") == 0)
    {
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
        sndMgr->playSound3D(mPtr, evt.substr(7), 1.0f, 1.0f);
        return;
    }
    if(evt.compare(0, 10, "soundgen: ") == 0)
    {
        std::string soundgen = evt.substr(10);

        // The event can optionally contain volume and pitch modifiers
        float volume=1.f, pitch=1.f;
        if (soundgen.find(" ") != std::string::npos)
        {
            std::vector<std::string> tokens;
            split(soundgen, ' ', tokens);
            soundgen = tokens[0];
            if (tokens.size() >= 2)
                volume = Ogre::StringConverter::parseReal(tokens[1]);
            if (tokens.size() >= 3)
                pitch = Ogre::StringConverter::parseReal(tokens[2]);
        }

        std::string sound = mPtr.getClass().getSoundIdFromSndGen(mPtr, soundgen);
        if(!sound.empty())
        {
            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            MWBase::SoundManager::PlayType type = MWBase::SoundManager::Play_TypeSfx;
            if(evt.compare(10, evt.size()-10, "left") == 0 || evt.compare(10, evt.size()-10, "right") == 0)
                type = MWBase::SoundManager::Play_TypeFoot;
            sndMgr->playSound3D(mPtr, sound, volume, pitch, type);
        }
        return;
    }

    if(evt.compare(0, groupname.size(), groupname) != 0 ||
       evt.compare(groupname.size(), 2, ": ") != 0)
    {
        // Not ours, skip it
        return;
    }
    size_t off = groupname.size()+2;
    size_t len = evt.size() - off;

    if(evt.compare(off, len, "loop start") == 0)
        state.mLoopStartTime = key->first;
    else if(evt.compare(off, len, "loop stop") == 0)
        state.mLoopStopTime = key->first;
    else if(evt.compare(off, len, "equip attach") == 0)
        showWeapons(true);
    else if(evt.compare(off, len, "unequip detach") == 0)
        showWeapons(false);
    else if(evt.compare(off, len, "chop hit") == 0)
        mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Chop);
    else if(evt.compare(off, len, "slash hit") == 0)
        mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Slash);
    else if(evt.compare(off, len, "thrust hit") == 0)
        mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Thrust);
    else if(evt.compare(off, len, "hit") == 0)
    {
        if (groupname == "attack1")
            mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Chop);
        else if (groupname == "attack2")
            mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Slash);
        else if (groupname == "attack3")
            mPtr.getClass().hit(mPtr, ESM::Weapon::AT_Thrust);
        else
            mPtr.getClass().hit(mPtr);
    }
    else if (evt.compare(off, len, "shoot attach") == 0)
        attachArrow();
    else if (evt.compare(off, len, "shoot release") == 0)
        releaseArrow();
    else if (evt.compare(off, len, "shoot follow attach") == 0)
        attachArrow();

    else if (groupname == "spellcast" && evt.substr(evt.size()-7, 7) == "release")
        MWBase::Environment::get().getWorld()->castSpell(mPtr);

    else if (groupname == "shield" && evt.compare(off, len, "block hit") == 0)
        mPtr.getClass().block(mPtr);
}
Пример #24
0
// initialize module vector and log file, level and remote log service 
// according to parameters in properties.
am_status_t Log::initialize(const Properties& properties)
    throw()
{
    am_status_t status = AM_SUCCESS;
    // initialize module list.
    if (!initialized)
        status = initialize();

    if (status == AM_SUCCESS) {
	// initialize log file name and level from properties. 
	try {
	    ScopeLock myLock(*lockPtr);
	    logFileName = 
		properties.get(AM_AGENT_DEBUG_FILE_PROPERTY, "", false);
	    logRotation = 
	        properties.getBool(AM_AGENT_DEBUG_FILE_ROTATE_PROPERTY, true);
	    maxLogFileSize = 
	        properties.getPositiveNumber(AM_AGENT_DEBUG_FILE_SIZE_PROPERTY, 
                    DEBUG_FILE_DEFAULT_SIZE);
            if (maxLogFileSize < DEBUG_FILE_MIN_SIZE) {
               maxLogFileSize = DEBUG_FILE_MIN_SIZE;
            }

            auditLogFileName =
                properties.get(AM_AUDIT_LOCAL_LOG_FILE_PROPERTY, "", false);

	    if (! pSetLogFile(logFileName)) {
		log(ALL_MODULES, LOG_ERROR,
		    "Unable to open agent debug file: '%s', errno = %d",
		    logFileName.c_str(), errno);
            }

            if (!setAuditLogFile(
                   auditLogFileName,
                   properties.getBool(
                       AM_AUDIT_LOCAL_LOG_ROTATE_PROPERTY, true),
                   properties.getPositiveNumber(
                       AM_AUDIT_LOCAL_LOG_FILE_SIZE_PROPERTY, LOCAL_AUDIT_FILE_DEFAULT_SIZE))) 
            {
                log(ALL_MODULES, LOG_ERROR,
                    "Unable to open local audit file: '%s', errno = %d",
                    auditLogFileName.c_str(), errno);
            }

            // if no log level specified, set default to "all:LOG_INFO".
	    std::string logLevels = 
		properties.get(AM_AGENT_DEBUG_LEVEL_PROPERTY, "all:3", false);
	    status = pSetLevelsFromString(logLevels); 
	}
	catch (NSPRException& exn) {
	    status = AM_NSPR_ERROR;
	}
	catch (std::bad_alloc& exb) {
	    status = AM_NO_MEMORY;
	}
	catch (std::exception& exs) {
	    status = AM_INVALID_ARGUMENT;
	}
	catch (...) {
	    status = AM_FAILURE;
	}
    }
    return status;
}
Пример #25
0
void Animation::setObjectRoot(const std::string &model, bool baseonly)
{
    OgreAssert(mAnimSources.empty(), "Setting object root while animation sources are set!");

    mSkelBase = NULL;
    mObjectRoot.setNull();

    if(model.empty())
        return;

    std::string mdlname = Misc::StringUtils::lowerCase(model);
    std::string::size_type p = mdlname.rfind('\\');
    if(p == std::string::npos)
        p = mdlname.rfind('/');
    if(p != std::string::npos)
        mdlname.insert(mdlname.begin()+p+1, 'x');
    else
        mdlname.insert(mdlname.begin(), 'x');
    if(!Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup(mdlname))
    {
        mdlname = model;
        Misc::StringUtils::toLower(mdlname);
    }

    mObjectRoot = (!baseonly ? NifOgre::Loader::createObjects(mInsert, mdlname) :
                               NifOgre::Loader::createObjectBase(mInsert, mdlname));
    if(mObjectRoot->mSkelBase)
    {
        mSkelBase = mObjectRoot->mSkelBase;

        Ogre::AnimationStateSet *aset = mObjectRoot->mSkelBase->getAllAnimationStates();
        Ogre::AnimationStateIterator asiter = aset->getAnimationStateIterator();
        while(asiter.hasMoreElements())
        {
            Ogre::AnimationState *state = asiter.getNext();
            state->setEnabled(false);
            state->setLoop(false);
        }

        // Set the bones as manually controlled since we're applying the
        // transformations manually
        Ogre::SkeletonInstance *skelinst = mObjectRoot->mSkelBase->getSkeleton();
        Ogre::Skeleton::BoneIterator boneiter = skelinst->getBoneIterator();
        while(boneiter.hasMoreElements())
            boneiter.getNext()->setManuallyControlled(true);

        // Reattach any objects that have been attached to this one
        ObjectAttachMap::iterator iter = mAttachedObjects.begin();
        while(iter != mAttachedObjects.end())
        {
            if(!skelinst->hasBone(iter->second))
                mAttachedObjects.erase(iter++);
            else
            {
                mSkelBase->attachObjectToBone(iter->second, iter->first);
                ++iter;
            }
        }
    }
    else
        mAttachedObjects.clear();

    for(size_t i = 0;i < mObjectRoot->mControllers.size();i++)
    {
        if(mObjectRoot->mControllers[i].getSource().isNull())
            mObjectRoot->mControllers[i].setSource(mAnimationTimePtr[0]);
    }
}
Пример #26
0
bool Log::setAuditLogFile(const std::string& name,
     bool localAuditLogRotate,
     long localAuditFileSize)
throw () {
    bool okay = true;
    std::string newName;
    FILE *newAuditLogFile = NULL;
    int retValue = 0;

    if (name.size() > 0) {
        if (localAuditLogRotate) {
            char hdr[100];
            PRUint32 len;
            int counter = 1;
            bool fileExists = true;

            if (auditLogFile == stderr) {
                // Open the log file for the first time
                newAuditLogFile = std::fopen(name.c_str(), "a");
                if (newAuditLogFile != NULL) {
                    auditLogFile = newAuditLogFile;
                } else {
                    okay = false;
                }
            } else {
                // Start the process of log rotation
                while (fileExists) {
                    len = PR_snprintf(hdr, sizeof (hdr), "%d", counter);
                    if (len > 0) {
                        std::string appendString(hdr);
                        newName = name + "-" + appendString;
                    }
                    if ((PR_Access(newName.c_str(), PR_ACCESS_EXISTS)) == 
                            PR_SUCCESS) {
                        counter++;
                    } else {
                        fileExists = false;
                    }
                }
                std::fflush(auditLogFile);
                std::fclose(auditLogFile);
                retValue = rename(name.c_str(), newName.c_str());
                if (retValue != -1) {
                    newAuditLogFile = std::fopen(name.c_str(), "a");
                    if (newAuditLogFile != NULL) {
                        auditLogFile = newAuditLogFile;
                        currentAuditLogFileSize = 0;
                    } else {
                        auditLogFile = stderr;
                    }
                } else {
                    auditLogFile = stderr;
                }
            }
        } else {
            // localAuditLogRotate is false, just create one log file and write to it
            newAuditLogFile = std::fopen(name.c_str(), "a");
            if (newAuditLogFile != NULL) {
                auditLogFile = newAuditLogFile;
            } else {
                okay = false;
            }
        }
    } else {
        okay = false;
    }

    return okay;
}
Пример #27
0
void ui_menu_control_device_image::hook_load(std::string name, bool softlist)
{
	if (image->is_reset_on_load()) image->set_init_phase();
	image->load(name.c_str());
	ui_menu::stack_pop(machine());
}
Пример #28
0
// this should not throw exception since it is called often in a 
// catch block to log an error resulting from an exception.
void Log::vlog(ModuleId module, Level level, const char *format,
	       std::va_list args) 
    throw()
{
    if (initialized) {
	if (module >= moduleList->size()) {
	    module = ALL_MODULES;
	}

        char *logMsg = PR_vsmprintf(format, args);
	// call user defined logger if any.
	if (loggerFunc != NULL) {
	    loggerFunc((*moduleList)[module].name.c_str(),  
		       static_cast<am_log_level_t>(static_cast<int>(level)),
		       logMsg);
	}

	// do default log.
	if ((*moduleList)[module].level >= level) {

	    // format: 
	    // year-month-day hour:min:sec.usec level pid:thread module: msg
	    // get level string		
	    std::size_t levelLabelIndex = getLevelString(level);
	    char levelStr[50]; 
	    PRUint32 llen;
	    if (levelLabelIndex < numLabels) {
		llen = PR_snprintf(levelStr, sizeof(levelStr),
				       "%s", levelLabels[levelLabelIndex]);
	    } else {
		llen = PR_snprintf(levelStr, sizeof(levelStr), "%d", level);
	    }

	    if (llen > 0) { 
		// get time.
		PRExplodedTime now;
		PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &now);
    
		// format header and msg.
		PRUint32 len;
		char hdr[100];
		len = PR_snprintf(hdr, sizeof(hdr), 
				  "%d-%02d-%02d %02d:%02d:%02d.%03d"
				  "%8s %u:%p %s: %%s\n",
				  now.tm_year, now.tm_month+1, now.tm_mday,
				  now.tm_hour, now.tm_min, now.tm_sec, 
				  now.tm_usec / 1000,
				  levelStr,
				  getpid(), PR_GetCurrentThread(),
				  (*moduleList)[module].name.c_str());
		if (len > 0) {
                  if (logRotation) {
                    if ((currentLogFileSize + 1000) < maxLogFileSize) {
		       std::fprintf(logFile, hdr, logMsg);
		       std::fflush(logFile);
                    } else {
    		      ScopeLock scopeLock(*lockPtr);
                      currentLogFileSize = ftell(logFile);
                      if ((currentLogFileSize + 1000) > maxLogFileSize) {
                         // Open a new log file
	                 if (!pSetLogFile(logFileName)) {
		                 log(ALL_MODULES, LOG_ERROR,
		                 "Unable to open log file: '%s', errno = %d",
		                 logFileName.c_str(), errno);
	                }
                      }
		      std::fprintf(logFile, hdr, logMsg);
		      std::fflush(logFile);
                    }
                    currentLogFileSize = ftell(logFile);
                  } else {
		      std::fprintf(logFile, hdr, logMsg);
		      std::fflush(logFile);
                  }
		}
	     }
	}

	// Remote Logging starts here.
	if (module == remoteModule) {
	    if (remoteInitialized) {
		bool doLogRemotely = 
		    ((*moduleList)[module].level >= Log::LOG_AUTH_REMOTE) &&
		    ((*moduleList)[module].level & level);

		if (doLogRemotely) {
		    am_status_t status;
		    status = rmtLogSvc->logMessage(logMsg);
		    if(status != AM_SUCCESS) {
			Log::log(Log::ALL_MODULES, Log::LOG_ERROR,
			    "Log::vlog(): Error logging message [%s] "
			    "to remote server. Error: %s.", 
			    logMsg, am_status_to_string(status));
		    }
		}
	    } else {
		Log::log(Log::ALL_MODULES, Log::LOG_ERROR,
		    "Log::vlog(): Remote logging service not initialized. "
		    "Cannot log message to remote server.");
	    }
	}
	PR_smprintf_free(logMsg);
    }
    return;
}
Пример #29
0
	numerator*=num;
	denominator*=num;
}

// @author Andre Allan Ponce
Fraction::operator double(){
	return (double)numerator / (double)denominator;
}

/*
	overloads extraction operator for Fraction
	input relies on '/' char to denote numerator or denominator
	@author Andre Allan Ponce
*/
std::istream& operator>>(std::istream& in, Fraction& f){
	std::string line;
	in >> line;
	int mid = line.find("/"); // find method locates index where the char is located
	if(mid > -1){ // find returns -1 if not char is not found
		int num = atoi(line.substr(0,mid).c_str()); // converts first half of string to int
		int den = atoi(line.substr(mid+1).c_str()); // converts second half of string to int (after the '/')
		if(den != 0){ // check if the denominator is 0, because thats bad
			f.numerator = num;
			f.denominator = den;
		}
		else{
			std::cout << "you can't divide by zero"; // you really can't
			f.denominator = 1;
		}
		f.simplify(); 
	}
Пример #30
0
 TempLocale::TempLocale( std::string tempLocale )
 {
   oldLocale = setlocale(LC_ALL, NULL);
   setlocale(LC_ALL, tempLocale.c_str());
 }