Example #1
0
inline void check_is_negative(const mpl::false_&)
{
   BOOST_THROW_EXCEPTION(std::range_error("Attempt to assign a negative value to an unsigned type."));
}
Example #2
0
int
main( int argc, char** argv )
{
	//std::ofstream logFile( "Log.txt" );
        //SET_LOUT( logFile );

        //D_COMMAND( std::ofstream debugFile( "Debug.txt" ); );
        //SET_DOUT( debugFile );

	//XInitThreads();
	ApplicationManager appManager;

	boost::filesystem::path executablePath(argv[0]);
	boost::filesystem::path dataDirName = GET_SETTINGS( "application.data_directory", std::string, (boost::filesystem::path(argv[0]).parent_path() / "data").string() );
	//If we cannot locate data directory - try other posiible locations
	if (!boost::filesystem::exists(dataDirName) || !boost::filesystem::is_directory(dataDirName)) {
		std::vector<boost::filesystem::path> possibleDataDirs;
		possibleDataDirs.push_back(boost::filesystem::current_path() / "data");
		possibleDataDirs.push_back(executablePath.parent_path() / "data");
		possibleDataDirs.push_back(executablePath.parent_path().parent_path() / "data");

		std::vector<boost::filesystem::path>::const_iterator it = possibleDataDirs.begin();
		bool found = false;
		LOG( "Trying to locate 'data' directory:" );
		while (!found && it != possibleDataDirs.end()) {
			LOG_CONT( "\tChecking: " << it->string() << " ... ");
			if (boost::filesystem::exists(*it) && boost::filesystem::is_directory(*it)) {
				dataDirName = *it;
				SET_SETTINGS( "application.data_directory", std::string, dataDirName.string() );
				found = true;
				LOG( "SUCCESS" );
			} else {
				LOG( "FAILED" );
			}
			++it;
		}
		if (!found) {
			BOOST_THROW_EXCEPTION( M4D::ErrorHandling::EDirNotFound() );
		}
	}
	boost::filesystem::path dirName = GET_SETTINGS( "gui.icons_directory", std::string, ( dataDirName / "icons" ).string() );
	appManager.setIconsDirectory(dirName);
	appManager.initialize( argc, argv );

	try {
		//processCommandLine( argc, argv );
		ViewerWindow viewer;
		appManager.setMainWindow( viewer );

		createModules();

		appManager.loadModules();
		viewer.showMaximized();
		return appManager.exec();
	} catch ( std::exception &e )
	{
		QMessageBox::critical ( NULL, "Exception", QString( e.what() ) );
	} 
	catch (...) {
		QMessageBox::critical ( NULL, "Exception", "Unknown error" );
	}
	
	return 1;
}
Example #3
0
void instantiator::validate(const field_definition& fd) const {
    const auto sn(fd.name().simple());
    if (fd.name().simple().empty()) {
        BOOST_LOG_SEV(lg, error) << empty_simple_name;
        BOOST_THROW_EXCEPTION(instantiation_error(empty_simple_name));
    }

    if (!is_instantiable(fd)) {
        BOOST_LOG_SEV(lg, error) << field_not_instantiable << sn;
        BOOST_THROW_EXCEPTION(instantiation_error(field_not_instantiable + sn));
    }

    if (!fd.name().qualified().empty()) {
        BOOST_LOG_SEV(lg, error) << qualified_name_not_empty << sn;
        BOOST_THROW_EXCEPTION(
            instantiation_error(qualified_name_not_empty + sn));
    }

    if (fd.definition_type() == field_definition_types::global_template) {
        if (!fd.ownership_hierarchy().facet_name().empty()) {
            BOOST_LOG_SEV(lg, error) << facet_name_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(facet_name_not_empty + sn));
        }

        if (!fd.ownership_hierarchy().formatter_name().empty()) {
            BOOST_LOG_SEV(lg, error) << formatter_name_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(formatter_name_not_empty + sn));
        }

        if (!fd.ownership_hierarchy().formatter_group_name().empty()) {
            BOOST_LOG_SEV(lg, error) << formatter_group_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(formatter_group_not_empty + sn));
        }
    }

    if (fd.definition_type() == field_definition_types::facet_template) {
        if (!fd.ownership_hierarchy().facet_name().empty()) {
            BOOST_LOG_SEV(lg, error) << facet_name_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(facet_name_not_empty + sn));
        }

        if (!fd.ownership_hierarchy().formatter_group_name().empty()) {
            BOOST_LOG_SEV(lg, error) << formatter_group_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(formatter_group_not_empty + sn));
        }

        if (!fd.ownership_hierarchy().formatter_name().empty()) {
            BOOST_LOG_SEV(lg, error) << formatter_name_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(formatter_name_not_empty + sn));
        }
    }

    if (fd.definition_type() == field_definition_types::formatter_template) {
        if (!fd.ownership_hierarchy().formatter_name().empty()) {
            BOOST_LOG_SEV(lg, error) << formatter_name_not_empty << sn;
            BOOST_THROW_EXCEPTION(
                instantiation_error(formatter_name_not_empty + sn));
        }
    }
}
Example #4
0
// TODO: prototype changed - will need rejigging.
ExecutionResult MixClient::debugTransaction(Transaction const& _t, State const& _state, EnvInfo const& _envInfo, bool _call)
{
	State execState = _state;
	execState.addBalance(_t.sender(), _t.gas() * _t.gasPrice()); //give it enough balance for gas estimation
	eth::ExecutionResult er;
	Executive execution(execState, _envInfo);
	execution.setResultRecipient(er);
	execution.initialize(_t);
	execution.execute();

	std::vector<MachineState> machineStates;
	std::vector<unsigned> levels;
	std::vector<MachineCode> codes;
	std::map<bytes const*, unsigned> codeIndexes;
	std::vector<bytes> data;
	std::map<bytesConstRef const*, unsigned> dataIndexes;
	bytes const* lastCode = nullptr;
	bytesConstRef const* lastData = nullptr;
	unsigned codeIndex = 0;
	unsigned dataIndex = 0;
	auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt)
	{
		VM& vm = *static_cast<VM*>(voidVM);
		ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
		if (lastCode == nullptr || lastCode != &ext.code)
		{
			auto const& iter = codeIndexes.find(&ext.code);
			if (iter != codeIndexes.end())
				codeIndex = iter->second;
			else
			{
				codeIndex = codes.size();
				codes.push_back(MachineCode({ext.myAddress, ext.code}));
				codeIndexes[&ext.code] = codeIndex;
			}
			lastCode = &ext.code;
		}

		if (lastData == nullptr || lastData != &ext.data)
		{
			auto const& iter = dataIndexes.find(&ext.data);
			if (iter != dataIndexes.end())
				dataIndex = iter->second;
			else
			{
				dataIndex = data.size();
				data.push_back(ext.data.toBytes());
				dataIndexes[&ext.data] = dataIndex;
			}
			lastData = &ext.data;
		}

		if (levels.size() < ext.depth)
			levels.push_back(machineStates.size() - 1);
		else
			levels.resize(ext.depth);

		machineStates.push_back(MachineState{
									steps,
									vm.curPC(),
									inst,
									newMemSize,
									static_cast<u256>(gas),
									vm.stack(),
									vm.memory(),
									gasCost,
									ext.state().storage(ext.myAddress),
									std::move(levels),
									codeIndex,
									dataIndex
								});
	};

	execution.go(onOp);
	execution.finalize();

	switch (er.excepted)
	{
	case TransactionException::None:
		break;
	case TransactionException::NotEnoughCash:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Insufficient balance for contract deployment"));
	case TransactionException::OutOfGasIntrinsic:
	case TransactionException::OutOfGasBase:
	case TransactionException::OutOfGas:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas"));
	case TransactionException::BlockGasLimitReached:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Block gas limit reached"));
	case TransactionException::BadJumpDestination:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Solidity exception (bad jump)"));
	case TransactionException::OutOfStack:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Out of stack"));
	case TransactionException::StackUnderflow:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Stack underflow"));
		//these should not happen in mix
	case TransactionException::Unknown:
	case TransactionException::BadInstruction:
	case TransactionException::InvalidSignature:
	case TransactionException::InvalidNonce:
	case TransactionException::InvalidFormat:
	case TransactionException::BadRLP:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Internal execution error"));
	}

	ExecutionResult d;
	d.inputParameters = _t.data();
	d.result = er;
	d.machineStates = machineStates;
	d.executionCode = std::move(codes);
	d.transactionData = std::move(data);
	d.address = _t.receiveAddress();
	d.sender = _t.sender();
	d.value = _t.value();
	d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend;
	if (_t.isCreation())
		d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce())));
	if (!_call)
		d.transactionIndex = m_postMine.pending().size();
	d.executonIndex = m_executions.size();
	return d;
}
Example #5
0
 void checkError() const override
 {
     if (getErrno()) {
         BOOST_THROW_EXCEPTION(SystemError(getErrno()));
     }
 }
Example #6
0
vanilla::object::ptr vanilla::object::abs()
{
    BOOST_THROW_EXCEPTION(error::bad_unary_operation_error()
        << error::operation_name("+")
        << error::first_operand(shared_from_this()));
}
Example #7
0
    void property::update(bitstream &stream) {
        #ifdef TEST_SKIPPING
            uint32_t cur = stream.position();
            property::skip(stream, prop);
            uint32_t diff1 = stream.position() - cur;
            stream.seekBackward(diff1);

            // assert that seeking backwards worked and we have a clean state
            assert ( cur == stream.position() );
        #endif // TEST_SKIPPING

        switch (prop->getType()) {
            // Read Integer
            case sendprop::T_Int:
                readInt(stream, this);
                break;

            // Read Float
            case sendprop::T_Float:
                set(readFloat(stream, this));
                break;

            // Read 3D Vector
            case sendprop::T_Vector: {
                std::array<float, 3> vec;
                readVector(vec, stream, this);
                set(std::move(vec));
            } break;

            // Read 2D
            case sendprop::T_VectorXY: {
                std::array<float, 2> vec;
                readVectorXY(vec, stream, this);
                set(std::move(vec));
            } break;

            // Read String
            case sendprop::T_String: {
                char str[PROPERTY_MAX_STRING_LENGTH + 1];
                uint32_t length = readString(str, stream);
                set(std::string(str, length));
            } break;

            // Read Array
            case sendprop::T_Array:{
                std::vector<property> vec;
                readArray(vec, stream, prop);
                set(std::move(vec));
            } break;

            // Read 64 bit Integer
            case sendprop::T_Int64:
                readInt64(stream, this);
                break;

            default:
                BOOST_THROW_EXCEPTION( propertyInvalidType()
                    << (EArgT<1, uint32_t>::info(prop->getType()))
                );
                break;
        }

        #ifdef TEST_SKIPPING
            uint32_t diff2 = stream.position() - cur;
            if (diff2 != diff1) {
                std::cout << "Skip failed: " << diff1 << " (skip) " << diff2 << " (read) " << std::endl;
                std::cout << "Type ID: " << prop->getType() << std::endl;
                exit(0);
            }
        #endif // TEST_SKIPPING
    }
void
FaceQueryFilter::wireDecode(const Block& block)
{
  //all fields are optional
  if (block.type() != tlv::nfd::FaceQueryFilter) {
    BOOST_THROW_EXCEPTION(Error("expecting FaceQueryFilter block"));
  }

  m_wire = block;
  m_wire.parse();
  Block::element_const_iterator val = m_wire.elements_begin();

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::FaceId) {
    m_faceId = readNonNegativeInteger(*val);
    m_hasFaceId = true;
    ++val;
  }
  else {
    m_hasFaceId = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::UriScheme) {
    m_uriScheme.assign(reinterpret_cast<const char*>(val->value()), val->value_size());
    m_hasUriScheme = true;
    ++val;
  }
  else {
    m_hasUriScheme = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::Uri) {
    m_remoteUri.assign(reinterpret_cast<const char*>(val->value()), val->value_size());
    m_hasRemoteUri = true;
    ++val;
  }
  else {
    m_hasRemoteUri = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::LocalUri) {
    m_localUri.assign(reinterpret_cast<const char*>(val->value()), val->value_size());
    m_hasLocalUri = true;
    ++val;
  }
  else {
    m_hasLocalUri = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::FaceScope) {
    m_faceScope = static_cast<FaceScope>(readNonNegativeInteger(*val));
    m_hasFaceScope = true;
    ++val;
  }
  else {
    m_hasFaceScope = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::FacePersistency) {
    m_facePersistency = static_cast<FacePersistency>(readNonNegativeInteger(*val));
    m_hasFacePersistency = true;
    ++val;
  }
  else {
    m_hasFacePersistency = false;
  }

  if (val != m_wire.elements_end() && val->type() == tlv::nfd::LinkType) {
    m_linkType = static_cast<LinkType>(readNonNegativeInteger(*val));
    m_hasLinkType = true;
    ++val;
  }
  else {
    m_hasLinkType = false;
  }

}
Example #9
0
 long operator()() const
 {
   if (data_ == 0) BOOST_THROW_EXCEPTION(E(6));
   return data_;
 }
vector<EncodedAttributeInfo*> LoadSavedDataSources::loadCodedAttributesFromMultipleFiles( string dsName,int rowCount,bool limit )
{
	vector<EncodedAttributeInfo*> codedAtts;
	try
	{
		for (int j = 0 ; j < this->saved_file_names.size() ; j++)
		{
			this->_fileName = ConfigurationReader::ReadConfiguration(ConfigurationReader::configutation::SAVE_DATA_FOLDER) + this->_saved_folder + "\\" + this->saved_file_names[j];
			TiXmlDocument *doc_1 = new TiXmlDocument(this->_fileName.c_str());
			doc_1->LoadFile();
			TiXmlHandle handler(doc_1);
			TiXmlElement *dsElement = handler.FirstChild("DataSources").ToElement();
			dsElement = dsElement->FirstChildElement("DataSource");
			if (strcmp(dsElement->Attribute("Name"),dsName.c_str()) == 0)
			{
				dsElement = dsElement->FirstChildElement("CodedAttribute");
				int attID = dsElement->FirstAttribute()->IntValue();
				int attType = atoi(dsElement->Attribute("Type"));
				string attName = dsElement->Attribute("Name");
				int noVStreams = dsElement->LastAttribute()->IntValue();
				EncodedAttributeInfo* attr;
				switch(attType){
					case 0:
						{
							EncodedIntAttribute *intAtt = new EncodedIntAttribute();
							intAtt->setAttID(attID);
							intAtt->setAttName(attName);
							intAtt->setNoOfVBitStreams(noVStreams,rowCount);
							intAtt->setAttType(getAttType(attType));

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							intAtt->setVBitStreams(tempVB);
							attr = intAtt;
							codedAtts.push_back(attr);
							break;
						}
					case 1:
						{
							EncodedDoubleAttribute *doubleAtt = new EncodedDoubleAttribute();
							doubleAtt->setAttID(attID);
							doubleAtt->setAttName(attName);
							doubleAtt->setNoOfVBitStreams(noVStreams,rowCount);
							doubleAtt->setAttType(getAttType(attType));

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							doubleAtt->setVBitStreams(tempVB);
							attr = doubleAtt;
							codedAtts.push_back(attr);
							break;
						}
					case 3:
						{
							EncodedMultiCatAttribute *catAtt = new EncodedMultiCatAttribute();
							catAtt->setAttID(attID);
							catAtt->setAttName(attName);
							catAtt->setAttType(getAttType(attType));
							catAtt->setNoOfVBitStreams(noVStreams,rowCount);

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							catAtt->setVBitStreams(tempVB);
							attr = catAtt;
							codedAtts.push_back(attr);
							break;
						}
				}
			}
			delete doc_1;
		}
	}
	catch(...)
	{
		error_loading_encoded_data ex;
		string err = ExceptionReader::GetError(SM1017);
		err += "-> Try to load from a multiple attribute data files";
		ex << error_message(err);
		ex << error_code(SM1017);
		BOOST_THROW_EXCEPTION(ex);
	}
	return codedAtts;
}
Example #11
0
 inline void SqlTranslator::Visit(const VirtualExpression& expression) {
   BOOST_THROW_EXCEPTION(ExpressionTranslationException(
     "Invalid expression."));
 }
DataSources* LoadSavedDataSources::loadSavedEncodedDataFromMultipleFiles( bool limit /*= false*/ )
{
	DataSources *dss = new DataSources();
	string metaDataFile = ConfigurationReader::ReadConfiguration(ConfigurationReader::configutation::SAVE_DATA_FOLDER) + this->_saved_folder + "\\" + this->_metaFile + ".xml";
	if (chdir(ConfigurationReader::ReadConfiguration(ConfigurationReader::configutation::SAVE_DATA_FOLDER).c_str()) == -1)
	{
		error_folder_not_exist ex;
		string err = ExceptionReader::GetError(SM1015);
		err += "-> Saved data folder provided in config file is missing";
		ex << error_message(err);
		ex << error_code(SM1015);
		BOOST_THROW_EXCEPTION(ex);
	}
	
	//string metaDataFile = ConfigurationReader::ReadConfiguration(ConfigurationReader::configutation::SAVE_DATA_FOLDER) + this->_saved_folder + "/" + this->_metaFile + ".xml";
	//string encodedDataFile = "../Reports/" + this->_fileName + ".xml";
	//this->_fileName=encodedDataFile;
	//string metaDataFile = "..\\Reports\\" + this->_metaFile + ".xml";
	try
	{
		TiXmlDocument doc(metaDataFile.c_str());
		bool loaded = doc.LoadFile();
		TiXmlHandle handler( &doc );
		if (loaded)
		{
			TiXmlElement *root = handler.FirstChild("DataSources").ToElement();
			int dataSources = root->FirstAttribute()->IntValue();
			for (int i = 0 ; i < dataSources ; i++)
			{
				TiXmlElement *dsElement = root->FirstChildElement("DataSource");
				string dsName = dsElement->FirstAttribute()->Value();
				dsElement = dsElement->FirstChildElement("noOfAttributes");
				int noAtts = atoi(dsElement->GetText());

				//position where attributes from multiple attribute files are loaded.
				dsElement = dsElement->NextSiblingElement("AttributeFiles");
				TiXmlElement* saved_file_att_element = dsElement->FirstChildElement("att_file");
				this->saved_file_names.resize(noAtts);
				int count_att = 0;
				while (saved_file_att_element)
				{
					this->saved_file_names[count_att++] = saved_file_att_element->GetText();
					saved_file_att_element = saved_file_att_element->NextSiblingElement("att_file");
				}

				dsElement = dsElement->NextSiblingElement("noOfRows");
				int noRows = atoi(dsElement->GetText());
				//Following two lines will load the existance bitmap from the saved file.
				//For older versions of saved data files, this won't be working.
				//So for old data file loading, just comment the following two lines.
				//And also make sure to comment the place where the existance_map is added to wrapdatasource object.
				//string existanceMap = dsElement->NextSiblingElement("existanceBitMap")->GetText();
				//dynamic_bitset<> existance_map(existanceMap);

				vector<EncodedAttributeInfo*> codedAtts = loadCodedAttributesFromMultipleFiles(dsName,noRows,limit);
				if (limit)
				{
					if (this->_rowLimit > noRows)
					{
						this->_rowLimit = noRows;
					}
					noRows = this->_rowLimit;
				}

				dsElement = dsElement->NextSiblingElement("DataSourceType");
				WrapDataSource::DATASOURCE sourceType = getDataSourceType(atoi(dsElement->GetText()));
				WrapDataSource *ds = new WrapDataSource();
				ds->setDSName(dsName);
				ds->noOfAttributes(noAtts);
				ds->noOfRows(noRows);
				ds->setSourceType(sourceType);
				//comment this for loading old saved files. 
				//ds->ExistanceDatabitMap(existance_map);
				dsElement = dsElement->NextSiblingElement("CodedAttributes");
				TiXmlElement *attElement = dsElement->FirstChildElement("Attribute");
				int counter = 0;
				while (attElement && (counter <= noAtts))
				{
					int attType = attElement->LastAttribute()->IntValue();
					int attID = attElement->FirstAttribute()->IntValue();
					switch(attType)
					{
					case 0:
						{
							EncodedIntAttribute* intAtt = static_cast<EncodedIntAttribute*>(codedAtts[counter]);
							TiXmlElement *attEl = attElement->FirstChildElement("maxval");
							intAtt->setMaxVal(atol(attEl->GetText()));
							attEl = attElement->FirstChildElement("minval");
							intAtt->setMinVal(atol(attEl->GetText()));
							attEl = attElement->FirstChildElement("SignBitSet");
							//attEl = attElement->FirstChildElement("SignMapVal");
							// 						vector<bool> signMap;
							// 						if (atol(attEl->GetText()) == 0)
							// 						{						
							// 							signMap.resize(noRows);
							// 						}
							// 						//Set sign Bit Map for negative vals.
							// 						else
							// 						{
							// 							signMap.resize(noRows);
							// 						}
							// 						intAtt->setSignBitMap(signMap);

							dynamic_bitset<> signSet((string)attEl->GetText());
							intAtt->setSignBitSet(signSet);
							EncodedAttributeInfo* atts = intAtt;
							codedAtts[counter] = atts;
							break;
						}
					case 1:
						{
							EncodedDoubleAttribute* doubleAtt = static_cast<EncodedDoubleAttribute*>(codedAtts[counter]);
							TiXmlElement *attEl = attElement->FirstChildElement("maxval");
							doubleAtt->setMaxVal(atol(attEl->GetText()));
							attEl = attElement->FirstChildElement("minval");
							doubleAtt->setMinVal(atol(attEl->GetText()));
							attEl = attElement->FirstChildElement("SignBitSet");
							//attEl = attElement->FirstChildElement("SignMapVal");
							// 						vector<bool> signMap;
							// 						if (atol(attEl->GetText()) == 0)
							// 						{						
							// 							signMap.resize(noRows);
							// 						}
							// 						//Set sign Bit Map for negative vals.
							// 						else
							// 						{
							// 							signMap.resize(noRows);
							// 						}
							// 						doubleAtt->SignBitMap(signMap);

							dynamic_bitset<> signSet((string)attEl->GetText());
							doubleAtt->setSignBitSet(signSet);
							attEl = attElement->FirstChildElement("PrecisionVal");
							doubleAtt->Precision(atol(attEl->GetText()));
							EncodedAttributeInfo* atts = doubleAtt;
							codedAtts[counter] = atts;
							break;
						}
					case 3:
						{
							EncodedMultiCatAttribute* catAtt = static_cast<EncodedMultiCatAttribute*>(codedAtts[counter]);
							TiXmlElement *uniqueElement = attElement->FirstChildElement("UniqueValues");
							int noUniques = uniqueElement->LastAttribute()->IntValue();
							vector<string> uniqueVals;
							uniqueVals.resize(noUniques);
							uniqueElement = uniqueElement->FirstChildElement("Val");
							for (int k = 0 ; k < noUniques ; k++)
							{
								string val = uniqueElement->GetText();
								uniqueVals[k] = val;
								uniqueElement = uniqueElement->NextSiblingElement("Val");
							}
							catAtt->setUniqueValList(uniqueVals);
							EncodedAttributeInfo *atts = catAtt;
							codedAtts[counter] = atts;
							break;
						}
					}
					attElement = attElement->NextSiblingElement("Attribute");
					counter++;
				}
				ds->CodedAtts(codedAtts);
				dss->insertDataSources(ds);
			}
		}		
	}
	catch(...)
	{
		error_loading_encoded_data ex;
		string err = ExceptionReader::GetError(SM1017);
		err += "-> Try to load from a single attribute data file";
		ex << error_message(err);
		ex << error_code(SM1017);
		BOOST_THROW_EXCEPTION(ex);
	}
	
	return dss;
}
vector<EncodedAttributeInfo*> LoadSavedDataSources::loadCodedAttributes(string dsName,int rowCount,bool limit){
	TiXmlDocument doc_1(this->_fileName.c_str());
	doc_1.LoadFile();
	TiXmlHandle handler(&doc_1);
	TiXmlElement *dsElement = handler.FirstChild("DataSources").ToElement();
	dsElement = dsElement->FirstChildElement("DataSource");
	vector<EncodedAttributeInfo*> codedAtts;
	try
	{
		while (dsElement)
		{
			if (strcmp(dsElement->Attribute("Name"),dsName.c_str()) == 0)
			{
				dsElement = dsElement->FirstChildElement("CodedAttributes")->FirstChildElement("Attribute");
				while (dsElement)
				{
					int attID = dsElement->FirstAttribute()->IntValue();
					int attType = atoi(dsElement->Attribute("Type"));
					string attName = dsElement->Attribute("Name");
					int noVStreams = dsElement->LastAttribute()->IntValue();
					EncodedAttributeInfo* attr;
					switch(attType){
					case 0:
						{
							EncodedIntAttribute *intAtt = new EncodedIntAttribute();
							intAtt->setAttID(attID);
							intAtt->setAttName(attName);
							intAtt->setNoOfVBitStreams(noVStreams,rowCount);
							intAtt->setAttType(getAttType(attType));

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							intAtt->setVBitStreams(tempVB);
							attr = intAtt;
							codedAtts.push_back(attr);
							break;
						}
					case 1:
						{
							EncodedDoubleAttribute *doubleAtt = new EncodedDoubleAttribute();
							doubleAtt->setAttID(attID);
							doubleAtt->setAttName(attName);
							doubleAtt->setNoOfVBitStreams(noVStreams,rowCount);
							doubleAtt->setAttType(getAttType(attType));

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							doubleAtt->setVBitStreams(tempVB);
							attr = doubleAtt;
							codedAtts.push_back(attr);
							break;
						}
					case 3:
						{
							EncodedMultiCatAttribute *catAtt = new EncodedMultiCatAttribute();
							catAtt->setAttID(attID);
							catAtt->setAttName(attName);
							catAtt->setAttType(getAttType(attType));
							catAtt->setNoOfVBitStreams(noVStreams,rowCount);

							BitStreamInfo** bitStreams = new BitStreamInfo*[noVStreams];
							TiXmlElement *vbs = dsElement->FirstChildElement("VBitStreams")->FirstChildElement("vbitstream");
							for (int k = 0 ; k < noVStreams ; k++)
							{
								BitStreamInfo* bitStr = new VBitStream();
								bitStr->setBitCount(rowCount);
								bitStr->setBitStreamAllocAttID(attID);
								bitStr->setBitStreamAllocAttName(attName);
								string bitStream;
								if (limit)
								{
									bitStream = vbs->GetText();
									long offset = rowCount - this->_rowLimit;
									bitStream = bitStream.substr(offset,this->_rowLimit);
								}
								else bitStream = vbs->GetText();
								dynamic_bitset<> temp(bitStream);
								bitStr->convert(temp);
								bitStreams[k] = bitStr;
								vbs = vbs->NextSiblingElement("vbitstream");
							}
							vector<BitStreamInfo*> tempVB(bitStreams , bitStreams + noVStreams);
							catAtt->setVBitStreams(tempVB);
							attr = catAtt;
							codedAtts.push_back(attr);
							break;
						}

					}

					dsElement = dsElement->NextSiblingElement("Attribute");
				}
			}
			else{
				dsElement = dsElement->NextSiblingElement("DataSource");
				continue;
			}
		}
	}
	catch(...)
	{
		error_loading_encoded_data ex;
		ex << error_message(ExceptionReader::GetError(SM1017));
		ex << error_code(SM1017);
		BOOST_THROW_EXCEPTION(ex);
	}
	return codedAtts;
}
Example #14
0
	implementation(const std::string& vertex_source_str, const std::string& fragment_source_str) : program_(0)
	{
		GLint success;
	
		const char* vertex_source = vertex_source_str.c_str();
						
		auto vertex_shader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
					
		GL(glShaderSourceARB(vertex_shader, 1, &vertex_source, NULL));
		GL(glCompileShaderARB(vertex_shader));

		GL(glGetObjectParameterivARB(vertex_shader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
		if (success == GL_FALSE)
		{
			char info[2048];
			GL(glGetInfoLogARB(vertex_shader, sizeof(info), 0, info));
			GL(glDeleteObjectARB(vertex_shader));
			std::stringstream str;
			str << "Failed to compile vertex shader:" << std::endl << info << std::endl;
			BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(str.str()));
		}
			
		const char* fragment_source = fragment_source_str.c_str();
						
		auto fragmemt_shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
					
		GL(glShaderSourceARB(fragmemt_shader, 1, &fragment_source, NULL));
		GL(glCompileShaderARB(fragmemt_shader));

		GL(glGetObjectParameterivARB(fragmemt_shader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
		if (success == GL_FALSE)
		{
			char info[2048];
			GL(glGetInfoLogARB(fragmemt_shader, sizeof(info), 0, info));
			GL(glDeleteObjectARB(fragmemt_shader));
			std::stringstream str;
			str << "Failed to compile fragment shader:" << std::endl << info << std::endl;
			BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(str.str()));
		}
			
		program_ = glCreateProgramObjectARB();
			
		GL(glAttachObjectARB(program_, vertex_shader));
		GL(glAttachObjectARB(program_, fragmemt_shader));

		GL(glLinkProgramARB(program_));
			
		GL(glDeleteObjectARB(vertex_shader));
		GL(glDeleteObjectARB(fragmemt_shader));

		GL(glGetObjectParameterivARB(program_, GL_OBJECT_LINK_STATUS_ARB, &success));
		if (success == GL_FALSE)
		{
			char info[2048];
			GL(glGetInfoLogARB(program_, sizeof(info), 0, info));
			GL(glDeleteObjectARB(program_));
			std::stringstream str;
			str << "Failed to link shader program:" << std::endl << info << std::endl;
			BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(str.str()));
		}
		GL(glUseProgramObjectARB(program_));
	}
Example #15
0
vanilla::object::ptr vanilla::object::to_bool() const
{
    BOOST_THROW_EXCEPTION(error::bad_cast_error()
        << error::first_operand(const_cast<object*>(this)->shared_from_this())
        << error::cast_target_name("bool"));
}
Example #16
0
 long operator()(long i, long j) const
 {
   if (j == 'z') BOOST_THROW_EXCEPTION(E(6));
   return data_ + i + j;
 }
Example #17
0
vanilla::object::ptr vanilla::object::call(context&, ptr*, unsigned)
{
    BOOST_THROW_EXCEPTION(error::value_not_callable_error()
        << error::first_operand(shared_from_this()));
}
Example #18
0
void
RibManager::onNrdCommandPrefixAddNextHopError(const Name& name, const std::string& msg)
{
  BOOST_THROW_EXCEPTION(Error("Error in setting interest filter (" + name.toUri() + "): " + msg));
}
Example #19
0
/**
 * Compute full data (averages,histograms buffer and selection buffer)
 * @param clipSrc	source of the plugin
 * @param time	current time
 * @param renderScale	current renderScale
 */
void OverlayData::computeFullData( OFX::Clip* clipSrc, const OfxTime time, const OfxPointD& renderScale, const bool selectionOnly )
{
	_isComputing = true;
	resetHistogramData();
	resetHistogramSelectionData();
	
	if( ! clipSrc->isConnected() )
	{	
		_isComputing = false;
		return;
	}
	
	//TUTTLE_TCOUT_INFOS;
	//TUTTLE_TCOUT_VAR( "computeHistogramBufferData - fetchImage " << time );
	boost::scoped_ptr<OFX::Image> src( clipSrc->fetchImage(time, clipSrc->getCanonicalRod(time)) );	//scoped pointer of current source clip
	//TUTTLE_TCOUT_INFOS;
	
	//TUTTLE_TCOUT_VAR( clipSrc->getPixelRod(time, renderScale) );
	//TUTTLE_TCOUT_VAR( clipSrc->getCanonicalRod(time, renderScale) );
	
	// Compatibility tests
	if( !src.get() ) // source isn't accessible
	{
		_isComputing = false;
		std::cout << "src is not accessible" << std::endl;
		return;
	}
	
//	TUTTLE_TCOUT_VAR( src->getBounds() );
//	TUTTLE_TCOUT_VAR( src->getRegionOfDefinition() );

	if( src->getRowBytes() == 0 )//if source is wrong
	{
		BOOST_THROW_EXCEPTION( exception::WrongRowBytes() );
	}
	OfxRectI srcPixelRod = clipSrc->getPixelRod( time, renderScale ); //get current RoD
	if( (clipSrc->getPixelDepth() != OFX::eBitDepthFloat) ||
		(!clipSrc->getPixelComponents()) )
	{
		BOOST_THROW_EXCEPTION( exception::Unsupported()	<< exception::user() + "Can't compute histogram data with the actual input clip format." );
        return;
	}
	
//	TUTTLE_TCOUT_INFOS;
//	BOOST_ASSERT( srcPixelRod == src->getBounds() );
	if( srcPixelRod != src->getBounds() )
	{
		// the host does bad things !
		// remove overlay... but do not crash.
		TUTTLE_COUT_WARNING( "Image RoD and image bounds are not the same (rod=" << srcPixelRod << " , bounds:" << src->getBounds() << ")." );
		return;
	}
//	BOOST_ASSERT( srcPixelRod.x1 == src->getBounds().x1 );
//	BOOST_ASSERT( srcPixelRod.y1 == src->getBounds().y1 );
//	BOOST_ASSERT( srcPixelRod.x2 == src->getBounds().x2 );
//	BOOST_ASSERT( srcPixelRod.y2 == src->getBounds().y2 );
	
	// Compute if source is OK
	SView srcView = tuttle::plugin::getView<SView>( src.get(), srcPixelRod );	// get current view from source clip
	
	OfxPointI imgSize;
	imgSize.x = srcView.width();
	imgSize.y = srcView.height();
	
//	TUTTLE_TCOUT_INFOS;
	if( isImageSizeModified( imgSize ) )
	{
		//TUTTLE_TCOUT_INFOS;
		clearAll( imgSize );
	}
	
	//TUTTLE_TCOUT_INFOS;
	//Compute histogram buffer
	this->computeHistogramBufferData( _data, srcView, time);
	
	//TUTTLE_TCOUT_INFOS;
	//Compute selection histogram buffer
	this->computeHistogramBufferData( _selectionData, srcView, time, true );
	
	//TUTTLE_TCOUT_INFOS;
	//Compute averages
	this->computeAverages();
	_isComputing = false;
	
	_currentTime = time;
	//TUTTLE_TCOUT_INFOS;
}
Example #20
0
	std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)
	{ 
		if(output_format_.vcodec == CODEC_ID_NONE)
			return nullptr;

		auto st = av_new_stream(oc_.get(), 0);
		if (!st) 		
			BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));		

		auto encoder = avcodec_find_encoder(output_format_.vcodec);
		if (!encoder)
			BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));

		auto c = st->codec;

		avcodec_get_context_defaults3(c, encoder);
				
		c->codec_id			= output_format_.vcodec;
		c->codec_type		= AVMEDIA_TYPE_VIDEO;
		c->width			= output_format_.width;
		c->height			= output_format_.height;
		c->time_base.den	= format_desc_.time_scale;
		c->time_base.num	= format_desc_.duration;
		c->gop_size			= 25;
		c->flags		   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);
		if(c->pix_fmt == PIX_FMT_NONE)
			c->pix_fmt = PIX_FMT_YUV420P;

		if(c->codec_id == CODEC_ID_PRORES)
		{			
			c->bit_rate	= c->width < 1280 ? 63*1000000 : 220*1000000;
			c->pix_fmt	= PIX_FMT_YUV422P10;
		}
		else if(c->codec_id == CODEC_ID_DNXHD)
		{
			if(c->width < 1280 || c->height < 720)
				BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));

			c->bit_rate	= 220*1000000;
			c->pix_fmt	= PIX_FMT_YUV422P;
		}
		else if(c->codec_id == CODEC_ID_DVVIDEO)
		{
			c->width = c->height == 1280 ? 960  : c->width;
			
			if(format_desc_.format == core::video_format::ntsc)
				c->pix_fmt = PIX_FMT_YUV411P;
			else if(format_desc_.format == core::video_format::pal)
				c->pix_fmt = PIX_FMT_YUV420P;
			else // dv50
				c->pix_fmt = PIX_FMT_YUV422P;
			
			if(format_desc_.duration == 1001)			
				c->width = c->height == 1080 ? 1280 : c->width;			
			else
				c->width = c->height == 1080 ? 1440 : c->width;			
		}
		else if(c->codec_id == CODEC_ID_H264)
		{			   
			c->pix_fmt = PIX_FMT_YUV420P;    
			if(options.empty())
			{
				av_opt_set(c->priv_data, "preset", "ultrafast", 0);
				av_opt_set(c->priv_data, "tune",   "fastdecode",   0);
				av_opt_set(c->priv_data, "crf",    "5",     0);
			}
		}
		else if(c->codec_id == CODEC_ID_QTRLE)
		{
			c->pix_fmt = PIX_FMT_ARGB;
		}
				
		c->max_b_frames = 0; // b-frames not supported.
				
		boost::range::remove_erase_if(options, [&](const option& o)
		{
			return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1 ||
				   ffmpeg::av_opt_set(c->priv_data, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;
		});
				
		if(output_format_.format->flags & AVFMT_GLOBALHEADER)
			c->flags |= CODEC_FLAG_GLOBAL_HEADER;
		
		c->thread_count = boost::thread::hardware_concurrency();
		if(avcodec_open(c, encoder) < 0)
		{
			c->thread_count = 1;
			THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");
		}

		return std::shared_ptr<AVStream>(st, [](AVStream* st)
		{
			LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");
			av_freep(&st->codec);
			av_freep(&st);
		});
	}
Example #21
0
void is_valid_bitwise_op(
      const cpp_int_backend<MinBits1, MaxBits1, signed_magnitude, Checked1, Allocator1>& result, const mpl::int_<checked>&)
{
   if(result.sign())
      BOOST_THROW_EXCEPTION(std::range_error("Bitwise operations on negative values results in undefined behavior."));
}
Example #22
0
/**
 * Helper function that will load the OpenCL source program, build and return a handle to that OpenCL kernel
 * @param context - the OpenCL context
 * @param device - the device to compile for
 * @param program - the program that is being built (in/out)
 * @param sourcePath - full path to the source file
 * @param options - build options, e.g. define flags("-D name=value")
 * @return an error code on failure, 0 on success
 */
cl_program CLState::compileOCLProgram(const char* sourcePath,
		const std::string& options) {
	cl_int errNum;

	size_t program_length;
	oclCheckError(sourcePath != NULL, shrTRUE);
	char *source = oclLoadProgSource(sourcePath, "", &program_length);
	if (!source) {
		shrLog("Error: Failed to load compute program %s!\n", sourcePath);
		BOOST_THROW_EXCEPTION(
				runtime_error()
						<< error_message(
								(std::string(
										"Error: Failed to load cl program source from ")
										+ sourcePath).c_str()));
	}

	// create the simple increment OpenCL program
	cl_program program = clCreateProgramWithSource(context, 1,
			(const char **) &source, &program_length, &errNum);
	if (errNum != CL_SUCCESS) {
		shrLog("Error: Failed to create program\n");
		BOOST_THROW_EXCEPTION(runtime_error() << cl_error_code(errNum));
	} else {
		shrLog("clCreateProgramWithSource <%s> succeeded, program_length=%d\n",
				sourcePath, program_length);
	}
	free(source);

	// build the program
	cl_build_status build_status = CL_SUCCESS;

	errNum =
			clBuildProgram(program, 0, NULL,
					std::string(
							"-cl-fast-relaxed-math -cl-nv-verbose" + options).c_str(),
					NULL, NULL);
	if (errNum != CL_SUCCESS) {
		// write out standard error, Build Log and PTX, then return error
		shrLogEx(LOGBOTH | ERRORMSG, errNum, STDERROR);
		oclLogBuildInfo(program, oclGetFirstDev(context));
		oclLogPtx(program, oclGetFirstDev(context), "build_error.ptx");
		BOOST_THROW_EXCEPTION(runtime_error() << cl_error_code(errNum));
	} else {
		shrLog("clBuildProgram <%s> succeeded\n", sourcePath);
		if (this->execDevices != NULL) {
			for (uint iDevice = 0;
					iDevice < this->execDeviceCount
							&& build_status == CL_SUCCESS
							&& errNum == CL_SUCCESS; iDevice++) {
				cl_device_id device = this->execDevices[iDevice];
				errNum = clGetProgramBuildInfo(program, device,
				CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &build_status,
				NULL);
				shrLog("clGetProgramBuildInfo returned: ");
				if (build_status == CL_SUCCESS) {
					shrLog("CL_SUCCESS\n");
				} else {
					shrLog("CLErrorNumber = %d\n", errNum);
				}
				// print out the build log, note in the case where there is nothing shown, some OpenCL PTX->SASS caching has happened
				{
					char *build_log;
					size_t ret_val_size;

					errNum = clGetProgramBuildInfo(program, device,
					CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size);

					if (errNum != CL_SUCCESS) {
						shrLog(
								"clGetProgramBuildInfo device %d, failed to get the log size at line %d\n",
								device, __LINE__);
					}
					build_log = (char *) malloc(ret_val_size + 1);

					errNum = clGetProgramBuildInfo(program, device,
					CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL);

					if (errNum != CL_SUCCESS) {
						shrLog(
								"clGetProgramBuildInfo device %d, failed to get the build log at line %d\n",
								device, __LINE__);
					}
					// to be carefully, terminate with \0
					// there's no information in the reference whether the string is 0 terminated or not
					build_log[ret_val_size] = '\0';
					shrLog("%s\n", build_log);
				}
			}
		}
	}
	this->programs.push_back(program);
	return program;
}
Example #23
0
void tables_creator::visit(const sequence_field_instruction *inst, void *) {
  const template_instruction *ref_instruction =
      dynamic_cast<const template_instruction *>(inst->ref_instruction());

  const template_instruction *element_instruction =
      dynamic_cast<const template_instruction *>(inst->element_instruction());

  bool is_ordered = masks_.is_ordered(inst);

  if (ref_instruction == nullptr && element_instruction == nullptr) {
    traverse_subinstructions(inst);
    if (is_ordered) {
      create_current_ << "  ordering INT,\n";
      num_columns_++;
    }
    return;
  }

  if (this->primary_key_name_.empty())
    BOOST_THROW_EXCEPTION(
        std::runtime_error("Current implementation only allows "
                           "primary key field appears before any "
                           "sequence field in a template."));

  if (element_instruction) {
    tables_creator nested_builder(insert_statements_, masks_, true);
    nested_builder.visit(element_instruction, nullptr);
    create_prefix_ << nested_builder.create_statements();

    if (strcmp(nested_builder.primary_key_name(), "rowid") == 0)
      create_prefix_ << "CREATE UNIQUE INDEX " << nested_builder.table_name()
                     << "_index "
                     << "ON " << nested_builder.table_name() << "("
                     << nested_builder.parameter_list() << ");\n\n";

    if (ref_instruction) {
      create_postfix_ << "CREATE TABLE " << inst->name() << "(\n";

      add_foreign_key(create_postfix_, this->table_name(),
                      this->primary_key_name(), this->primary_key_type());
      add_foreign_key(create_postfix_, nested_builder.table_name(),
                      nested_builder.primary_key_name(),
                      nested_builder.primary_key_type());
      if (is_ordered) {
        create_postfix_ << "ordering INT,\n";
      }
      create_postfix_.seekp(-2, std::ios_base::cur);
      create_postfix_ << ");\n\n";

      if (insert_statements_.count(ref_instruction->id())) {
        std::stringstream err_msg;
        err_msg << "Conflicted sequence id= " << ref_instruction->id()
                << " for " << inst->name();
        BOOST_THROW_EXCEPTION(std::runtime_error(err_msg.str()));
      }
      insert_statements &stmts = insert_statements_[ref_instruction->id()];
      stmts.insert_item_stmt =
          construct_insert_statement(inst->name(), 2 + is_ordered);
      stmts.primary_key_index = this->primary_key_index_;
    } else {
      add_foreign_key(create_current_, nested_builder.table_name(),
                      nested_builder.primary_key_name(),
                      nested_builder.primary_key_type());
      num_columns_++;

      if (is_ordered) {
        create_current_ << "  ordering INT,\n";
        num_columns_++;
      }
    }
  } else {

    tables_creator nested_builder(insert_statements_, masks_,
                                  this->table_name(), this->primary_key_name(),
                                  this->primary_key_type());
    nested_builder.visit(ref_instruction, nullptr);
    create_postfix_ << nested_builder.create_statements();
  }
}
Example #24
0
 utree eval (utree const& subject) const { 
   if (!predicate(subject))
     BOOST_THROW_EXCEPTION(assertion_failed());
   return utree();
 } 
Example #25
0
void
Interest::decode03()
{
  // Interest ::= INTEREST-TYPE TLV-LENGTH
  //                Name
  //                CanBePrefix?
  //                MustBeFresh?
  //                ForwardingHint?
  //                Nonce?
  //                InterestLifetime?
  //                HopLimit?
  //                Parameters?

  bool hasName = false;
  m_selectors = Selectors().setMaxSuffixComponents(1); // CanBePrefix=0
  m_nonce.reset();
  m_interestLifetime = DEFAULT_INTEREST_LIFETIME;
  m_forwardingHint = DelegationList();

  int lastEle = 0; // last recognized element index, in spec order
  for (const Block& ele : m_wire.elements()) {
    switch (ele.type()) {
      case tlv::Name: {
        if (lastEle >= 1) {
          BOOST_THROW_EXCEPTION(Error("Name element is out of order"));
        }
        hasName = true;
        m_name.wireDecode(ele);
        if (m_name.empty()) {
          BOOST_THROW_EXCEPTION(Error("Name has zero name components"));
        }
        lastEle = 1;
        break;
      }
      case tlv::CanBePrefix: {
        if (lastEle >= 2) {
          BOOST_THROW_EXCEPTION(Error("CanBePrefix element is out of order"));
        }
        if (ele.value_size() != 0) {
          BOOST_THROW_EXCEPTION(Error("CanBePrefix element has non-zero TLV-LENGTH"));
        }
        m_selectors.setMaxSuffixComponents(-1);
        lastEle = 2;
        break;
      }
      case tlv::MustBeFresh: {
        if (lastEle >= 3) {
          BOOST_THROW_EXCEPTION(Error("MustBeFresh element is out of order"));
        }
        if (ele.value_size() != 0) {
          BOOST_THROW_EXCEPTION(Error("MustBeFresh element has non-zero TLV-LENGTH"));
        }
        m_selectors.setMustBeFresh(true);
        lastEle = 3;
        break;
      }
      case tlv::ForwardingHint: {
        if (lastEle >= 4) {
          BOOST_THROW_EXCEPTION(Error("ForwardingHint element is out of order"));
        }
        m_forwardingHint.wireDecode(ele);
        lastEle = 4;
        break;
      }
      case tlv::Nonce: {
        if (lastEle >= 5) {
          BOOST_THROW_EXCEPTION(Error("Nonce element is out of order"));
        }
        uint32_t nonce = 0;
        if (ele.value_size() != sizeof(nonce)) {
          BOOST_THROW_EXCEPTION(Error("Nonce element is malformed"));
        }
        std::memcpy(&nonce, ele.value(), sizeof(nonce));
        m_nonce = nonce;
        lastEle = 5;
        break;
      }
      case tlv::InterestLifetime: {
        if (lastEle >= 6) {
          BOOST_THROW_EXCEPTION(Error("InterestLifetime element is out of order"));
        }
        m_interestLifetime = time::milliseconds(readNonNegativeInteger(ele));
        lastEle = 6;
        break;
      }
      case tlv::HopLimit: {
        if (lastEle >= 7) {
          break; // HopLimit is non-critical, ignore out-of-order appearance
        }
        if (ele.value_size() != 1) {
          BOOST_THROW_EXCEPTION(Error("HopLimit element is malformed"));
        }
        // TLV-VALUE is ignored
        lastEle = 7;
        break;
      }
      case tlv::Parameters: {
        if (lastEle >= 8) {
          BOOST_THROW_EXCEPTION(Error("Parameters element is out of order"));
        }
        // TLV-VALUE is ignored
        lastEle = 8;
        break;
      }
      default: {
        if (tlv::isCriticalType(ele.type())) {
          BOOST_THROW_EXCEPTION(Error("unrecognized element of critical type " +
                                      to_string(ele.type())));
        }
        break;
      }
    }
  }

  if (!hasName) {
    BOOST_THROW_EXCEPTION(Error("Name element is missing"));
  }
}
Example #26
0
void check_is_configured()
{
	if(pt.empty())
		BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Enviroment properties has not been configured"));
}
Example #27
0
		virtual void on_post(http_server_context& /*context*/, const std::smatch& /*match*/)
		{
			BOOST_THROW_EXCEPTION(http_exception(http_status_code::method_not_allowed));
		}
Example #28
0
void vanilla::object::sset(object::ptr const&, ptr)
{
    BOOST_THROW_EXCEPTION(error::unsupported_operation_error()
        << error::first_operand(shared_from_this())
        << error::operation_name("subscript assign"));
}
Example #29
0
void hyp2F1(T& result, const T& a, const T& b, const T& c, const T& x)
{
  // Compute the series representation of hyperg_2f1 taken from
  // Abramowitz and Stegun 15.1.1.
  // There are no checks on input range or parameter boundaries.

   typedef typename boost::multiprecision::detail::canonical<boost::int32_t, T>::type si_type;
   typedef typename boost::multiprecision::detail::canonical<boost::uint32_t, T>::type ui_type;
   typedef typename T::exponent_type exp_type;
   typedef typename boost::multiprecision::detail::canonical<exp_type, T>::type canonical_exp_type;
   typedef typename mpl::front<typename T::float_types>::type fp_type;

   T x_pow_n_div_n_fact(x);
   T pochham_a         (a);
   T pochham_b         (b);
   T pochham_c         (c);
   T ap                (a);
   T bp                (b);
   T cp                (c);

   eval_multiply(result, pochham_a, pochham_b);
   eval_divide(result, pochham_c);
   eval_multiply(result, x_pow_n_div_n_fact);
   eval_add(result, ui_type(1));

   T lim;
   eval_ldexp(lim, result, 1 - boost::multiprecision::detail::digits2<number<T, et_on> >::value);

   if(eval_get_sign(lim) < 0)
      lim.negate();

   ui_type n;
   T term;

   static const unsigned series_limit = 
      boost::multiprecision::detail::digits2<number<T, et_on> >::value < 100
      ? 100 : boost::multiprecision::detail::digits2<number<T, et_on> >::value;
   // Series expansion of hyperg_2f1(a, b; c; x).
   for(n = 2; n < series_limit; ++n)
   {
      eval_multiply(x_pow_n_div_n_fact, x);
      eval_divide(x_pow_n_div_n_fact, n);

      eval_increment(ap);
      eval_multiply(pochham_a, ap);
      eval_increment(bp);
      eval_multiply(pochham_b, bp);
      eval_increment(cp);
      eval_multiply(pochham_c, cp);

      eval_multiply(term, pochham_a, pochham_b);
      eval_divide(term, pochham_c);
      eval_multiply(term, x_pow_n_div_n_fact);
      eval_add(result, term);

      if(eval_get_sign(term) < 0)
         term.negate();
      if(lim.compare(term) >= 0)
         break;
   }
   if(n > series_limit)
      BOOST_THROW_EXCEPTION(std::runtime_error("H2F1 failed to converge."));
}
Example #30
0
inline void conversion_overflow(const mpl::int_<checked>&)
{
   BOOST_THROW_EXCEPTION(std::overflow_error("Overflow in conversion to narrower type"));
}