int main(int argc, char *argv[])
{
    //for random number generator
    srand((unsigned)time(NULL));

    //preprocessing
    if(argc != 5){
        std::cout<<"No enough arugments\n";
        exit(0);
    }
    int k, n_threads;
    double lambda, wall_timer;
    std::string data_dir, meta_dir, train_dir, test_dir;
    std::string line;
    int row, col, train_size, test_size;

    std::cout<<"----------------------------------------------"<<std::endl;
    std::cout<<"exec filename: "<<argv[0]<<std::endl;
    wall_timer = omp_get_wtime();
    k = atoi(argv[1]);
    lambda = atof(argv[2]);
    n_threads = atoi(argv[3]);
    data_dir = argv[4];

    //set number of threads
    omp_set_num_threads(n_threads); 
   
    std::vector<std::string> files(3,"");
    files.reserve(3);
    getdir(data_dir, files);

    meta_dir = data_dir+files[0];
    train_dir = data_dir+files[1];
    test_dir = data_dir+files[2];
 

    //std::cout<<"Using [rank, lambda, n_threads, directory]->>: "<<"[ "<<k<<", "<<lambda<<", "<<n_threads<<", "<<data_dir<<"* ]\n";
    //std::cout<<meta_dir<<" "<<train_dir<<" "<<test_dir<<" "<<"\n";

    //read meta file
    std::ifstream meta_file(meta_dir.c_str());
        //get rows and clos
    std::getline(meta_file, line);
    std::stringstream meta_ss(line);
    meta_ss >> row >> col;
        //get size of train
    std::getline(meta_file, line);
    std::stringstream train_ss(line);
    train_ss >> train_size;
        //get size of test
    std::getline(meta_file, line);
    std::stringstream test_ss(line);
    test_ss >> test_size;
    //std::cout<<"row: "<<row<<" col: "<<col<<" train size: "<<train_size<<" test size: "<<test_size<<"\n";


    //read from training file, and construct matrix
    int *Ix = new int[train_size];
    int *Jx = new int[train_size];
    double *xx = new double[train_size];

    int *Iy = new int[train_size];
    int *Jy = new int[train_size];
    double *yy = new double[train_size];

    int *cc = new int[col](); //number of non zeros in each column
    int *rc = new int[row]();


    std::ifstream train_file(train_dir.c_str());
    std::vector<T> train_list;
    train_list.reserve(train_size);

    for(int i=0;i<train_size;i++){
	train_file >> Ix[i];
	train_file >> Jx[i];
	train_file >> xx[i];
        Ix[i] = Ix[i] - offset;
        Jx[i] = Jx[i] - offset;
        train_list.push_back(T(Ix[i], Jx[i], xx[i]));
        cc[Jx[i]] = cc[Jx[i]] + 1;
        rc[Ix[i]]= rc[Ix[i]] + 1;
    }
    Eigen::SparseMatrix<double> R(row, col);
    R.setFromTriplets(train_list.begin(), train_list.end());



    Eigen::SparseMatrix<double> R_tsp = R.transpose();
    int i_count = 0;
    for(int i=0;i<R_tsp.outerSize(); i++){
        for(Eigen::SparseMatrix<double>::InnerIterator it(R_tsp, i); it; ++it){
            Iy[i_count] = it.row();
            Jy[i_count] = it.col();
            yy[i_count] = it.value();
            i_count++;
        }
    }
    
    //std::cout<<"cc(1)=2->>: "<<cc[1]<<" cc(14)=1->>: "<<cc[14]<<" cc(32)=8->>: "<<cc[32]<<"\n";
    //std::cout<<"xx(0)=4->>: "<<xx[0]<<" xx(7)=5->>: "<<xx[7]<<" xx(38)=3->>: "<<xx[7]<<"\n";
    //std::cout<<"rc(4)=23->>: "<<rc[4]<<" rc(6)=1->>: "<<rc[6]<<" rc[12]=148->>: "<<rc[12]<<"\n";
    //std::cout<<"yy(2)=5->>: "<<yy[2]<<" yy(8)=4->>: "<<yy[8]<<" yy(19)=3->>: "<<yy[19]<<"\n";

    //read from testing file, and construct matrix
    
    int *Ixt = new int[test_size];
    int *Jxt = new int[test_size];
    double *xxt = new double[test_size];

    std::ifstream test_file(test_dir.c_str());
    std::vector<T> test_list;
    test_list.reserve(test_size);

    for(int i=0;i<test_size;i++){
    	test_file >> Ixt[i];
        test_file >> Jxt[i];
        test_file >> xxt[i];
        Ixt[i] = Ixt[i] - offset;
        Jxt[i] = Jxt[i] - offset;
        test_list.push_back(T(Ixt[i], Jxt[i], xx[i]));
    }
    Eigen::SparseMatrix<double> Rt(row, col);
    Rt.setFromTriplets(test_list.begin(), test_list.end());

    int maxiter = 10;

    Eigen::MatrixXd U(k, row);
    Eigen::MatrixXd M(k, col);

    //generate random numbers within 0 and 1 for U, and M
    #pragma omp parallel for
    for(int i=0;i<k;i++){
        for(int j=0;j<row;j++){
            U(i,j) = (double) rand() / (double) RAND_MAX;
        }
        for(int j=0;j<col;j++){
            M(i,j) = (double) rand() / (double) RAND_MAX;
        }
    }
    //preprocessing for parallelization
    int *cci = new int[col];
    int *rci = new int[row];
    int pre_count;

    pre_count = 0;
    for(int i=0;i<col;i++){
        cci[i] = pre_count;
        pre_count = cci[i] + cc[i];
    }

    pre_count = 0;
    for(int i=0;i<row;i++){
       rci[i] = pre_count;
       pre_count = rci[i] + rc[i];
    }


    std::cout<<"walltime spent on preprocessing data: "<<omp_get_wtime() - wall_timer<<"\n";

    //std::cout<<"R_tsp: "<<R_tsp.size()<<" R_tsp(4999, 1825) = 3, the output is: "<<R_tsp.coeffRef(4999,1825)<<"\n";

    //for small
    //std::cout<<"R size: "<<R.size()<<" R(1825, 4999) = 3, the output is: "<<R.coeffRef(1825,4999)<<"\n";
    //std::cout<<"Rt size: "<<Rt.size()<<" Rt(1395, 4999) = 3, the output is: "<<Rt.coeffRef(1395,4999)<<"\n";

    //for medium
    //std::cout<<"R size: "<<R.size()<<" R(4750, 3951) is 4, the output is:  "<<R.coeffRef(4750,3951)<<"\n";
    //std::cout<<"Rt size: "<<Rt.size()<<" R(2128, 3951) is 3, the output is: "<<Rt.coeffRef(2128,3951)<<"\n";

//------------------------------begin processing----------------------------------------------//
    double accu_sum=0;
    double rmse_test=0;
    double rmse_train=0;
    Eigen::MatrixXd U_tps = U.transpose();
    #pragma omp parallel for reduction(+:accu_sum) 
    for(int i=0;i<train_size;i++){
        accu_sum += pow(U_tps.row(Ix[i])*M.col(Jx[i]) - xx[i], 2);
    }
    rmse_train = sqrt(accu_sum/train_size);

    accu_sum = 0;
    #pragma omp parallel for reduction(+:accu_sum)
    for(int i=0;i<test_size;i++){
        accu_sum += pow(U_tps.row(Ixt[i])*M.col(Jxt[i]) - xxt[i], 2);
    }
    rmse_test = sqrt(accu_sum/test_size);

    Eigen::MatrixXd iden = Eigen::MatrixXd::Identity(k,k);

    std::cout<<"start with rmse on train: "<< rmse_train <<" rmse on test: "<< rmse_test << " n_threads: "<<n_threads<<std::endl;
    double total_timer, end_timer;
    for(int t=0;t<maxiter;t++){
	printf("iter: %d\n",t+1);

	printf("Minimize M while fixing U ...");
        wall_timer = omp_get_wtime();
        //minimize M while fixing U
	#pragma omp parallel for schedule(dynamic, 1)
        for(int i=0;i<col;i++){
            if( cc[i]>0 ){
                //construct subU, and subR
                Eigen::MatrixXd subU(k, cc[i]);
                Eigen::VectorXd subR(cc[i]);
		int j=cci[i];
                for(int l=0; l<cc[i];l++){
                    subU.col(l) = U.col(Ix[j+l]);
		    subR[l] = xx[j+l];
                }
                M.col(i) = (lambda*iden+subU*subU.transpose()).llt().solve((subU*subR));
            }else{
                M.col(i) = Eigen::VectorXd::Zero(k);
            }
        
        }
        end_timer = omp_get_wtime();
	total_timer += end_timer-wall_timer;	
        printf("%0.2f seconds\n", end_timer - wall_timer);

	printf("Minimize U whilt fixing M ...");
	wall_timer = omp_get_wtime();
        //minimize U while fixing M
        #pragma omp parallel for schedule(dynamic, 1)
        for(int i=0;i<row;i++){
            if( rc[i] > 0){
                //construct subM, and subR
                Eigen::MatrixXd subM(k, rc[i]);
                Eigen::VectorXd subR(rc[i]);
		int j=rci[i];
                for(int l=0;l<rc[i];l++){
                    subM.col(l) = M.col(Iy[j+l]);
		    subR[l] = yy[j+l];
                }
                U.col(i) = (lambda*iden+subM*subM.transpose()).llt().solve((subM*subR));
            }else{
                U.col(i) = Eigen::VectorXd::Zero(k);
            }
        }
	end_timer = omp_get_wtime();
	total_timer += end_timer-wall_timer;
	printf("%0.2f seconds\n", end_timer - wall_timer);

	Eigen::MatrixXd U_tps = U.transpose();
    
        accu_sum = 0;
        #pragma omp parallel for reduction(+:accu_sum)
        for(int i=0;i<train_size;i++){
            accu_sum += pow(U_tps.row(Ix[i])*M.col(Jx[i]) - xx[i], 2);
        }
        rmse_train = sqrt(accu_sum/train_size);
        
        accu_sum = 0;
        #pragma omp parallel for reduction(+:accu_sum)
        for(int i=0;i<test_size;i++){
            accu_sum += pow(U_tps.row(Ixt[i])*M.col(Jxt[i]) - xxt[i], 2);
        }
        rmse_test = sqrt(accu_sum/test_size);

        printf("rmse on train: %0.6f, rmse on test: %0.6f\n",rmse_train, rmse_test);
    }
    printf("total running time: %0.2f\n",total_timer);

    //free variables
    delete[] Ix;
    delete[] Jx;
    delete[] xx;
    delete[] Iy;
    delete[] Jy;
    delete[] yy;
    delete[] Ixt;
    delete[] Jxt;
    delete[] xxt;
    delete[] rci;
    delete[] cci;
}
Exemplo n.º 2
0
void
ReadCadmould::openFiles()
{
    retOpenFile = 0;
    // cout << "p_byteswap: "<<p_byteswap->getValue()<<endl;

    /// shut down all old if exist
    delete d_grid;
    for (int i = 0; i < d_numDataSets; i++)
    {
        delete d_data[i];
        d_data[i] = NULL;
    }
    d_numDataSets = 0;

    // the filename parameter
    const char *selFile = p_filename->getValue();

    // make sure we can work with the file name
    char basename[MAXPATHLEN + 1], filename[MAXPATHLEN + 1];

    //// Open mesh file: clip off last char if old style
    strncpy(basename, selFile, MAXPATHLEN);
    basename[MAXPATHLEN] = '\0';

    setCaseType(basename);

    if (d_type != TYPE_CAR)
    {
        basename[strlen(basename) - 1] = '\0';
    }

    d_grid = new CadmouldGrid(basename);
    int gridState = -1;
    int gridNoVert = -1;
    if (d_grid)
        gridState = d_grid->getState();
    if (gridState != 0)
    {
        if (gridState < 0)
            sendError("Could not read %s as Cadmould mesh", basename);

        else
            sendError("Could not read %s as Cadmould mesh: %s", basename, strerror(gridState));
        delete d_grid;
        d_grid = NULL;
    }
    else
    {
        gridNoVert = d_grid->getNumVert();
    }

    // from now on: base is Fuellbild file ( case+Kenner )
    strncpy(basename, selFile, MAXPATHLEN);
    basename[MAXPATHLEN] = '\0';

    if (d_type == TYPE_CAR)
    {
        char car_base[MAXPATHLEN];
        strcpy(car_base, basename);
        *(strstr(car_base, ".cfe")) = '\0';

        CarFiles files(car_base);

        for (int grp_nb = 0; grp_nb < files.numGroups(); grp_nb++)
        {

            MultiCarData *data = new MultiCarData(files, grp_nb, byteswap_);
            if (data)
            {
                if (data->getState() == 0)
                {
                    d_data[d_numDataSets] = data;
                    d_numDataSets++;
                }
                else
                {
                    delete data;
                }
            }
        }
    }

    else if (d_type == TYPE_STD)
    {
        // check, whether we have a E0 file = Rheologie-File
        {
            sprintf(filename, "%sE0", basename);
            static const char *labelsE0[] = {
                "Fliessfront-Temperatur",
                "Fliessfront-Druckbedarf",
                "Fliessfront-Schubspannung",
                "Fliessfront-Geschwindigkeit"
            };
            FuellDruckData *data = new FuellDruckData(filename, 4, labelsE0, byteswap_);
            if (data)
            {
                if (data->getState() == 0)
                {
                    d_data[d_numDataSets] = data;
                    d_numDataSets++;
                }
                else
                    delete data;
            }
        }

        // check, whether we have E## files = Zwischenergebnisse
        {
            sprintf(filename, "%sE", basename);
            static const char *labelsExx[] = {
                "Momentan-Temperatur(t)",
                "Momentan-Druck(t)",
                "Momentan-Schubspannung(t)",
                "Momentan-Geschwindigkeit(t)"
            };
            MultiFuellData *data = new MultiFuellData(filename, 4, labelsExx, byteswap_);
            if (data)
            {
                if (data->getState() == 0)
                {
                    d_data[d_numDataSets] = data;
                    d_numDataSets++;
                }
                else
                    delete data;
            }
        }

        // check, whether we have S## files = Schichtergebnisse
        {
            sprintf(filename, "%sS", basename);
            static const char *labelsSxx[] = { "Randschichtddicke(t)" };
            MultiFuellData *data = new MultiFuellData(filename, 1, labelsSxx, byteswap_);
            if (data)
            {
                if (data->getState() == 0)
                {
                    d_data[d_numDataSets] = data;
                    d_numDataSets++;
                }
                else
                    delete data;
            }
        }

        //////// other data sets here ...

        // filling process, file: basename
        // data: Fuellstand, connect, fill_time
        {
            static const char *labelsFilling[] = { "Fuellstand", "Connect", "fill_time" };
            static const CadmouldData::FieldType fieldType[] = {
                CadmouldData::SCALAR_FLOAT,
                CadmouldData::SCALAR_INT,
                CadmouldData::SCALAR_FLOAT
            };
            FillingData *data = new FillingData(basename, 3, labelsFilling, fieldType, byteswap_);
            fillTimeDataSets = -1;
            fillChoice = 0;

            if (data)
            {
                if (data->getState() == 0)
                {
                    fillTimeDataSets = d_numDataSets;
                    fillField = 0;
                    d_data[d_numDataSets] = data;
                    d_numDataSets++;
                    if (gridNoVert != -1 && data->numVert() != ((gridNoVert + 3) / 4) * 4)
                    {
                        retOpenFile = -1;
                        sendWarning("Number of nodes from mesh and fill-data does not match. Trying with the contrary byte-swapping option");
                    }
                }
                else
                    delete data;
            }
        }

        // check, whether we have .car files
        {
            CarFiles files(basename);
            for (int i = 0; i < files.numFiles(); i++)
            {
                CarData *data = new CarData(files.get(i), byteswap_);
                if (data)
                {
                    if (data->getState() == 0)
                    {
                        d_data[d_numDataSets] = data;
                        d_numDataSets++;
                    }
                    else
                        delete data;
                }
            }
        }
    }

    if (retOpenFile == 0)
    {
        // create the labels for the choices
        int numLabels = 1; // the "---" label
        for (int i = 0; i < d_numDataSets; i++)
            numLabels += d_data[i]->numFields();
        const char **labels = new const char *[numLabels];
        labels[0] = "---";
        int labelNo = 1;

        for (int i = 0; i < d_numDataSets; i++)
        {
            for (int j = 0; j < d_data[i]->numFields(); j++)
            {

                labels[labelNo] = d_data[i]->getName(j);
                if (fillChoice == 0 && strstr(labels[labelNo], "Fuellzeit") != NULL)
                {
                    fillChoice = labelNo;
                }
                else if (fillChoice == 0 && strstr(labels[labelNo], "llzeit"))
                {
                    fillChoice = labelNo;
                }
                // +1 because choices return 1 for 1st label ([0])
                dataLoc[labelNo].datasetNo = i;
                dataLoc[labelNo].fieldNo = j;
                labelNo++;
            }
        }

        // attach to all choices, keep old values if valid
        for (int i = 0; i < NUM_PORTS; i++)
        {
            int oldVal = p_choice[i]->getValue();
            //if (oldVal<d_numDataSets-2)
            if (oldVal < numLabels)
                p_choice[i]->setValue(numLabels, labels, oldVal);
            else
                p_choice[i]->setValue(numLabels, labels, 0);
        }

        labels[0] = "automatic";
        p_fillField->setValue(numLabels, labels, fillChoice);
    }
}
Exemplo n.º 3
0
void ShipType::Init()
{
	static bool isInitted = false;
	if (isInitted) 
		return;
	isInitted = true;

	// load all ship definitions
	namespace fs = FileSystem;
	for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse); !files.Finished(); files.Next()) {
		const fs::FileInfo &info = files.Current();
		if (ends_with_ci(info.GetPath(), ".json")) {
			const std::string id(info.GetName().substr(0, info.GetName().size()-5));
			ShipType st = ShipType(id, info.GetPath());
			types.insert(std::make_pair(st.id, st));

			// assign the names to the various lists
			switch( st.tag ) {
			case TAG_SHIP:				player_ships.push_back(id);				break;
			case TAG_STATIC_SHIP:		static_ships.push_back(id);				break;
			case TAG_MISSILE:			missile_ships.push_back(id);			break;
				break;
			case TAG_NONE:
			default:
				break;
			}
		}
	}

#if ALLOW_LUA_SHIP_DEF
	lua_State *l = luaL_newstate();

	LUA_DEBUG_START(l);

	luaL_requiref(l, "_G", &luaopen_base, 1);
	luaL_requiref(l, LUA_DBLIBNAME, &luaopen_debug, 1);
	luaL_requiref(l, LUA_MATHLIBNAME, &luaopen_math, 1);
	lua_pop(l, 3);

	LuaConstants::Register(l);
	LuaVector::Register(l);
	LUA_DEBUG_CHECK(l, 0);

	// provide shortcut vector constructor: v = vector.new
	lua_getglobal(l, LuaVector::LibName);
	lua_getfield(l, -1, "new");
	assert(lua_iscfunction(l, -1));
	lua_setglobal(l, "v");
	lua_pop(l, 1); // pop the vector library table

	LUA_DEBUG_CHECK(l, 0);

	// register ship definition functions
	lua_register(l, "define_ship", define_ship);
	lua_register(l, "define_static_ship", define_static_ship);
	lua_register(l, "define_missile", define_missile);

	LUA_DEBUG_CHECK(l, 0);

	// load all ship definitions
	namespace fs = FileSystem;
	for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse); !files.Finished(); files.Next()) {
		const fs::FileInfo &info = files.Current();
		if (ends_with_ci(info.GetPath(), ".lua")) {
			const std::string name = info.GetName();
			s_currentShipFile = name.substr(0, name.size() - 4);
			if (ShipType::types.find(s_currentShipFile) == ShipType::types.end())
			{
				pi_lua_dofile(l, info.GetPath());
				s_currentShipFile.clear();
			}
		}
	}

	LUA_DEBUG_END(l, 0);

	lua_close(l);
#endif

	//remove unbuyable ships from player ship list
	ShipType::player_ships.erase(
		std::remove_if(ShipType::player_ships.begin(), ShipType::player_ships.end(), ShipIsUnbuyable),
		ShipType::player_ships.end());

	if (ShipType::player_ships.empty())
		Error("No playable ships have been defined! The game cannot run.");
}
Exemplo n.º 4
0
int main()
{


	if (1)
	{
		//testSequenceSummary();
		//testGene();
		testGenome("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/UnitTestingData");

		/*
		Genome genome;
		genome.readRFPFile("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/rfp/rfp.counts.by.codon.and.gene.GSE63789.wt.csv");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
		{
			geneAssignment[i] = 0u;
		}
		unsigned numMixtures = 1;
		std::vector<double> sphi_init(numMixtures, 2);
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		RFPParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, "allUnique");

		std::vector<std::string> files;
		files.push_back("/Users/roxasoath1/Desktop/TONEWTON/RFPAlphaValues.csv");
		tmp.initMutationSelectionCategories(files, 1, RFPParameter::alp);
		files[0] = "/Users/roxasoath1/Desktop/TONEWTON/RFPLambdaPrimeValues.csv";
		tmp.initMutationSelectionCategories(files, 1, RFPParameter::lmPri);
		std::vector<double> phi = tmp.readPhiValues("/Users/roxasoath1/Desktop/TONEWTON/RFPPsiValues.csv");
		tmp.InitializeSynthesisRate(phi);


		RFPModel model;

		model.setParameter(tmp);

		std::cout <<"init done\n";
		model.simulateGenome(genome);
		std::cout <<"writing file\n";
		genome.writeRFPFile("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/rfp/simulatedRFPData.csv", true);
*/
		exit(1);
	}
	std::string modelToRun = "RFP"; //can also be ROC or FONSE
	bool withPhi = false;
	bool fromRestart = true;
	unsigned numMixtures = 1;


	std::cout << "Initializing MCMCAlgorithm object---------------" << std::endl;
	int samples = 10;
	int thinning = 10;
	int useSamples = 100;
	std::cout << "\t# Samples: " << samples << "\n";
	std::cout << "\tThinning: " << thinning << "\n";
	std::cout << "\t # Samples used: " << useSamples << "\n";
	MCMCAlgorithm mcmc = MCMCAlgorithm(samples, thinning, 10, true, true, true);
	mcmc.setRestartFileSettings("RestartFile.txt", 20, true);
	std::cout << "Done!-------------------------------\n\n\n";




	if (modelToRun == "ROC")
	{
		std::cout << "Initializing Genome object--------------------------" << std::endl;
		Genome genome;
		genome.readFasta("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/twoMixtures/simulatedAllUniqueR.fasta");
		if (withPhi)
		{
			genome.readObservedPhiValues("/Users/roxasoath1/Desktop/RibModelFramework/ribModel/data/simulatedAllUniqueR_phi.csv", false);
		}
		std::cout << "Done!-------------------------------\n\n\n";



		std::cout << "Initializing shared parameter variables---------------\n";
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		std::cout << "Done!------------------------\n\n\n";



		std::cout << "Initializing ROCParameter object--------------------\n" << std::endl;
		ROCParameter parameter;

		if (fromRestart)
		{
			ROCParameter tmp("/Users/roxasoath1/Desktop/RibModelFramework/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			ROCParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				std::cout << "Sphi_init for selection category " << selectionCategry << ": " << sphi_init[selectionCategry] << std::endl;
			}
			std::cout << "\t# mixtures: " << numMixtures << "\n";
			std::cout << "\tmixture definition: " << mixDef << "\n";

			std::vector<std::string> files(2);
			files[0] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_mutation0.csv");
			files[1] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_mutation1.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			files[0] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_selection0.csv");
			files[1] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_selection1.csv");
			tmp.initSelectionCategories(files, tmp.getNumSelectionCategories());

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals = parameter.readPhiValues("/home/clandere/CodonUsageBias/RibosomeModel/RibModelFramework/ribModel/data/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
		}
		std::cout << "Done!--------------------------------\n\n\n" << std::endl;



		std::cout << "Initializing ROCModel object--------------------------\n";

		ROCModel model;
		model.setParameter(parameter);
		std::cout << "Done!----------------------------------\n\n\n" << std::endl;


		std::cout << "Running MCMC.............\n" << std::endl;
		mcmc.run(genome, model, 1, 0);
		std::cout << "Done!----------------------------------\n\n\n" << std::endl;
	} //END OF ROC
	else if (modelToRun == "RFP")
	{
		std::cout << "Initializing Genome object--------------------------" << std::endl;
		Genome genome;
		genome.readRFPFile("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/rfp/rfp.counts.by.codon.and.gene.GSE63789.wt.csv");
		std::cout << "Done!-------------------------------\n\n\n";



		std::cout << "Initializing shared parameter variables---------------\n";
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		std::cout << "Done!------------------------\n\n\n";



		std::cout << "Initializing RFPParameter object--------------------\n" << std::endl;
		RFPParameter parameter;

		if (fromRestart)
		{
			RFPParameter tmp("/Users/roxasoath1/Desktop/RibModelFramework/10_restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = Parameter::allUnique;
			RFPParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++) {
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				std::cout << "Sphi_init for selection category " << selectionCategry << ": " <<
				sphi_init[selectionCategry] << std::endl;
			}
			std::cout << "\t# mixtures: " << numMixtures << "\n";
			std::cout << "\tmixture definition: " << mixDef << "\n";

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			parameter = tmp;
		}
		std::cout << "Done!--------------------------------\n\n\n" << std::endl;



		std::cout << "Initializing RFPModel object--------------------------\n";

		RFPModel model;
		model.setParameter(parameter);
		std::cout << "Done!----------------------------------\n\n\n" << std::endl;


		std::cout << "Running MCMC.............\n" << std::endl;
		mcmc.run(genome, model, 1, 0);
		std::cout << "Done!----------------------------------\n\n\n" << std::endl;

	} //END OF RFP
	else if (modelToRun == "FONSE")
	{
		std::cout << "initialize Genome object--------------------------" << std::endl;
		Genome genome;
		genome.readFasta("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/FONSE/genome_2000.fasta");
		std::cout << "Done!-------------------------------\n\n\n";



		std::cout << "Initializing shared parameter variables---------------\n";
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		std::cout << "Done!------------------------\n\n\n";



		FONSEParameter parameter;
		std::cout << "initialize Parameter object" << std::endl;
		if (fromRestart)
		{
			FONSEParameter tmp("/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			FONSEParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++) {
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				std::cout << "Sphi_init for selection category " << selectionCategry << ": " <<
				sphi_init[selectionCategry] << std::endl;
			}
			std::cout << "\t# mixtures: " << numMixtures << "\n";
			std::cout << "\tmixture definition: " << mixDef << "\n";

			std::vector<std::string> files(1);
			files[0] = std::string(
					"/Users/roxasoath1/Desktop/RibModelDevScripts/RibModelDev/data/FONSE/genome_2000.mutation.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals = parameter.readPhiValues("/home/clandere/CodonUsageBias/RibosomeModel/RibModelFramework/ribModel/data/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
			std::cout << "done initialize Parameter object" << std::endl;
		}


		std::cout << "Initializing Model object\n";

		FONSEModel model;
		model.setParameter(parameter);


		std::cout << "starting MCMC for ROC" << std::endl;
		mcmc.run(genome, model, 4, 0);
		std::cout << std::endl << "Finished MCMC for ROC" << std::endl;

	}
}
Exemplo n.º 5
0
int main()
{
	std::string pathBegin = "/Users/hollisbui/";

	unsigned numMixtures = 1;
	std::vector<double> sphi_init(numMixtures, 2);
	std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;

	// SIMULATE GENOME: RFP
	/*
	Genome genome;
	//genome.readFasta(pathBegin + "HollisTestingData/s288c.genome.fasta");
	genome.readRFPFile(pathBegin + "HollisTestingData/rfp.counts.by.codon.and.gene.GSE63789.wt.csv");
	std::vector<unsigned> geneAssignment(genome.getGenomeSize());
	for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
	{
		geneAssignment[i] = 0u;
	}

	RFPParameter parameter(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, "allUnique");

	std::vector<std::string> files;
	files.push_back(pathBegin + "HollisTestingData/RFPAlphaValues.csv");
	parameter.initMutationSelectionCategories(files, 1, RFPParameter::alp);
	files[0] = pathBegin + "HollisTestingData/RFPLambdaPrimeValues.csv";
	parameter.initMutationSelectionCategories(files, 1, RFPParameter::lmPri);

	std::vector<double> phi = parameter.readPhiValues(pathBegin + "HollisTestingData/RFPPhiValues.csv");
	//std::vector<double> phi = tmp.readPhiValues("/Users/roxasoath1/Desktop/TONEWTON/RFPPsiValues.csv");
	parameter.InitializeSynthesisRate(phi);

	RFPModel model;

	model.setParameter(parameter);

	model.simulateGenome(genome);
	genome.writeRFPFile(pathBegin + "HollisTestingOut/HollisSimulatedGenome2.csv", true);
	exit(1);
	*/

	// UNIT TESTING
	//testUtility();
	//testSequenceSummary();
	//testGene();
	//testGenome(pathBegin + "RibModelFramework/tests/testthat/UnitTestingData");
	//testCovarianceMatrix();
	testParameter();
	//testParameterWithFile(pathBegin + "HollisFile.txt");
	//testTrace();
	//testRFPParameter();
	//testMCMCAlgorithm();
	exit(0);


	std::string modelToRun = "RFP"; //can be RFP, ROC or FONSE
	bool withPhi = false;
	bool fromRestart = false;


	my_print("Initializing MCMCAlgorithm object---------------\n");
	unsigned samples = 10;
	unsigned thinning = 10;
	int useSamples = 100;
	my_print("\t# Samples: %\n", samples);
	my_print("\tThinning: %\n", thinning);
	my_print("\t # Samples used: %\n", useSamples);
	MCMCAlgorithm mcmc = MCMCAlgorithm(samples, thinning, 10, true, true, true);
	//mcmc.setRestartFileSettings(pathBegin + "RestartFile.txt", 20, true);
	my_print("Done!-------------------------------\n\n\n");


	if (modelToRun == "ROC")
	{
		my_print("Initializing Genome object--------------------------\n");
		Genome genome;
		genome.readFasta(pathBegin + "RibModelDev/data/twoMixtures/simulatedAllUniqueR.fasta");
		if (withPhi)
		{
			genome.readObservedPhiValues(pathBegin + "RibModelFramework/ribModel/data/simulatedAllUniqueR_phi.csv", false);
		}
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing ROCParameter object--------------------\n\n");
		ROCParameter parameter;

		if (fromRestart)
		{
			ROCParameter tmp(pathBegin + "RibModelFramework/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			ROCParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategry, sphi_init[selectionCategry]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(2);
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation1.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection1.csv");
			tmp.initSelectionCategories(files, tmp.getNumSelectionCategories());

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals =
			// parameter.readPhiValues(pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing ROCModel object--------------------------\n");
		ROCModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");
	} //END OF ROC
	else if (modelToRun == "RFP")
	{
		my_print("Initializing Genome object--------------------------\n");
		Genome genome;
		genome.readRFPFile(pathBegin + "RibModelDev/data/rfp/rfp.counts.by.codon.and.gene.GSE63789.wt.csv");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing RFPParameter object--------------------\n\n");
		RFPParameter parameter;
		//parameter.writeBasicRestartFile("/Users/hollisbui/HollisFile.txt");

		if (fromRestart)
		{
			RFPParameter tmp(pathBegin + "RibModelFramework/10_restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = Parameter::allUnique;
			RFPParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategry, sphi_init[selectionCategry]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			parameter = tmp;
			//parameter.writeEntireRestartFile("/Users/hollisbui/HollisFile2.txt");
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing RFPModel object--------------------------\n");
		RFPModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");

	} //END OF RFP
	else if (modelToRun == "FONSE")
	{
		my_print("initialize Genome object--------------------------\n");
		Genome genome;
		genome.readFasta(pathBegin + "RibModelDev/data/singleMixture/genome_2000.fasta");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		FONSEParameter parameter;
		my_print("initialize Parameter object\n");
		if (fromRestart)
		{
			FONSEParameter tmp(pathBegin + "RibModelDev/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			FONSEParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategory = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategory, sphi_init[selectionCategory]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(1);
			files[0] = std::string(pathBegin + "RibModelDev/data/singleMixture/genome_2000.mutation.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals = parameter.readPhiValues(
			// pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
			my_print("done initialize Parameter object\n");
		}


		my_print("Initializing Model object\n");
		FONSEModel model;
		model.setParameter(parameter);
		my_print("Done!------------------------\n\n\n");


		my_print("starting MCMC for ROC\n");
		mcmc.run(genome, model, 4, 0);
		my_print("\nFinished MCMC for ROC\n");

	}
}
Exemplo n.º 6
0
int
main (int argc, char *argv[])
try
{
  if (argc < 2)
    return EXIT_FAILURE;

  if (!strcmp (argv[1], "--version"))
    {
      puts ("yaccpp v0.1");
      return EXIT_SUCCESS;
    }

  if (!strcmp (argv[1], "--help"))
    {
      puts ("usage: yaccpp <file> [file]...");
      return EXIT_SUCCESS;
    }

  symbol_table local_symtab;
  symtab = &local_symtab;

  std::vector<std::string> files (argv + 1, argv + argc);;

#if 0
  std::copy (files.begin (), files.end (), std::ostream_iterator<std::string> (std::cout, "\n"));
#endif

  lexer lex (files);
  parser parse (lex);

  if (node_ptr doc = parse ())
    {
      phases::run ("nop", doc);
      phases::run ("anon_rules", doc);
      phases::run ("cardinality", doc);
      phases::run ("insert_syms", doc);
      phases::run ("scobind", doc);
      phases::run ("resolve_refs", doc);
      phases::run ("call_macros", doc);
      return EXIT_SUCCESS;
      phases::run ("print", doc);
      phases::run ("xmlprint", doc);
    }
  else
    {
      return EXIT_FAILURE;
    }

#if 0
  BOOST_FOREACH (node *n, node::nodes)
    printf ("%p : %d\n", n, n ? n->index : -1);
#endif

  assert (node::audit_hash ());
  node::compress_hash ();
  assert (node::audit_hash ());

#if 0
  BOOST_FOREACH (node *n, node::nodes)
    printf ("%p : %d\n", n, n ? n->index : -1);
#endif

  return EXIT_SUCCESS;
}
catch (std::runtime_error const &e)
{
  printf ("runtime error: %s\n", e.what ());
  return EXIT_FAILURE;
}
catch (std::exception const &e)
{
  puts (e.what ());
  return EXIT_FAILURE;
}
Exemplo n.º 7
0
const QStringList QTinyArchive::files() const
{
	return files(this);
}
Exemplo n.º 8
0
	bool posix_storage::has_any_file(storage_error& error)
	{
		m_stat_cache.reserve(files().num_files());
		return aux::has_any_file(files(), m_save_path, m_stat_cache, error);
	}
Exemplo n.º 9
0
	void posix_storage::delete_files(remove_flags_t const options, storage_error& error)
	{
		aux::delete_files(files(), m_save_path, m_part_file_name, options, error);
	}
Exemplo n.º 10
0
/*
 * Function: ReadDirectory
 *
 * > local files, dirs = FileSystem.ReadDirectory(root, path)
 *
 * Return a list of files and dirs in the specified directory.
 *
 * Parameters:
 *
 *   root - a <FileSystemRoot> constant for the root of the dir to read from
 *   path - optional. a directory under the root
 *
 * Returns:
 *
 *   files - a list of files as full paths from the root
 *   dirs - a list of dirs as full paths from the root
 *
 * Availability:
 *
 *   alpha 26
 *
 * Status:
 *
 *   experimental
 */
static int l_filesystem_read_dir(lua_State *l)
{
	LuaFileSystem::Root root = static_cast<LuaFileSystem::Root>(LuaConstants::GetConstantFromArg(l, "FileSystemRoot", 1));
	std::string path;
	if (lua_gettop(l) > 1)
		path = luaL_checkstring(l, 2);

	FileSystem::FileSource *fs = nullptr;
	switch (root) {
		case LuaFileSystem::ROOT_USER:
			fs = &FileSystem::userFiles;
			break;

		case LuaFileSystem::ROOT_DATA:
			fs = &FileSystem::gameDataFiles;
			break;

		default:
			assert(0); // can't happen
			return 0;
	}

	assert(fs);

	{
		try {
			const FileSystem::FileInfo &info = fs->Lookup(path);
			if (!info.IsDir()) {
				luaL_error(l, "'%s' is not a directory", path.c_str());
				return 0;
			}
		}
		catch (std::invalid_argument) {
			luaL_error(l, "'%s' is not a valid path", path.c_str());
			return 0;
		}
	}

	FileSystem::FileEnumerator files(*fs, FileSystem::FileEnumerator::IncludeDirs);
	files.AddSearchRoot(path);

	lua_newtable(l);
	int filesTable = lua_gettop(l);
	lua_newtable(l);
	int dirsTable = lua_gettop(l);

	for (; !files.Finished(); files.Next()) {
		const FileSystem::FileInfo &info = files.Current();

		lua_newtable(l);
		pi_lua_settable(l, "name", info.GetName().c_str());
		push_date_time(l, info.GetModificationTime());
		lua_setfield(l, -2, "mtime");

		if (info.IsDir())
			lua_rawseti(l, dirsTable, lua_rawlen(l, dirsTable)+1);
		else
			lua_rawseti(l, filesTable, lua_rawlen(l, filesTable)+1);
	}

	return 2;
}
Exemplo n.º 11
0
// #include"reaction.h"
int main()
{

////////Input Parameters of the potential (fit parameters) /////
std::string parameters_filename="Input.inp";

NuclearParameters Nu = read_nucleus_parameters( "Input/pca40.inp" );

double Ef=Nu.Ef;
int lmax=5;
double z0=20.0;
double zp0;
double A0=40.0;
double tz=0.5;

int type=1;
int mvolume = 4;
int AsyVolume = 1;

double A = 40.0;

if (tz>0) { zp0=1;}
else {zp0=0;}

double ph_gap = Nu.ph_gap;
double  rStart = .05;
double  rmax = 12.;
double  ham_pts = 180; 

double  rdelt = rmax / ham_pts;

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );

        // Construct Potential Object
        pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
	pot * pott = &pottt;

        // store coulomb potential in order to compare with




 boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A , pott);


  
 double Elower = -11.61818;
 double Eupper = -9.4;
 double jj = .5;
 int ll = 0;
 int Ifine = 1;
 initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
 initiate.exteriorWaveFunct(ll);
 initiate.normalizeWF();


double tol=.01;
double estart=Ef;

///// Making rmesh///

// std::vector<double> rmesh_p= initiate.make_rmesh_point();
 std::vector<double> rmesh_p= initiate.make_rmesh_point();
 std::vector<double> rmesh= initiate.make_rmesh();


////////////////////////////
//// s and d wave functions////
///////////////////////////
int N = 0;
int L = 1;
double J = 0.5;

double Emax=2*-4.7;
double Emin=-200.0 + Emax;

eigen_t waves0=initiate.find_boundstate(rmesh_p, estart,0,L,J,tol);
eigen_t waves1=initiate.find_boundstate(rmesh_p, estart,1,L,J,tol);
eigen_t waves2=initiate.find_boundstate(rmesh_p, estart,2,L,J,tol);
eigen_t waves3=initiate.find_boundstate(rmesh_p, estart,3,L,J,tol);
eigen_t waves4=initiate.find_boundstate(rmesh_p, estart,4,L,J,tol);
eigen_t waves5=initiate.find_boundstate(rmesh_p, estart,5,L,J,tol);
eigen_t waves6=initiate.find_boundstate(rmesh_p, estart,6,0,0.5,tol);

std::ofstream filee("waves/wave.out");
std::cout<<Elower<<std::endl;
//////////
////////////

// Plottinge Pot and wavefuntionsa and their log//
// and also the derivitaves
//////////////////////
double norm0=0,norm1=0,norm2=0,norm3=0,norm4=0,norm5=0,norm6=0;
double normAsymp_s = 0.;
double normAsymp_d = 0.;
double Mproton = 931.5;// 937.27;
double normbob= 0.;

//double Ed = -waves_d.first;
//double Es = -waves_s.first;
//double bbetta_d = std::sqrt(2. * Mproton * (40./41.) * Ed /(197. * 197.));
//double bbetta_s = std::sqrt(2. * Mproton * (40./41.) * Es /(197. * 197.));
//double llambbda = 2.0 * Mproton * (40./41.) * 1.44 * 19. /(197. * 197.);

for(int ii=0;ii<rmesh_p.size();++ii){
      norm0 += rdelt * std::pow(rmesh_p[ii] * waves0.second[ii],2) ;
			norm1 += rdelt * std::pow(rmesh_p[ii] * waves1.second[ii],2) ;
			norm2 += rdelt * std::pow(rmesh_p[ii] * waves2.second[ii],2) ;
			norm3 += rdelt * std::pow(rmesh_p[ii] * waves3.second[ii],2) ;
			norm4 += rdelt * std::pow(rmesh_p[ii] * waves4.second[ii],2) ;
			norm5 += rdelt * std::pow(rmesh_p[ii] * waves5.second[ii],2) ;
			norm6 += rdelt * std::pow(rmesh_p[ii] * waves6.second[ii],2) ;
      //normAsymp_s += rdelt * std::pow((exp(-bbetta_s * rmesh_p[ii]) * std::pow(rmesh_p[ii], -llambbda /( 2.0 * bbetta_s))) ,2); 
      //normAsymp_d += rdelt * std::pow((exp(-bbetta_d * rmesh_p[ii]) * std::pow(rmesh_p[ii], -llambbda /( 2.0 * bbetta_d))) ,2); 
      //normbob += rdelt * std::pow(rmesh_p[ii] * initiate.WaveArray[ii],2);
}


/////////////////////// ADDING CODE FOR SPECTRAL FUNCTION FOLDING WITH SKYRME ////////////////////////

int index=initiate.index_from_LJ(L,J);

std::vector< lj_eigen_t > bound_levels = initiate.get_bound_levels( rmesh, tol );

std::vector< mesh_t > emesh_vec =
        initiate.get_emeshes( rmesh, Emin, Emax, bound_levels );

cout<<"emesh_vec = "<<emesh_vec.size()<<endl;

std::vector< prop_t > prop_vec = initiate.get_propagators( rmesh, emesh_vec );

const prop_t &propE = prop_vec.at(index);

const mesh_t &emesh = emesh_vec.at(index);

std::vector< double > bspec = initiate.spectral_strength( L, J, rmesh, emesh_vec, prop_vec );

mesh_t energym = initiate.get_lj_emesh(L,J,emesh_vec ); 

eigen_t bound_info = initiate.find_boundstate( rmesh, estart, N, L, J, tol );

std::vector< double > &QPF = bound_info.second;

double QPE = bound_info.first;

double S = initiate.sfactor( rmesh, QPE, L, J, QPF );

std::vector< double > chd = initiate.charge_density(rmesh, Emax, emesh_vec, prop_vec, bound_levels);

vector <double> pdist = initiate.point_distribution(rmesh_p,Emax,emesh_vec,prop_vec,bound_levels);

matrix_t d_mtx( rmesh.size(), rmesh.size() ); // density matrix
d_mtx.clear();

//making it so that wavefunction takes skyrme wavefunction as the input and finds the skyrme spectral function

std::ifstream filein("waves/upp12.txt");

double skyrme[rmesh.size()];

std::string line;

double part=0;
double part2=0;

for(int i=0;i<rmesh.size();i++){
	part += chd[i] * rdelt * pow(rmesh[i],2) * 4 * M_PI;
	part2 += pdist[i] * rdelt * pow(rmesh[i],2) * 4 * M_PI;
}

cout<<"Particle Number = "<<part<<endl;
cout<<"Particle Number2 = "<<part2<<endl;

int iii;
iii=0;
while(getline(filein,line)){
	skyrme[iii]=atof(line.c_str());
	iii++;
}

filein.close();

int esize;
esize=emesh.size();

std::vector<double> spec;
std::vector<double> spec2;

std::vector <double> dom0,dom1,dom2,dom3,dom4,dom5,dom6;
double dwave0,dwave1,dwave2,dwave3,dwave4,dwave5,dwave6;

for(int i=0;i<rmesh.size();i++){
	dwave0=rmesh[i]*waves0.second[i]/norm0;
	dom0.push_back(dwave0);
	dwave1=rmesh[i]*waves1.second[i]/norm1;
	dom1.push_back(dwave1);
	dwave2=rmesh[i]*waves2.second[i]/norm2;
	dom2.push_back(dwave2);
	dwave3=rmesh[i]*waves3.second[i]/norm3;
	dom3.push_back(dwave3);
	dwave4=rmesh[i]*waves4.second[i]/norm4;
	dom4.push_back(dwave4);
	dwave5=rmesh[i]*waves5.second[i]/norm5;
	dom5.push_back(dwave5);
	dwave6=rmesh[i]*waves6.second[i]/norm6;
	dom6.push_back(dwave6);
}


//Remember that propE is actually G*r*r'*rdelt
for(unsigned int n=0;n<emesh.size();++n){
	double spf=0.0;
	double spf2=0.0;
	double Edelt=emesh[n].second;
 for( unsigned int i = 0; i < rmesh.size(); ++i ) {
		for( unsigned int j = 0; j < rmesh.size(); ++j ) {
			//d_mtx(i,j) += Edelt * imag(propE[n](i,j)) / (M_PI * rmesh[i] * rmesh[j] * rdelt);
			d_mtx(i,j) += Edelt * imag(propE[n](i,j)) / M_PI; 
  		spf -= rdelt * skyrme[i] * skyrme[j] *imag( propE[n]( i, j ) ) / M_PI;
			spf2 -= rdelt * dom0[i]*dom0[j] *imag( propE[n]( i, j ) ) / M_PI;
			//spf -= rmesh[i] * rmesh[j] * rdelt / M_PI
      //            * QPF[i] * QPF[j] * imag( propE[n]( i, j ) );
  	} 
	} 
	spec.push_back(spf);
	spec2.push_back(spf2);
}

std::ofstream fmtx("waves/dmtx.txt");

for(int i=0;i<rmesh.size();i++){
	for(int j=0;j<rmesh.size();j++){
		fmtx<<d_mtx(i,j)<<" ";
	}
	fmtx<<endl;
}

fmtx.close();
		

std::vector <eigen_t> eig = initiate.real_eigvecs(d_mtx);

double norme=0.0;
double norm=0.0;
double eigsum=0.0;
double maxeig=0.0;

norm0=0,norm1=0,norm2=0,norm3=0,norm4=0,norm5=0,norm6=0;

for(int i=0;i<rmesh.size();++i){
	norm0 += rdelt * pow( eig[0].second[i],2);
	norm1 += rdelt * pow( eig[1].second[i],2);
	norm2 += rdelt * pow( eig[2].second[i],2);
	norm3 += rdelt * pow( eig[3].second[i],2);
	norm4 += rdelt * pow( eig[4].second[i],2);
}

double occ=0.0;

for (int i=0;i<rmesh.size();++i){
	for (int j=0;j<rmesh.size();++j){
		occ += rdelt*rdelt * d_mtx(i,j) * eig[N].second[i]/std::sqrt(norm) * eig[N].second[j]/std::sqrt(norm) * pow(rmesh[i],2) * pow(rmesh[j],2);
	}
}

//cout<<"QP OCCUPATION NUMBER = "<<initiate.occupation(rmesh,d_mtx,QPF)<<endl;

//cout<<"occupation number = "<<occ<<endl;

ofstream fval("waves/i13 2.txt");

fval<<eig[0].first*-1<<std::endl;
fval<<eig[1].first*-1<<std::endl;
fval<<eig[2].first*-1<<endl;
fval<<eig[3].first*-1<<endl;
fval<<eig[4].first*-1<<endl;



std::ofstream feig("waves/eig.out");

//std::cout<<"Here is an eigenvector"<<std::endl;
double esum=0.0;
for(int i=0;i<rmesh.size();++i){
	//want to give R(r), so print out u(r)/r
	feig<<rmesh[i]<<" "<<eig[0].second[i]/sqrt(norm0)/rmesh[i];
	feig<<" "<<eig[1].second[i]/sqrt(norm1)/rmesh[i];
	feig<<" "<<eig[2].second[i]/sqrt(norm2)/rmesh[i];
	feig<<" "<<eig[3].second[i]/sqrt(norm3)/rmesh[i];
	feig<<" "<<eig[4].second[i]/sqrt(norm4)/rmesh[i]<<endl;;
//	esum += rdelt*pow(rmesh[i]*eig[N].second[i]/sqrt(norme),2);
}

//std::cout<<"esum = "<<esum<<std::endl;

//This is where I will find rhobar, ask houssein how to put in clebsch gordon and spherical harmonics
double dens=0.0;
int nt=50;
int np=25;
double dt=2*M_PI/nt;
double dp=M_PI/np;
for(int i=0;i<rmesh.size();i++){
	for(int j=0;j<nt;j++){
		for(int k=0;k<np;k++){
			dens+= rdelt*rdelt * skyrme[i]*skyrme[i] * chd[i]; //* spherical harmonics and clebsch gordon * sin(theta)
		}
	}
}

std::vector< double >  s_of_Eqh = initiate.spectral_strength_QH( L, J, rmesh, emesh_vec, prop_vec, QPF);

std::ofstream fden("waves/chd.out");
ofstream fpoint("waves/p.out");
std::ofstream fileout("waves/spec.out");
std::ofstream files("waves/skyrme.out");
std::ofstream fileq("waves/quasi.out");
std::ofstream filef("waves/fold.out");
std::ofstream filed("waves/dom.out");
std::ofstream filer("waves/r.out");
//std::ofstream filep("waves/prop.out");

for(int i=0;i<rmesh.size();i++){
	files<<skyrme[i]<<endl;
	fileq<<QPF[i]<<endl;
	filer<<rmesh[i]<<" "<<rmesh_p[i]<<endl;
	fden<<rmesh[i]<<" "<<chd[i]<<endl;
	fpoint<<rmesh[i]<<" "<<pdist[i]<<endl;
}

for(int i=0;i<bspec.size();i++){
	fileout<<energym[i].first<<" "<<energym[i].second<<" "<<spec[i]<<endl;
	filed<<energym[i].first<<" "<<energym[i].second<<" "<<spec2[i]<<endl;
	filef<<energym[i].first<<" "<<energym[i].second<<" "<<s_of_Eqh[i]<<endl;	
}

filed.close();
filer.close();
filef.close();
fileq.close();
files.close();
fileout.close();

///////////  END OF ADDED CODE ///////////////////////////////////////



////////
//normalizing wavefunctions at 4.008 to s wave to compare the asymptotic behaviour and energy
//the value of s at 4.008 is .023309//d is .132997 , s_asymp is .000271922 , d_asymp  i s .000336918
/////////
for(int ii=0;ii<rmesh.size();++ii){
      filee<<dom0[ii]/rmesh[ii]<<" "<<dom1[ii]<<" "<<dom2[ii]<<" "<<dom3[ii]<<" "<<dom4[ii]<<" "<<dom5[ii]<<std::endl;  
}
//std::cout <<"Es =" << waves_s.first << " " << "Ed= " << waves_d.first <<std::endl;
//std::cout << zp0 << " " << tz<<" "<<norm_s<<" "<< norm_d<<" "<< normAsymp_s<<" norm bob=" << normbob<< std::endl;
//std::cout <<"Elower = "<< Elower <<" " << "Eupper = " << Eupper<<std::endl;
filee.close();
std::cout<<"Spectral Factor = "<<S<<endl;
std::cout<<"Quasi-hole Energy = "<<QPE<<endl;
return 0;

}
Exemplo n.º 12
0
int main(int argc, char * argv[]) {
  try {
    indri::api::Parameters& parameters = indri::api::Parameters::instance();
    parameters.loadCommandLine( argc, argv );

    require_parameter( "corpus", parameters );
    require_parameter( "index", parameters );

    StatusMonitor monitor;
    indri::api::IndexEnvironment env;
    std::string repositoryPath = parameters["index"];

    buildindex_start_time();

    if( parameters.get( "version", 0 ) ) {
      std::cout << INDRI_DISTRIBUTION << std::endl;
    }

    env.setMemory( parameters.get("memory", INT64(1024*1024*1024)) );

    env.setNormalization( parameters.get("normalize", true));
    env.setInjectURL( parameters.get("injectURL", true));
    env.setStoreDocs( parameters.get("storeDocs", true));

    std::string blackList = parameters.get("blacklist", "");
    if( blackList.length() ) {
        int count = env.setBlackList(blackList);
        std::cout << "Added to blacklist: "<< count << std::endl;
        std::cout.flush();
    }

    std::string offsetAnnotationHint=parameters.get("offsetannotationhint", "default");
    if (offsetAnnotationHint=="ordered") {
      env.setOffsetAnnotationIndexHint(indri::parse::OAHintOrderedAnnotations);
    } if (offsetAnnotationHint=="unordered") {
      env.setOffsetAnnotationIndexHint(indri::parse::OAHintSizeBuffers);
    } else {
      env.setOffsetAnnotationIndexHint(indri::parse::OAHintDefault);
    }

    std::string stemmerName = parameters.get("stemmer.name", "");
    if( stemmerName.length() )
      env.setStemmer(stemmerName);

    std::vector<std::string> stopwords;
    if( copy_parameters_to_string_vector( stopwords, parameters, "stopper.word" ) )
      env.setStopwords(stopwords);
    // fields to include as metadata (unindexed)
    std::vector<std::string> metadata;
    // metadata fields that should have a forward lookup table.
    std::vector<std::string> metadataForward;
    // metadata fields that should have a backward lookup table.
    std::vector<std::string> metadataBackward;
    copy_parameters_to_string_vector( metadata, parameters, "metadata.field" ); 
    downcase_string_vector(metadata);
    
    copy_parameters_to_string_vector( metadataForward, parameters, "metadata.forward" ); 
    downcase_string_vector(metadataForward);
    copy_parameters_to_string_vector( metadataBackward, parameters, "metadata.backward" );
    downcase_string_vector(metadataBackward);
    // docno is a special field, automagically add it as forward and backward.
    std::string docno = "docno";
    if( std::find( metadataForward.begin(), 
                   metadataForward.end(), 
                   docno ) == metadataForward.end() )
      metadataForward.push_back(docno);
    if( std::find( metadataBackward.begin(), 
                   metadataBackward.end(), 
                   docno ) == metadataBackward.end() )
      metadataBackward.push_back(docno);

    env.setMetadataIndexedFields( metadataForward, metadataBackward );
#if 0    
    // "document" is a special field.
    // automagically add it as an indexed field.
    indri::api::Parameters field = parameters.append("field");
    field.set( "name", "document" );
    field.set( "ordinal", true );
    field.set("parental", true);
#endif
    std::vector<std::string> fields;    
    std::string subName = "name";
    if( copy_parameters_to_string_vector( fields, parameters, "field", &subName ) ) {
      downcase_string_vector(fields);
      env.setIndexedFields(fields);
      process_numeric_fields( parameters, env );
      process_ordinal_fields( parameters, env );
      process_parental_fields( parameters, env ); //pto
    }

    if( indri::collection::Repository::exists( repositoryPath ) ) {
      // check if the repository was corrupted by an indexing crash
      // if so, recover it and continue.
      if (_recoverRepository(repositoryPath)) {
        env.open( repositoryPath, &monitor );
        buildindex_print_event( std::string() + "Opened repository " + repositoryPath ); 
      } else  {
        //  failed to open it, needs to be created from scratch.
        // create will remove any cruft.
        env.create( repositoryPath, &monitor );
        buildindex_print_event( std::string() + "Created repository " + repositoryPath );
      }
    } else {
      env.create( repositoryPath, &monitor );
      buildindex_print_event( std::string() + "Created repository " + repositoryPath );
    }

    indri::api::Parameters corpus = parameters["corpus"];

    for( unsigned int i=0; i<corpus.size(); i++ ) {
      indri::api::Parameters thisCorpus = corpus[i];
      require_parameter( "path", thisCorpus );
      std::string corpusPath = thisCorpus["path"];
      std::string fileClass = thisCorpus.get("class", "");
      
      // augment field/metadata tags in the environment if needed.
      if( fileClass.length() ) {
        indri::parse::FileClassEnvironmentFactory::Specification *spec = env.getFileClassSpec(fileClass);
        if( spec ) {
          // add fields if necessary, only update if changed.
          if( augmentSpec( spec, fields, metadata, metadataForward, metadataBackward ) ) 
            env.addFileClass(*spec);
          delete(spec);
        }
      }
      
      bool isDirectory = indri::file::Path::isDirectory( corpusPath );
 
      // First record the document root, and then the paths to any annotator inputs
      env.setDocumentRoot( corpusPath );

      // Support for anchor text
      std::string anchorText = thisCorpus.get("inlink", "");
      env.setAnchorTextPath( anchorText );

      // Support for offset annotations
      std::string offsetAnnotationsPath = thisCorpus.get( "annotations", "" );
      env.setOffsetAnnotationsPath( offsetAnnotationsPath );

      // Support for offset metadata file
      std::string offsetMetadataPath = thisCorpus.get( "metadata", "" );
      env.setOffsetMetadataPath( offsetMetadataPath );

      if( isDirectory ) {
        indri::file::FileTreeIterator files( corpusPath );

        for( ; files != indri::file::FileTreeIterator::end(); files++ ) {
          if( fileClass.length() )
            env.addFile( *files, fileClass );
          else {
            std::string extension = indri::file::Path::extension( *files );
            indri::parse::FileClassEnvironmentFactory::Specification *spec = env.getFileClassSpec(extension);
            if( spec ) {
              // add fields if necessary, only update if changed.
              if( augmentSpec( spec, fields, metadata, metadataForward, metadataBackward ) ) 
                env.addFileClass(*spec);
              delete(spec);
            }
            env.addFile( *files );
          }
        }
      } else {
        if( fileClass.length() )
          env.addFile( corpusPath, fileClass );
        else {
          std::string extension = indri::file::Path::extension( corpusPath );
          indri::parse::FileClassEnvironmentFactory::Specification *spec = env.getFileClassSpec(extension);
          if( spec ) {
            // add fields if necessary, only update if changed.
            if( augmentSpec( spec, fields, metadata, metadataForward, metadataBackward ) ) 
              env.addFileClass(*spec);
            delete(spec);
          }
          env.addFile( corpusPath );
        }
      }
    }

    buildindex_print_event( "Closing index" );
    env.close();
    buildindex_print_event( "Finished" );
  } catch( lemur::api::Exception& e ) {
    LEMUR_ABORT(e);
  }

  return 0;
}
Exemplo n.º 13
0
        unique_ptr<ArchiveMetadata> ArchiveMetadata::readArchiveMetadata(ifstream &fs) {
            if (!fs.is_open()) {
                throw "File couldn't be opened!";
            }
            fs.seekg(ios_base::beg);

            // --------------------
            // Read in archive file
            // --------------------
            // Archive Header
            ArchiveHeader archiveHeader;
            fs.read(reinterpret_cast<char *>(&archiveHeader), sizeof(ArchiveHeader));

            // File List
            FileList fileList;
            fs.seekg(archiveHeader.fileListOffset);

            uint32_t fileCount;
            fs.read(reinterpret_cast<char *>(&fileCount), sizeof(uint32_t));
            fileList.count = fileCount;

            // File Entries
            vector<FileEntry> files(fileCount);
            fs.read(reinterpret_cast<char *>(&files[0]), fileCount * sizeof(FileEntry));
            fileList.files = files;

            // Path List
            PathList pathList;
            fs.seekg(archiveHeader.pathListOffset);

            uint32_t pathBytes;
            fs.read(reinterpret_cast<char *>(&pathBytes), sizeof(uint32_t));
            pathList.bytes = pathBytes;

            uint32_t pathCount;
            fs.read(reinterpret_cast<char *>(&pathCount), sizeof(uint32_t));
            pathList.count = pathCount;

            // Path Entries
            vector<PathEntry> paths(pathCount);
            fs.read(reinterpret_cast<char *>(&paths[0]), pathCount * sizeof(PathEntry));
            pathList.paths = paths;

            // --------------------------
            // Build Archive model object
            // --------------------------
            unique_ptr<ArchiveMetadata> metadata(new ArchiveMetadata());
            map<string, File> fileMap;

            for (auto it = files.begin(); it < files.end(); it++) {
                PathEntry pathEntry = paths[it->pathListIndex];

                uint32_t adjustedPathOffset = archiveHeader.pathListOffset + pathEntry.offset;
                uint32_t pathLength = pathEntry.length;
                
                char *bytes = new char[pathLength];
                fs.seekg(adjustedPathOffset);
                fs.read(bytes, pathLength);
                string path = string(bytes, pathLength - 1);
                delete bytes;
                assert(File::calculatePathHash(path) == it->pathHash);
                fileMap.insert(make_pair(path, File(path, it->dataOffset, it->dataSize)));
            }
            
            metadata->setFiles(fileMap);
            return metadata;
        }
Exemplo n.º 14
0
int main(int argc, char** argv)
try
{
    po::options_description desc("Required options");
    desc.add_options()
    ("help,h", "produce help message")
    ("force,f", "overwrite existing files")
    ("mpq", po::value<std::string>(), "the mpq to create")
    ("files", po::value<std::vector<std::string> >(), "input files");

    po::positional_options_description p;

    p.add("mpq", 1);
    p.add("files", -1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (!vm.count("files") || !vm.count("mpq") || vm.count("help"))
    {
        std::cout << "usage: <mpq> [<files> ...]" << std::endl << std::endl
                  << desc << std::endl;
        return 1;
    }

    std::vector<std::string> files(vm["files"].as< std::vector<std::string> >());
    std::vector<FileEntry> toAdd;
    fs::path mpqPath(vm["mpq"].as<std::string>());

    if(fs::exists(mpqPath))
    {
        if(vm.count("force"))
            fs::remove(mpqPath);
        else
            throw std::runtime_error("mpq does already exist");
    }

    for(std::vector<std::string>::iterator path = files.begin(); path != files.end(); ++path)
    {
        if(fs::is_regular_file(*path))
            toAdd.push_back(FileEntry(*path, *path));

        if(!fs::is_directory(*path)) //no symlinks etc
            continue;

        for(fs::recursive_directory_iterator file(*path), end; file != end; ++file)
            if(fs::is_regular_file(file->path()))
                toAdd.push_back(FileEntry(file->path(), makeRelative(*path, file->path())));
    }

    for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it)
        std::cout << it->realPath << " >> " << it->mpqPath << std::endl;

    HANDLE mpq;
    if(!SFileCreateArchive(mpqPath.string().c_str(), MPQ_CREATE_ARCHIVE_V2, toAdd.size(), &mpq))
        throw std::runtime_error("couldn't create mpq");

    SFileSetLocale(0);

    size_t counter(0);
    for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it)
    {
        loadbar(++counter, toAdd.size());

        if(!SFileAddFileEx(mpq, it->realPath.string().c_str(), it->mpqPath.string().c_str(), MPQ_FILE_COMPRESS, MPQ_COMPRESSION_BZIP2, MPQ_COMPRESSION_BZIP2))
            std::cout << "couldn't add file " << it->realPath << std::endl;
    }

    std::cout << std::endl;
    SFileCompactArchive(mpq, NULL, false);

    SFileFlushArchive(mpq);
    SFileCloseArchive(mpq);

    return 0;
}
catch (const std::exception& e)
{
    std::cerr << "error: " << e.what() << "\n";
}
Exemplo n.º 15
0
main()
{	int i;
	char *p;

	uid = getuid();
	myname = (char *)getlogin();
	if(myname == NULL)
		myname = getpwuid(uid)->pw_name;
	comminit();
	mbuf = itom(0);
	files();
	setup(getpass("Key: "));
	mkb();
	mkx();
#ifndef debug
	invert(x, b, x);
#else
	invert(x, b, z);
	mult(x, z, z);
	mdiv(z, b, q, z);
	omout(z);
	invert(x, b, x);
#endif
	for(i=0; i<fcnt; i++)
	{	sprintf(line, "%s%s.%d", maildir, myname, fnum[i]);
		if(stat(line, &stbuf)<0)
		{	perror(line);
			continue;
		}
		if(stbuf.st_size == 0)
		{	printf("zero length mail file\n");
			unlink(line);
			continue;
		}
		if((mf = fopen(line, "r"))==NULL)
		{	perror(line);
			continue;
		}
		decipher(mf, stdout);
	cmnd:
		printf("? ");
		fgets(buf, sizeof(buf), stdin);
		if(feof(stdin)) exit(0);
		switch(buf[0])
		{
		case 'q':
			exit(0);
		case 'n':
		case 'd':
		case '\n':
			fclose(mf);
			unlink(line);
			break;
		case '!':
			system(buf+1);
			printf("!\n");
			goto cmnd;
		case 's':
		case 'w':
			rewind(mf);
			if(buf[1] == '\n' || buf[1] == '\0')
				strcpy(buf, "s mbox\n");
			for(p = buf+1; isspace(*p); p++);
			p[strlen(p)-1] = 0;
			kf = fopen(p, "a");
			if(kf == NULL)
			{	perror(p);
				goto cmnd;
			}
			decipher(mf, kf);
			fclose(mf);
			fclose(kf);
			unlink(line);
			break;
		default:
			printf("Commands are:\n");
			printf("q	quit, leaving unread messages\n");
			printf("n	delete current message and goto next\n");
			printf("d	same as above\n");
			printf("\\n	same as above\n");
			printf("!	execute shell command\n");
			printf("s	save message in the named file or mbox\n");
			printf("w	same as above\n");
			printf("?	prints this list\n");
			goto cmnd;
		}
	}
	exit(0);
}
Exemplo n.º 16
0
	FILE* posix_storage::open_file(file_index_t idx, open_mode_t const mode
		, std::int64_t const offset, storage_error& ec)
	{
		std::string const fn = files().file_path(idx, m_save_path);

		char const* mode_str = (mode & open_mode::write)
			? "rb+" : "rb";

		FILE* f = fopen(fn.c_str(), mode_str);
		if (f == nullptr)
		{
			ec.ec.assign(errno, generic_category());

			// if we fail to open a file for writing, and the error is ENOENT,
			// it is likely because the directory we're creating the file in
			// does not exist. Create the directory and try again.
			if ((mode & open_mode::write)
				&& ec.ec == boost::system::errc::no_such_file_or_directory)
			{
				// this means the directory the file is in doesn't exist.
				// so create it
				ec.ec.clear();
				create_directories(parent_path(fn), ec.ec);

				if (ec.ec)
				{
					ec.file(idx);
					ec.operation = operation_t::mkdir;
					return nullptr;
				}

				// now that we've created the directories, try again
				// and make sure we create the file this time ("r+") opens for
				// reading and writing, but doesn't create the file. "w+" creates
				// the file and truncates it
				f = fopen(fn.c_str(), "wb+");
				if (f == nullptr)
				{
					ec.ec.assign(errno, generic_category());
					ec.file(idx);
					ec.operation = operation_t::file_open;
					return nullptr;
				}
			}
			else
			{
				ec.file(idx);
				ec.operation = operation_t::file_open;
				return nullptr;
			}
		}

#ifdef TORRENT_WINDOWS
#define fseek _fseeki64
#endif

		if (offset != 0)
		{
			if (fseek(f, offset, SEEK_SET) != 0)
			{
				ec.ec.assign(errno, generic_category());
				ec.file(idx);
				ec.operation = operation_t::file_seek;
				fclose(f);
				return nullptr;
			}
		}

		return f;
	}
Exemplo n.º 17
0
int main(int argc, char** argv)
{
#if MAPPER_USE_QTSINGLEAPPLICATION
	// Create single-instance application.
	// Use "oo-mapper" instead of the executable as identifier, in case we launch from different paths.
	QtSingleApplication qapp("oo-mapper", argc, argv);
	if (qapp.isRunning()) {
		// Send a message to activate the running app, and optionally open a file
		qapp.sendMessage((argc > 1) ? argv[1] : "");
		return 0;
	}
#else
	QApplication qapp(argc, argv);
#endif
	
	// Load resources
#ifdef MAPPER_USE_QT_CONF_QRC
	Q_INIT_RESOURCE(qt);
#endif
	Q_INIT_RESOURCE(resources);
	Q_INIT_RESOURCE(licensing);
	
	// QSettings on OS X benefits from using an internet domain here.
	QCoreApplication::setOrganizationName("OpenOrienteering.org");
	QCoreApplication::setApplicationName("Mapper");
	
	// Set settings defaults
	Settings& settings = Settings::getInstance();
	settings.applySettings();
	
#ifdef WIN32
	// Load plugins on Windows
	qapp.addLibraryPath(QCoreApplication::applicationDirPath() + "/plugins");
#endif
	
	// Localization
	TranslationUtil::setBaseName(QString("OpenOrienteering"));
	QLocale::Language lang = (QLocale::Language)settings.getSetting(Settings::General_Language).toInt();
	QString translation_file = settings.getSetting(Settings::General_TranslationFile).toString();
	TranslationUtil translation(lang, translation_file);
	QLocale::setDefault(translation.getLocale());
#if defined(Mapper_DEBUG_TRANSLATIONS)
	if (!translation.getAppTranslator().isEmpty())
	{
		// Debug translation only if there is a Mapper translation, i.e. not for English.
		qapp.installTranslator(new RecordingTranslator());
	}
#endif
	qapp.installTranslator(&translation.getQtTranslator());
	qapp.installTranslator(&translation.getAppTranslator());
	
	// Avoid numeric issues in libraries such as GDAL
	setlocale(LC_NUMERIC, "C");
	
	// Initialize static things like the file format registry.
	doStaticInitializations();
	
	QStyle* base_style = nullptr;
#if !defined(Q_OS_WIN) && !defined(Q_OS_OSX)
	if (QGuiApplication::platformName() == QLatin1String("xcb"))
	{
		// Use the modern 'fusion' style instead of the 
		// default "windows" style on X11.
		base_style = QStyleFactory::create("fusion");
	}
#endif
	QApplication::setStyle(new MapperProxyStyle(base_style));
#if !defined(Q_OS_OSX)
	QApplication::setPalette(QApplication::style()->standardPalette());
#endif
	
	// Create first main window
	MainWindow first_window(true);
	first_window.setAttribute(Qt::WA_DeleteOnClose, false);
	first_window.setController(new HomeScreenController());
	
	bool no_files_given = true;
#ifdef Q_OS_ANDROID
	QAndroidJniObject activity = QtAndroid::androidActivity();
	QAndroidJniObject intent = activity.callObjectMethod("getIntent", "()Landroid/content/Intent;");
	const QString action = intent.callObjectMethod<jstring>("getAction").toString();
	static const QString action_edit =
	  QAndroidJniObject::getStaticObjectField<jstring>("android/content/Intent", "ACTION_EDIT").toString();
	static const QString action_view =
	  QAndroidJniObject::getStaticObjectField<jstring>("android/content/Intent", "ACTION_VIEW").toString();
	if (action == action_edit || action == action_view)
	{
		const QString data_string = intent.callObjectMethod<jstring>("getDataString").toString();
		const QString local_file  = QUrl(data_string).toLocalFile();
		first_window.setHomeScreenDisabled(true);
		first_window.setCentralWidget(new QLabel(MainWindow::tr("Loading %1...").arg(local_file)));
		first_window.setVisible(true);
		first_window.raise();
		// Empircal tested: We need to process the loop twice.
		QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
		QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
		if (!first_window.openPath(local_file))
			return -1;
		return qapp.exec();
	}
#else
	// Open given files later, i.e. after the initial home screen has been
	// displayed. In this way, error messages for missing files will show on 
	// top of a regular main window (home screen or other file).
	
	// Treat all program parameters as files to be opened
	QStringList args(qapp.arguments());
	args.removeFirst(); // the program name
	for (auto&& arg : args)
	{
		if (arg[0] != '-')
		{
			first_window.openPathLater(arg);
			no_files_given = false;
		}
	}
#endif
	
	// Optionally open most recently used file on startup
	if (no_files_given && settings.getSettingCached(Settings::General_OpenMRUFile).toBool())
	{
		QStringList files(settings.getSettingCached(Settings::General_RecentFilesList).toStringList());
		if (!files.isEmpty())
			first_window.openPathLater(files[0]);
	}
	
#if MAPPER_USE_QTSINGLEAPPLICATION
	// If we need to respond to a second app launch, do so, but also accept a file open request.
	qapp.setActivationWindow(&first_window);
	QObject::connect(&qapp, SIGNAL(messageReceived(const QString&)), &first_window, SLOT(openPath(const QString &)));
#endif
	
	// Let application run
	first_window.setVisible(true);
	first_window.raise();
	return qapp.exec();
}
Exemplo n.º 18
0
    void FindSegmentsFile::doRun(IndexCommitPtr commit)
    {
        if (commit)
        {
            if (directory != commit->getDirectory())
                boost::throw_exception(IOException(L"The specified commit does not match the specified Directory"));
            runBody(commit->getSegmentsFileName());
            return;
        }
        
        String segmentFileName;
        int64_t lastGen = -1;
        int64_t gen = 0;
        int32_t genLookaheadCount = 0;
        bool retry = false;
        LuceneException exc;
        SegmentInfosPtr segmentInfos(_segmentInfos);
        
        int32_t method = 0;
        
        // Loop until we succeed in calling runBody() without hitting an IOException.  An IOException most likely
        // means a commit was in process and has finished, in the time it took us to load the now-old infos files
        // (and segments files).  It's also possible it's a true error (corrupt index).  To distinguish these,
        // on each retry we must see "forward progress" on which generation we are trying to load.  If we don't, 
        // then the original error is real and we throw it.

        // We have three methods for determining the current generation.  We try the first two in parallel, and
        // fall back to the third when necessary.
        
        while (true)
        {
            if (method == 0)
            {
                // Method 1: list the directory and use the highest segments_N file.  This method works well as long
                // as there is no stale caching on the directory contents (NOTE: NFS clients often have such stale caching)
                HashSet<String> files(directory->listAll());
                int64_t genA = segmentInfos->getCurrentSegmentGeneration(files);

                segmentInfos->message(L"directory listing genA=" + StringUtils::toString(genA));

                // Method 2: open segments.gen and read its contents.  Then we take the larger of the two gens.  This way,
                // if either approach is hitting a stale cache (NFS) we have a better chance of getting the right generation.
                int64_t genB = -1;
                for (int32_t i = 0; i < SegmentInfos::defaultGenFileRetryCount; ++i)
                {
                    IndexInputPtr genInput;
                    try
                    {
                        genInput = directory->openInput(IndexFileNames::SEGMENTS_GEN());
                    }
                    catch (FileNotFoundException& e)
                    {
                        segmentInfos->message(L"Segments.gen open: FileNotFoundException " + e.getError());
                        break;
                    }
                    catch (IOException& e)
                    {
                        segmentInfos->message(L"Segments.gen open: IOException " + e.getError());
                    }
                    
                    if (genInput)
                    {
                        LuceneException finally;
                        bool fileConsistent = false;
                        try
                        {
                            int32_t version = genInput->readInt();
                            if (version == SegmentInfos::FORMAT_LOCKLESS)
                            {
                                int64_t gen0 = genInput->readLong();
                                int64_t gen1 = genInput->readLong();
                                segmentInfos->message(L"fallback check: " + StringUtils::toString(gen0) + L"; " + StringUtils::toString(gen1));
                                if (gen0 == gen1)
                                {
                                    // the file is consistent
                                    genB = gen0;
                                    fileConsistent = true;
                                }
                            }
                        }
                        catch (IOException&)
                        {
                            // will retry
                        }
                        catch (LuceneException& e)
                        {
                            finally = e;
                        }
                        genInput->close();
                        finally.throwException();
                        if (fileConsistent)
                            break;
                    }
                    
                    LuceneThread::threadSleep(SegmentInfos::defaultGenFileRetryPauseMsec);
                }
                
                segmentInfos->message(String(IndexFileNames::SEGMENTS_GEN()) + L" check: genB=" + StringUtils::toString(genB));

                // pick the larger of the two gen's
                gen = std::max(genA, genB);
                
                // neither approach found a generation
                if (gen == -1)
                    boost::throw_exception(FileNotFoundException(L"No segments* file found in directory"));
            }
            
            // Third method (fallback if first & second methods are not reliable): since both directory cache and
            // file contents cache seem to be stale, just advance the generation.
            if (method == 1 || (method == 0 && lastGen == gen && retry))
            {
                method = 1;
                
                if (genLookaheadCount < SegmentInfos::defaultGenLookaheadCount)
                {
                    ++gen;
                    ++genLookaheadCount;
                    segmentInfos->message(L"look ahead increment gen to " + StringUtils::toString(gen));
                }
            }
            
            if (lastGen == gen)
            {
                // This means we're about to try the same segments_N last tried.  This is allowed, exactly once, because 
                // writer could have been in the process of writing segments_N last time.
                
                if (retry)
                {
                    // OK, we've tried the same segments_N file twice in a row, so this must be a real error.
                    exc.throwException();
                }
                else
                    retry = true;
            }
            else if (method == 0)
            {
                // Segment file has advanced since our last loop, so reset retry
                retry = false;
            }
            
            lastGen = gen;
            
            segmentFileName = IndexFileNames::fileNameFromGeneration(IndexFileNames::SEGMENTS(), L"", gen);
            
            try
            {
                runBody(segmentFileName);
                segmentInfos->message(L"success on " + segmentFileName);
                return;
            }
            catch (LuceneException& err)
            {
                // Save the original root cause
                if (exc.isNull())
                    exc = err;
                
                segmentInfos->message(L"primary Exception on '" + segmentFileName + L"': " + err.getError() + L"'; will retry: retry=" + StringUtils::toString(retry) + L"; gen = " + StringUtils::toString(gen));
                
                if (!retry && gen > 1)
                {
                    // This is our first time trying this segments file (because retry is false), and, there is possibly a 
                    // segments_(N-1) (because gen > 1). So, check if the segments_(N-1) exists and try it if so.
                    String prevSegmentFileName(IndexFileNames::fileNameFromGeneration(IndexFileNames::SEGMENTS(), L"", gen - 1));
                    
                    if (directory->fileExists(prevSegmentFileName))
                    {
                        segmentInfos->message(L"fallback to prior segment file '" + prevSegmentFileName + L"'");
                        
                        try
                        {
                            runBody(prevSegmentFileName);
                            if (!exc.isNull())
                                segmentInfos->message(L"success on fallback " + prevSegmentFileName);
                            return;
                        }
                        catch (LuceneException& err2)
                        {
                            segmentInfos->message(L"secondary Exception on '" + prevSegmentFileName + L"': " + err2.getError() + L"'; will retry");
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 19
0
QVariant AppsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_entryList.count()) {
        return QVariant();
    }

    const AbstractEntry *entry = m_entryList.at(index.row());

    if (role == Qt::DisplayRole) {
        return entry->name();
    } else if (role == Qt::DecorationRole) {
        return entry->icon();
    } else if (role == Kicker::IsParentRole) {
        return (entry->type() == AbstractEntry::GroupType);
    } else if (role == Kicker::HasChildrenRole) {
        if (entry->type() == AbstractEntry::GroupType) {
            const AbstractGroupEntry *groupEntry = static_cast<const AbstractGroupEntry *>(entry);

            if (groupEntry->model() && groupEntry->model()->count()) {
                return true;
            }
        }
    } else if (role == Kicker::FavoriteIdRole) {
        if (entry->type() == AbstractEntry::RunnableType) {
            return QVariant("app:" + static_cast<AppEntry *>(m_entryList.at(index.row()))->service()->storageId());
        }
    } else if (role == Kicker::HasActionListRole) {
        if (entry->type() == AbstractEntry::RunnableType || !m_hiddenEntries.isEmpty()) {
            return true;
        } else if (entry->type() == AbstractEntry::GroupType) {
            const AbstractGroupEntry *groupEntry = static_cast<const AbstractGroupEntry *>(entry);

            if (groupEntry->model()) {
                const AppsModel *appsModel = qobject_cast<const AppsModel *>(groupEntry->model());

                if (appsModel && !appsModel->hiddenEntries().isEmpty()) {
                    return true;
                }
            }
        }
    } else if (role == Kicker::ActionListRole) {
        QVariantList actionList;

        if (entry->type() == AbstractEntry::RunnableType) {
            const KService::Ptr service = static_cast<const AppEntry *>(entry)->service();

            if (ContainmentInterface::mayAddLauncher(m_appletInterface, ContainmentInterface::Desktop)) {
                actionList << Kicker::createActionItem(i18n("Add to Desktop"), "addToDesktop");
            }

            if (ContainmentInterface::mayAddLauncher(m_appletInterface, ContainmentInterface::Panel)) {
                actionList << Kicker::createActionItem(i18n("Add to Panel"), "addToPanel");
            }

            if (ContainmentInterface::mayAddLauncher(m_appletInterface, ContainmentInterface::TaskManager, service->entryPath())) {
                actionList << Kicker::createActionItem(i18n("Add as Launcher"), "addToTaskManager");
            }

            if (m_menuEntryEditor->canEdit(service->entryPath())) {
                actionList << Kicker::createSeparatorActionItem();

                QVariantMap editAction = Kicker::createActionItem(i18n("Edit Application..."), "editApplication");
                editAction["icon"] = "kmenuedit"; // TODO: Using the KMenuEdit icon might be misleading.
                actionList << editAction;
            }

#ifdef PackageKitQt5_FOUND
            QStringList files(service->entryPath());

            if (service->isApplication()) {
                files += QStandardPaths::findExecutable(KShell::splitArgs(service->exec()).first());
            }

            FindPackageJob* job = new FindPackageJob(files); // TODO: Would be great to make this async.

            if (job->exec() && !job->packageNames().isEmpty()) {
                QString packageName = job->packageNames().first();

                QVariantMap removeAction = Kicker::createActionItem(i18n("Remove '%1'...", packageName), "removeApplication", packageName);
                removeAction["icon"] = "applications-other";
                actionList << removeAction;
            }
#endif

            if (appletConfig() && appletConfig()->contains("hiddenApplications")) {
                const QStringList &hiddenApps = appletConfig()->value("hiddenApplications").toStringList();

                if (!hiddenApps.contains(service->menuId())) {
                    actionList << Kicker::createActionItem(i18n("Hide Application"), "hideApplication");
                }
            }
        }

        if (!m_hiddenEntries.isEmpty()) {
            actionList << Kicker::createSeparatorActionItem();
            actionList << Kicker::createActionItem(i18n("Unhide Applications in this Submenu"), "unhideSiblingApplications");
        }

        if (entry->type() == AbstractEntry::GroupType) {
            const AbstractGroupEntry *groupEntry = static_cast<const AbstractGroupEntry *>(entry);

            if (groupEntry->model()) {
                const AppsModel *appsModel = qobject_cast<const AppsModel *>(groupEntry->model());

                if (appsModel && !appsModel->hiddenEntries().isEmpty()) {
                    actionList << Kicker::createActionItem(i18n("Unhide Applications in '%1'", entry->name()), "unhideChildApplications");
                }
            }
        }

        return actionList;
    } else if (role == Kicker::UrlRole) {
        if (entry->type() == AbstractEntry::RunnableType) {
            return QUrl::fromLocalFile(static_cast<AppEntry *>(m_entryList.at(index.row()))->service()->entryPath());
        }
    }

    return QVariant();
}
Exemplo n.º 20
0
void ShipType::Init()
{
	static bool isInitted = false;
	if (isInitted) return;
	isInitted = true;

	lua_State *l = luaL_newstate();

	LUA_DEBUG_START(l);

	luaL_requiref(l, "_G", &luaopen_base, 1);
	luaL_requiref(l, LUA_DBLIBNAME, &luaopen_debug, 1);
	luaL_requiref(l, LUA_MATHLIBNAME, &luaopen_math, 1);
	lua_pop(l, 3);

	LuaConstants::Register(l);
	LuaVector::Register(l);
	LUA_DEBUG_CHECK(l, 0);

	// provide shortcut vector constructor: v = vector.new
	lua_getglobal(l, LuaVector::LibName);
	lua_getfield(l, -1, "new");
	assert(lua_iscfunction(l, -1));
	lua_setglobal(l, "v");
	lua_pop(l, 1); // pop the vector library table

	LUA_DEBUG_CHECK(l, 0);

	// register ship definition functions
	lua_register(l, "define_ship", define_ship);
	lua_register(l, "define_static_ship", define_static_ship);
	lua_register(l, "define_missile", define_missile);

	LUA_DEBUG_CHECK(l, 0);

	// load all ship definitions
	namespace fs = FileSystem;
	for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse);
			!files.Finished(); files.Next()) {
		const fs::FileInfo &info = files.Current();
		if (ends_with(info.GetPath(), ".lua")) {
			const std::string name = info.GetName();
			s_currentShipFile = name.substr(0, name.size()-4);
			pi_lua_dofile(l, info.GetPath());
			s_currentShipFile.clear();
		}
	}

	LUA_DEBUG_END(l, 0);

	lua_close(l);

	if (ShipType::player_ships.empty())
		Error("No playable ships have been defined! The game cannot run.");

	//collect ships that can fit atmospheric shields
	for (std::vector<ShipType::Type>::const_iterator it = ShipType::player_ships.begin();
		it != ShipType::player_ships.end(); ++it) {
		const ShipType &ship = ShipType::types[*it];
		if (ship.equipSlotCapacity[Equip::SLOT_ATMOSHIELD] != 0)
			ShipType::playable_atmospheric_ships.push_back(*it);
	}

	if (ShipType::playable_atmospheric_ships.empty())
		Error("No ships can fit atmospheric shields! The game cannot run.");
}
Exemplo n.º 21
0
// Commit
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionVCXProject::Commit( const BFFIterator & funcStartIter ) const
{
	// required
	AStackString<> projectOutput;
	AStackString<> rootNamespace;
	AStackString<> projectGuid;
	AStackString<> defaultLanguage;
	AStackString<> applicationEnvironment;
	if ( !GetString( funcStartIter, projectOutput,		".ProjectOutput", true ) ||
		 !GetString( funcStartIter, rootNamespace,		".RootNamespace", false ) ||
		 !GetString( funcStartIter, projectGuid,		".ProjectGuid", false ) ||
		 !GetString( funcStartIter, defaultLanguage,	".DefaultLanguage", false ) ||
		 !GetString( funcStartIter, applicationEnvironment,	".ApplicationEnvironment", false ) )
	{
		return false;
	}

	// optional inputs
	Array< AString > inputPaths;
	Array< AString > inputPathsExclude;
	if ( !GetStrings( funcStartIter, inputPaths,		".ProjectInputPaths", false ) ||
		 !GetStrings( funcStartIter, inputPathsExclude,	".ProjectInputPathsExclude", false ) )
	{
		return false;
	}

	// project base
	Array< AString > basePaths;
	if ( !GetStrings( funcStartIter, basePaths,	".ProjectBasePath", false ) )
	{
		return false;
	}
	CleanFolderPaths( basePaths );

	// references
	Array< AString > references;
	Array< AString > projectReferences;
	if ( !GetStrings( funcStartIter, references,		".ProjectReferences", false ) ||
		 !GetStrings( funcStartIter, projectReferences,	".ProjectProjectReferences", false ) )
	{
		return false;
	}

	// permitted file extensions
	Array< AString > allowedFileExtensions( 8, true );
	if ( !GetStrings( funcStartIter, allowedFileExtensions, ".ProjectAllowedFileExtensions", false ) )
	{
		return true;
	}
	if ( allowedFileExtensions.IsEmpty() )
	{
		const char * extensions[] = { ".cpp", ".hpp", ".cxx",".hxx",".c",".h",".cc",".hh",
									  ".cp",".hp",".cs",".inl",".bff",".rc",".resx",".m",".mm",
									  ".cu",
									  nullptr };
		AStackString<> tmp;
		const char ** item = extensions;
		while ( *item )
		{
			tmp.Assign( *item );
			allowedFileExtensions.Append( tmp );
			++item;
		}
	}

	// files and filesToExclude
	Array< AString > files( 8, true );
	Array< AString > filesToExclude( 8, true );	
	if ( !GetStrings( funcStartIter, files,				".ProjectFiles", false ) ||
 		 !GetStrings( funcStartIter, filesToExclude,	".ProjectFilesToExclude", false ) )
	{
		return false;
	}

	// filetypes
	Array< VSProjectFileType > fileTypes;
	const BFFVariable * projectFileTypes = BFFStackFrame::GetVar( ".ProjectFileTypes" );
	if ( projectFileTypes )
	{
		if ( projectFileTypes->IsArrayOfStructs() == false )
		{
			Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectFileTypes", projectFileTypes->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
			return false;
		}

		const Array< const BFFVariable * > & structs = projectFileTypes->GetArrayOfStructs();
		const BFFVariable * const * end = structs.End();
		for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
		{
			const BFFVariable * s = *it;

			VSProjectFileType ft;

			// .FileType must be provided
			if ( !GetStringFromStruct( s, ".FileType",	ft.m_FileType ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".FileType" ) );
				return false;
			}

			// .Pattern must be provided
			if ( !GetStringFromStruct( s, ".Pattern",	ft.m_Pattern ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Pattern" ) );
				return false;
			}

			fileTypes.Append( ft );
		}
	}

	// path cleaning
	CleanFolderPaths( inputPaths );			// input paths
	CleanFolderPaths( inputPathsExclude );	// exclude paths
	CleanFilePaths( files );				// explicit files

	// per-config options
	VSProjectConfig baseConfig;

	// various options
	if ( !GetString( funcStartIter, baseConfig.m_BuildCommand,	".ProjectBuildCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_RebuildCommand,".ProjectRebuildCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_CleanCommand,	".ProjectCleanCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_Output,		".Output", false ) ||
		 !GetString( funcStartIter, baseConfig.m_PreprocessorDefinitions,	".PreprocessorDefinitions", false ) ||
		 !GetString( funcStartIter, baseConfig.m_IncludeSearchPath,		".IncludeSearchPath", false ) ||
		 !GetString( funcStartIter, baseConfig.m_ForcedIncludes,		".ForcedIncludes", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AssemblySearchPath,	".AssemblySearchPath", false ) ||
		 !GetString( funcStartIter, baseConfig.m_ForcedUsingAssemblies,	".ForcedUsingAssemblies", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AdditionalOptions,		".AdditionalOptions", false ) ||
		 !GetString( funcStartIter, baseConfig.m_OutputDirectory,		".OutputDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_IntermediateDirectory,	".IntermediateDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_Xbox360DebuggerCommand,".Xbox360DebuggerCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LayoutDir,				".LayoutDir", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LayoutExtensionFilter,	".LayoutExtensionFilter", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DebuggerFlavor,		".DebuggerFlavor", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AumidOverride,			".AumidOverride", false ) ||
		 !GetString( funcStartIter, baseConfig.m_PlatformToolset,		".PlatformToolset", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DeploymentType,		".DeploymentType", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DeploymentFiles,		".DeploymentFiles", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerCommandArguments,	".LocalDebuggerCommandArguments", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerWorkingDirectory,	".LocalDebuggerWorkingDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerCommand,			".LocalDebuggerCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerEnvironment,		".LocalDebuggerEnvironment", false ) )
	{
		return false;
	}

	// create configs
	Array< VSProjectConfig > configs( 16, true );

	const BFFVariable * projectConfigs = BFFStackFrame::GetVar( ".ProjectConfigs" );
	if ( projectConfigs )
	{
		if ( projectConfigs->IsArrayOfStructs() == false )
		{
			Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectConfigs", projectConfigs->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
			return false;
		}

		const Array< const BFFVariable * > & structs = projectConfigs->GetArrayOfStructs();
		const BFFVariable * const * end = structs.End();
		for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
		{
			const BFFVariable * s = *it;

			// start with the base configuration
			VSProjectConfig newConfig( baseConfig );

			// .Platform must be provided
			if ( !GetStringFromStruct( s, ".Platform",	newConfig.m_Platform ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Platform" ) );
				return false;
			}

			// .Config must be provided
			if ( !GetStringFromStruct( s, ".Config",	newConfig.m_Config ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Config" ) );
				return false;
			}

			GetStringFromStruct( s, ".ProjectBuildCommand",		newConfig.m_BuildCommand );
			GetStringFromStruct( s, ".ProjectRebuildCommand",	newConfig.m_RebuildCommand );
			GetStringFromStruct( s, ".ProjectCleanCommand",		newConfig.m_CleanCommand );
			GetStringFromStruct( s, ".Output",					newConfig.m_Output );
			GetStringFromStruct( s, ".PreprocessorDefinitions",	newConfig.m_PreprocessorDefinitions );
			GetStringFromStruct( s, ".IncludeSearchPath",		newConfig.m_IncludeSearchPath );
			GetStringFromStruct( s, ".ForcedIncludes",			newConfig.m_ForcedIncludes );
			GetStringFromStruct( s, ".AssemblySearchPath",		newConfig.m_AssemblySearchPath );
			GetStringFromStruct( s, ".ForcedUsingAssemblies",	newConfig.m_ForcedUsingAssemblies );
			GetStringFromStruct( s, ".AdditionalOptions",		newConfig.m_AdditionalOptions );
			GetStringFromStruct( s, ".OutputDirectory",			newConfig.m_OutputDirectory );
			GetStringFromStruct( s, ".IntermediateDirectory",	newConfig.m_IntermediateDirectory );
		 	GetStringFromStruct( s, ".LayoutDir",				newConfig.m_LayoutDir );
			GetStringFromStruct( s, ".LayoutExtensionFilter",	newConfig.m_LayoutExtensionFilter );
			GetStringFromStruct( s, ".Xbox360DebuggerCommand",	newConfig.m_Xbox360DebuggerCommand );
			GetStringFromStruct( s, ".DebuggerFlavor",			newConfig.m_DebuggerFlavor );
			GetStringFromStruct( s, ".AumidOverride",			newConfig.m_AumidOverride );
			GetStringFromStruct( s, ".PlatformToolset",			newConfig.m_PlatformToolset );
			GetStringFromStruct( s, ".DeploymentType",			newConfig.m_DeploymentType );
			GetStringFromStruct( s, ".DeploymentFiles",			newConfig.m_DeploymentFiles );
			GetStringFromStruct( s, ".LocalDebuggerCommandArguments",	newConfig.m_LocalDebuggerCommandArguments );
			GetStringFromStruct( s, ".LocalDebuggerWorkingDirectory",	newConfig.m_LocalDebuggerWorkingDirectory );
			GetStringFromStruct( s, ".LocalDebuggerCommand",			newConfig.m_LocalDebuggerCommand );
			GetStringFromStruct( s, ".LocalDebuggerEnvironment",		newConfig.m_LocalDebuggerEnvironment );

			configs.Append( newConfig );
		}
	}
	else
	{
		// no user specified configs, make some defaults

		// start from the default
		VSProjectConfig config( baseConfig );

		// make the configs
		config.m_Platform	= "Win32";
		config.m_Config		= "Debug";
		configs.Append( config );
		config.m_Config		= "Release";
		configs.Append( config );
		config.m_Platform	= "x64";
		configs.Append( config );
		config.m_Config		= "Debug";
		configs.Append( config );
	}

	NodeGraph & ng = FBuild::Get().GetDependencyGraph();

	// create all of the DirectoryListNodes we need
	Dependencies dirNodes( inputPaths.GetSize() );
	if ( !GetDirectoryListNodeList( funcStartIter, inputPaths, Array< AString >(), Array< AString >(), true, nullptr, "ProjectInputPaths", dirNodes ) )
	{
		return false; // GetDirectoryListNodeList will have emitted an error
	}

	// Check for existing node
	if ( ng.FindNode( projectOutput ) )
	{
		Error::Error_1100_AlreadyDefined( funcStartIter, this, projectOutput );
		return false;
	}

	VCXProjectNode * pn = ng.CreateVCXProjectNode( projectOutput,
												   basePaths,
												   dirNodes,
												   inputPathsExclude, // TODO:B Remove this (handled by DirectoryListNode now)
												   allowedFileExtensions, // TODO:B Remove this (handled by DirectoryListNode now)
												   files,
												   filesToExclude,
												   rootNamespace,
												   projectGuid,
												   defaultLanguage,
												   applicationEnvironment,
												   configs,
												   fileTypes,
												   references,
												   projectReferences );

	ASSERT( pn );

	return ProcessAlias( funcStartIter, pn );
}
Exemplo n.º 22
0
// -----------------------------------------------------------------------------
// Reads pod format data from a MemChunk
// Returns true if successful, false otherwise
// -----------------------------------------------------------------------------
bool PodArchive::open(MemChunk& mc)
{
	// Check data was given
	if (!mc.hasData())
		return false;

	// Read no. of files
	mc.seek(0, 0);
	uint32_t num_files;
	mc.read(&num_files, 4);

	// Read id
	mc.read(id_, 80);

	// Read directory
	vector<FileEntry> files(num_files);
	mc.read(files.data(), num_files * sizeof(FileEntry));

	// Stop announcements (don't want to be announcing modification due to entries being added etc)
	setMuted(true);

	// Create entries
	UI::setSplashProgressMessage("Reading pod archive data");
	for (unsigned a = 0; a < num_files; a++)
	{
		// Get the entry name as a wxFileName (so we can break it up)
		wxFileName fn(files[a].name);

		// Create entry
		auto new_entry              = std::make_shared<ArchiveEntry>(fn.GetFullName(), files[a].size);
		new_entry->exProp("Offset") = files[a].offset;
		new_entry->setLoaded(false);

		// Add entry and directory to directory tree
		string path = fn.GetPath(false);
		auto   ndir = createDir(path);
		ndir->addEntry(new_entry);

		new_entry->setState(ArchiveEntry::State::Unmodified);

		LOG_MESSAGE(5, "File size: %d, offset: %d, name: %s", files[a].size, files[a].offset, files[a].name);
	}

	// Detect entry types
	vector<ArchiveEntry*> all_entries;
	putEntryTreeAsList(all_entries);
	UI::setSplashProgressMessage("Detecting entry types");
	for (unsigned a = 0; a < all_entries.size(); a++)
	{
		// Skip dir/marker
		if (all_entries[a]->size() == 0 || all_entries[a]->type() == EntryType::folderType())
		{
			all_entries[a]->setState(ArchiveEntry::State::Unmodified);
			continue;
		}

		// Update splash window progress
		UI::setSplashProgress((float)a / (float)all_entries.size());

		// Read data
		MemChunk edata;
		mc.exportMemChunk(edata, all_entries[a]->exProp("Offset").intValue(), all_entries[a]->size());
		all_entries[a]->importMemChunk(edata);

		// Detect entry type
		EntryType::detectEntryType(all_entries[a]);

		// Unload entry data if needed
		if (!archive_load_data)
			all_entries[a]->unloadData();

		// Set entry to unchanged
		all_entries[a]->setState(ArchiveEntry::State::Unmodified);
		LOG_MESSAGE(5, "entry %s size %d", CHR(all_entries[a]->name()), all_entries[a]->size());
	}

	// Setup variables
	setMuted(false);
	setModified(false);
	announce("opened");

	UI::setSplashProgressMessage("");

	return true;
}
Exemplo n.º 23
0
int main()
{
	std::cout << "Initializing MCMCAlgorithm object---------------" << std::endl;
	int samples = 200;
	int thinning = 10;
	int useSamples = 100;
	std::cout << "\t# Samples: " << samples << "\n";
	std::cout << "\tThinning: " << thinning << "\n";
	std::cout << "\t# Samples used: " << useSamples << "\n";
	MCMCAlgorithm mcmc = MCMCAlgorithm(samples, thinning, 100, false, true, true);
	mcmc.setRestartFileSettings(std::string("test"), 100, true);

	//mcmc.setRestartFileSettings("RestartFile.txt", 20, true);
	std::cout << "Done!-------------------------------\n\n\n";


	std::cout << "initialize Genome object--------------------------" << std::endl;
	bool withPhi = false;

	Genome genome;
	genome.readFasta("/home/clandere/CodonUsageBias/RibosomeModel/RibModelDev/data/twoMixtures/simulatedMutationSharedR.fasta");
	//genome.readFasta("F:/GitHub/RibModelDev/data/twoMixtures/simulatedAllUniqueR.fasta");
	//genome.readFasta("E:/RibosomeModel/RibModelDev/data/twoMixtures/simulatedAllUniqueR_unevenMixtures.fasta");
	if(withPhi)
	{
		genome.readObservedPhiValues("F:/GitHub/RibModelDev/data/twoMixtures/simulatedAllUniqueR_phi_withPhiSet.csv", false);
		//genome.readObservedPhiValues("E:/RibosomeModel/RibModelDev/data/twoMixtures/simulatedAllUniqueR_phi_unevenMixtures.csv", false);
	}

	std::cout << "Done!-------------------------------\n\n\n";
	std::cout << "Initializing shared parameter variables---------------\n";

	std::cout << "Done!-------------------------------\n\n\n";
	std::cout << "Initializing shared parameter variables---------------\n";
	std::vector<unsigned> geneAssignment(genome.getGenomeSize());

	unsigned numMixtures = 2;
	std::vector<double> sphi_init(numMixtures, 1);

	/* For 2 mixture */
	for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
	{
		geneAssignment[i] = ( ((double)rand() / (double)RAND_MAX) < 0.5 ? 0u : 1u );

	}
	std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
	std::cout << "Done!------------------------\n\n\n";

	std::cout << "initialize ROCParameter object" << std::endl;
	std::string mixDef = ROCParameter::mutationShared;
	ROCParameter parameter(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

	for (unsigned i = 0u; i < numMixtures; i++)
	{
		unsigned selectionCategry = parameter.getSelectionCategory(i);
		std::cout << "Sphi_init for selection category " << selectionCategry << ": " << sphi_init[selectionCategry] << std::endl;
	}
	std::cout << "\t# mixtures: " << numMixtures << "\n";
	std::cout << "\tmixture definition: " << mixDef << "\n";

	std::vector<std::string> files(1);
	//files[0] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_mutation0.csv");
	//files[1] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_mutation1.csv");
	files[0] = std::string("/home/clandere/CodonUsageBias/RibosomeModel/RibModelDev/data/twoMixtures/simulated_mutation0.csv");
	//files[1] = std::string("/home/clandere/CodonUsageBias/RibosomeModel/RibModelDev/data/twoMixtures/simulated_mutation1.csv");
	parameter.initMutationCategories(files, parameter.getNumMutationCategories());
	files.resize(2);
	//files[0] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_selection0.csv");
	//files[1] = std::string("F:/GitHub/RibModelDev/data/twoMixtures/simulated_selection1.csv");
	files[0] = std::string("/home/clandere/CodonUsageBias/RibosomeModel/RibModelDev/data/twoMixtures/simulated_selection0.csv");
	files[1] = std::string("/home/clandere/CodonUsageBias/RibosomeModel/RibModelDev/data/twoMixtures/simulated_selection1.csv");
	parameter.initSelectionCategories(files, parameter.getNumSelectionCategories());

	parameter.InitializeSynthesisRate(genome, sphi_init[0]);
	//std::vector<double> phiVals = parameter.readPhiValues("/home/clandere/CodonUsageBias/RibosomeModel/RibModelFramework/ribModel/data/Skluyveri_ChrA_ChrCleft_phi_est.csv");
	//parameter.InitializeSynthesisRate(phiVals);
	std::cout << "done initialize ROCParameter object" << std::endl;


	std::cout << "Initializing ROCModel object\n";

	ROCModel model(withPhi);
	model.setParameter(parameter);


	std::cout << "starting MCMC for ROC" << std::endl;
	mcmc.run(genome, model, 1, 0);
	std::cout << std::endl << "Finished MCMC for ROC" << std::endl;
	double temp[] = { 0.025, 0.5, 0.975 };
	std::vector<double> probs(temp, temp + sizeof(temp) / sizeof(double));
	//std::vector<double> quants = parameter.getCodonSpecificQuantile(1, 100, std::string("GCA"), 0, probs, true);

	std::string codon = std::string("TTT");
	double a = parameter.getCodonSpecificPosteriorMean(0u, 50u, codon, 0u, true);
	double b = parameter.getCodonSpecificPosteriorMean(0u, 50u, codon, 1u, true);
	double c = parameter.getCodonSpecificPosteriorMean(1u, 50u, codon, 0u, true);
	double d = parameter.getCodonSpecificPosteriorMean(1u, 50u, codon, 1u, true);

	std::cout << std::endl << "Exiting" << std::endl;
}
Exemplo n.º 24
0
string getDBStructure()
{
	return "----------------------------------------------------------------------\n\
--\n\
--	MOPSLinux package system\n\
--	Database creation script\n\
--	$Id: dbstruct.cpp,v 1.3 2007/11/02 20:19:45 i27249 Exp $\n\
--\n\
----------------------------------------------------------------------\n\
\n\
create table packages (\n\
	package_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	package_name TEXT NOT NULL,\n\
	package_version TEXT NOT NULL,\n\
	package_arch TEXT NOT NULL,\n\
	package_build TEXT NULL,\n\
	package_compressed_size TEXT NOT NULL,\n\
	package_installed_size TEXT NOT NULL,\n\
	package_short_description TEXT NULL,\n\
	package_description TEXT NULL, \n\
	package_changelog TEXT NULL,\n\
	package_packager TEXT NULL,\n\
	package_packager_email TEXT NULL,\n\
	package_installed INTEGER NOT NULL,\n\
	package_configexist INTEGER NOT NULL,\n\
	package_action INTEGER NOT NULL,\n\
	package_md5 TEXT NOT NULL,\n\
	package_filename TEXT NOT NULL,\n\
	package_betarelease TEXT NOT NULL,\n\
	package_installed_by_dependency INTEGER NOT NULL DEFAULT '0',\n\
	package_type INTEGER NOT NULL DEFAULT '0'\n\
);\n\
create index ppname on packages (package_id, package_name, package_version, package_action, package_installed, package_md5);\n\
\n\
create table files (\n\
	file_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	file_name TEXT NOT NULL,\n\
	file_type INTEGER NOT NULL,\n\
	packages_package_id INTEGER NOT NULL\n\
);\n\
create index pname on files (file_name, packages_package_id);\n\
\n\
create table conflicts (\n\
	conflict_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	conflict_file_name TEXT NOT NULL,\n\
	backup_file TEXT NOT NULL,\n\
	conflicted_package_id INTEGER NOT NULL\n\
);\n\
\n\
create table locations (\n\
	location_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	packages_package_id INTEGER NOT NULL,\n\
	server_url TEXT NOT NULL,\n\
	location_path TEXT NOT NULL\n\
);\n\
create index locpid on locations(packages_package_id, location_path, server_url);\n\
create table tags (\n\
	tags_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	tags_name TEXT NOT NULL\n\
);\n\
create index ptag on tags (tags_id, tags_name);\n\
\n\
create table tags_links (\n\
	tags_link_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	packages_package_id INTEGER NOT NULL,\n\
	tags_tag_id INTEGER NOT NULL\n\
);\n\
create index ptaglink on tags_links (packages_package_id, tags_tag_id);\n\
\n\
create table dependencies (\n\
	dependency_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
	packages_package_id INTEGER NOT NULL,\n\
	dependency_condition INTEGER NOT NULL DEFAULT '1',\n\
	dependency_type INTEGER NOT NULL DEFAULT '1',\n\
	dependency_package_name TEXT NOT NULL,\n\
	dependency_package_version TEXT NULL,\n\
	dependency_build_only INTEGER NOT NULL DEFAULT '0' \
);\n\
\n\
create index pdeps on dependencies (packages_package_id, dependency_id, dependency_package_name, dependency_package_version, dependency_condition);\n\
\n\
-- INTERNATIONAL SUPPORT\n\
\n\
--create table descriptions (\n\
--	description_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
--	packages_package_id INTEGER NOT NULL,\n\
--	description_language TEXT NOT NULL,\n\
--	description_text TEXT NOT NULL,\n\
--	short_description_text TEXT NOT NULL\n\
--);\n\
\n\
--create table changelogs (\n\
--	changelog_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
--	packages_package_id INTEGER NOT NULL,\n\
--	changelog_language TEXT NOT NULL,\n\
--	changelog_text TEXT NOT NULL\n\
--);\n\
\n\
-- RATING SYSTEM - SUPPORT FOR FUTURE\n\
--create table ratings (\n\
--	rating_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n\
--	rating_value INTEGER NOT NULL,\n\
--	packages_package_name TEXT NOT NULL\n\
--);\n\
";
}
Exemplo n.º 25
0
bool MainComponent::perform (const juce::ApplicationCommandTarget::InvocationInfo& info)
{
    CodeFileList codeFilesToEdit;

    {
        juce::StringArray files (codeFiles.getSelectedCodeFiles());

        if (files.size() <= 0)
        {
            const juce::Array<juce::File>& list (codeFiles.getCodeFiles().getFiles());

            for (int i = 0; i < list.size(); ++i)
                files.addIfNotAlreadyThere (list.getUnchecked (i).getFullPathName());
        }

        codeFilesToEdit.addFiles (files);
    }

    switch (info.commandID)
    {
        case CommandIDs::ProjectNew:
        {
        }
        break;

        case CommandIDs::ProjectOpen:
        {
        }
        break;

        case CommandIDs::ProjectSave:
        {
        }
        break;

        case CommandIDs::ProjectSaveAs:
        {
        }
        break;

        case CommandIDs::ProjectClose:
        {
        }
        break;

        case CommandIDs::OpenFiles:
        {
        }
        break;

        case CommandIDs::OpenIntrojucerProject:
        {
        }
        break;

        case CommandIDs::Exit:
        {
        }
        break;

        case CommandIDs::EditUndo:
        {
            undoManager.undo();
        }
        break;

        case CommandIDs::EditRedo:
        {
            undoManager.redo();
        }
        break;

        case CommandIDs::FilesCapitaliseStringLiterals:
        {
        }
        break;

        case CommandIDs::FilesCleanTrailingWhitespace:
        {
            TrailingWhitespaceCleaner (codeFilesToEdit)
                .perform (UserSettings::getInstance()->getBool ("RemoveDocumentStartWhitespace"),
                          (TrailingWhitespaceCleaner::WhitespaceRemovalOptions) UserSettings::getInstance()->getInt ("RemoveDocumentStartWhitespace",
                                                                                (int) TrailingWhitespaceCleaner::RemoveAll));
        }
        break;

        case CommandIDs::FilesConvertLineEndings:
        {
        }
        break;

        case CommandIDs::FilesConvertTabsToSpaces:
        {
        }
        break;

        case CommandIDs::FilesModularise:
        {
        }
        break;

        case CommandIDs::ShowSettings:
        {
            BasicWindow* doc = new BasicWindow (TRANS ("Settings"), juce::Colours::darkgrey, juce::DocumentWindow::closeButton);

            doc->setResizable (false, false);
            doc->setUsingNativeTitleBar (true);

            ConfigurationWindow* cw = new ConfigurationWindow();
            doc->setContentOwned (cw, true);
            doc->centreWithSize (cw->getWidth(), cw->getHeight());

            doc->setVisible (true);
        }
        break;

        default:
            jassertfalse;
            return false;
        break;
    };

    return true;
}
Exemplo n.º 26
0
void IndexReader::main(Collection<String> args) {
    String filename;
    bool extract = false;

    for (Collection<String>::iterator arg = args.begin(); arg != args.end(); ++arg) {
        if (*arg == L"-extract") {
            extract = true;
        } else if (filename.empty()) {
            filename = *arg;
        }
    }

    if (filename.empty()) {
        std::wcout << L"Usage: IndexReader [-extract] <cfsfile>";
        return;
    }

    DirectoryPtr dir;
    CompoundFileReaderPtr cfr;

    LuceneException finally;
    try {
        String dirname(FileUtils::extractPath(filename));
        filename = FileUtils::extractPath(filename);
        dir = FSDirectory::open(dirname);
        cfr = newLucene<CompoundFileReader>(dir, filename);

        HashSet<String> _files(cfr->listAll());
        Collection<String> files(Collection<String>::newInstance(_files.begin(), _files.end()));
        std::sort(files.begin(), files.end()); // sort the array of filename so that the output is more readable

        for (Collection<String>::iterator file = files.begin(); file != files.end(); ++file) {
            int64_t len = cfr->fileLength(*file);

            if (extract) {
                std::wcout << L"extract " << *file << L" with " << len << L" bytes to local directory...";
                IndexInputPtr ii(cfr->openInput(*file));

                boost::filesystem::ofstream f(*file, std::ios::binary | std::ios::out);

                // read and write with a small buffer, which is more effective than reading byte by byte
                ByteArray buffer(ByteArray::newInstance(1024));

                int32_t chunk = buffer.size();
                while (len > 0) {
                    int32_t bufLen = std::min(chunk, (int32_t)len);
                    ii->readBytes(buffer.get(), 0, bufLen);
                    f.write((char*)buffer.get(), bufLen);
                    len -= bufLen;
                }
                ii->close();
            } else {
                std::wcout << *file << L": " << len << " bytes\n";
            }
        }
    } catch (LuceneException& e) {
        finally = e;
    }

    if (dir) {
        dir->close();
    }
    if (cfr) {
        cfr->close();
    }

    finally.throwException();
}
Exemplo n.º 27
0
bool cAlarmServer::loadAlarms()
{
   // load global alarm config from alarm-config.xml
   UtlString strAlarmFilename = SipXecsService::Path(SipXecsService::ConfigurationDirType,
         "alarm-config.xml");
   UtlString strGroupFilename = SipXecsService::Path(SipXecsService::ConfigurationDirType,
         "alarm-groups.xml");
   loadAlarmConfig(strAlarmFilename, strGroupFilename);

   // load specific alarm definitions from ${confdir}/alarms/*.xml
   UtlString alarmDefDir = SipXecsService::Path(SipXecsService::ConfigurationDirType);
   alarmDefDir.append("/alarms/");
   OsSysLog::add(FAC_ALARM, PRI_INFO, "Looking for alarm def files in '%s'", alarmDefDir.data());
   OsFileIterator files(alarmDefDir);
   OsPath entry;

   // for each file in the ${confdir}/alarms, load alarm definitions
   OsStatus status;
   int numFound;
   for (status=files.findFirst(entry, ".*\\.xml$", OsFileIterator::FILES), numFound=0;
        status == OS_SUCCESS;
        status = files.findNext(entry) )
   {
      loadAlarmDefinitions(alarmDefDir + entry);
   }

   // load alarm strings and local language version from ${datadir}/alarms/*.xml
   UtlString alarmStringsDir = SipXecsService::Path(SipXecsService::DataDirType);
   alarmStringsDir.append("/alarms/");
   OsSysLog::add(FAC_ALARM, PRI_INFO, "Looking for alarm string files in '%s'",
                 alarmStringsDir.data());
   OsFileIterator stringFiles(alarmStringsDir);

   // for each "base" file (*-strings.xml) in the ${datadir}/alarms, load alarm strings
   for (status=stringFiles.findFirst(entry, ".*-strings\\.xml$", OsFileIterator::FILES), numFound=0;
        status == OS_SUCCESS;
        status = stringFiles.findNext(entry) )
   {
      loadAlarmStrings(alarmStringsDir + entry);
   }


#ifdef DEBUG
   UtlHashMapIterator alarmIter(mAlarmMap);
   UtlString* alarmKey;
   int count=0;
   while ((alarmKey = dynamic_cast<UtlString*>(alarmIter())))
   {
      cAlarmData* alarm = dynamic_cast<cAlarmData*>(alarmIter.value());
      OsSysLog::add(FAC_ALARM, PRI_DEBUG,
            "alarm[%d]: %s %s: %s, Log:%d, Email:%d",
            count, alarmKey->data(), alarm->getCode().data(),
            OsSysLog::priorityName(alarm->getSeverity()),
            alarm->actions[cAlarmData::eActionLog], alarm->actions[cAlarmData::eActionEmail]);
      OsSysLog::add(FAC_ALARM, PRI_DEBUG,
            "           Title:%s", alarm->getShortTitle().data());
      OsSysLog::add(FAC_ALARM, PRI_DEBUG,
            "           Description:%s", alarm->getDescription().data());
      OsSysLog::add(FAC_ALARM, PRI_DEBUG,
            "           Resolution:%s", alarm->getResolution().data());
      count++;
   }
#endif

   return true;
}
Exemplo n.º 28
0
// DoBuild
//------------------------------------------------------------------------------
/*virtual*/ Node::BuildResult DirectoryListNode::DoBuild( Job * UNUSED( job ) )
{
	// NOTE: The DirectoryListNode makes no assumptions about whether no files
	// is an error or not.  That's up to the dependent nodes to decide.

	Array< FileIO::FileInfo > files( 4096, true );
	FileIO::GetFilesEx( m_Path, &m_Patterns, m_Recursive, &files );

	m_Files.SetCapacity( files.GetSize() );

	// filter exclusions
	const FileIO::FileInfo * const end = files.End();
	for ( const FileIO::FileInfo * it = files.Begin(); it != end; it++ )
	{
		bool excluded = false;
        
		// filter excluded paths
		const AString * const eEnd = m_ExcludePaths.End();
		for ( const AString * eIt=m_ExcludePaths.Begin(); eIt != eEnd; ++eIt )
		{
			if ( PathUtils::PathBeginsWith( it->m_Name, *eIt ) )
			{
				excluded = true;
				break;
			}
		}

        // filter excluded files
		if ( !excluded )
		{
	        const AString * fit = m_FilesToExclude.Begin();
	        const AString * const fend = m_FilesToExclude.End();
	        for ( ; fit != fend; ++fit )
	        {
				if ( PathUtils::PathEndsWithFile( it->m_Name, *fit ) )
	            {
	                excluded = true;
	                break;
	            }
	        }
		}

		if ( !excluded )
		{
			m_Files.Append( *it );
		}
	}

	if ( FLog::ShowInfo() )
	{
		const size_t numFiles = m_Files.GetSize();
		FLOG_INFO( "Dir: '%s' (found %u files)\n", 
							m_Name.Get(), 
							(uint32_t)numFiles);
		for ( size_t i=0; i<numFiles; ++i )
		{
			FLOG_INFO( " - %s\n", m_Files[ i ].m_Name.Get() );
		}
	}

	return NODE_RESULT_OK;
}
Exemplo n.º 29
0
/// This is where the link is actually performed.
bool Driver::link(const TargetInfo &targetInfo) {
  // Honor -mllvm
  if (!targetInfo.llvmOptions().empty()) {
    unsigned numArgs = targetInfo.llvmOptions().size();
    const char **args = new const char*[numArgs + 2];
    args[0] = "lld (LLVM option parsing)";
    for (unsigned i = 0; i != numArgs; ++i)
      args[i + 1] = targetInfo.llvmOptions()[i];
    args[numArgs + 1] = 0;
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
  }

  // Read inputs
  ScopedTask readTask(getDefaultDomain(), "Read Args");
  std::vector<std::vector<std::unique_ptr<File>>> files(
      targetInfo.inputFiles().size());
  size_t index = 0;
  std::atomic<bool> fail(false);
  TaskGroup tg;
  for (const auto &input : targetInfo.inputFiles()) {
    if (targetInfo.logInputFiles())
      llvm::outs() << input.getPath() << "\n";

    tg.spawn([ &, index]{
      if (error_code ec = targetInfo.readFile(input.getPath(), files[index])) {
        llvm::errs() << "Failed to read file: " << input.getPath() << ": "
                     << ec.message() << "\n";
        fail = true;
        return;
      }
    });
    ++index;
  }
  tg.sync();
  readTask.end();

  if (fail)
    return true;

  InputFiles inputs;
  for (auto &f : files)
    inputs.appendFiles(f);

  // Give target a chance to add files.
  targetInfo.addImplicitFiles(inputs);

  // assign an ordinal to each file so sort() can preserve command line order
  inputs.assignFileOrdinals();

  // Do core linking.
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
  Resolver resolver(targetInfo, inputs);
  if (resolver.resolve()) {
    if (!targetInfo.allowRemainingUndefines())
      return true;
  }
  MutableFile &merged = resolver.resultFile();
  resolveTask.end();

  // Run passes on linked atoms.
  ScopedTask passTask(getDefaultDomain(), "Passes");
  PassManager pm;
  targetInfo.addPasses(pm);
  pm.runOnFile(merged);
  passTask.end();

  // Give linked atoms to Writer to generate output file.
  ScopedTask writeTask(getDefaultDomain(), "Write");
  if (error_code ec = targetInfo.writeFile(merged)) {
    llvm::errs() << "Failed to write file '" << targetInfo.outputPath()
                 << "': " << ec.message() << "\n";
    return true;
  }

  return false;
}
Exemplo n.º 30
0
DWORD
ParseArgs(int argc, char* argv[])

// This function parses arguments given to the client application
//
// argc : The number of arguments
// argv : The array pointing to the arguments
{
    try {

        po::options_description certtoolArgs("");

        po::options_description desc("certool general command options");
        po::options_description config("configuration file format ( for example see : certool.cfg )");
        po::options_description init("CA server initialization functions");
        po::options_description functions("14 managment functions");
        po::options_description files("certificate data files");
        po::options_description params("additional params");

        AddGeneralOptions(desc);
        AddConfigOptions(config);
        AddInitOptions(init);
        AddFunctionsOptions(functions);
        AddFilesOptions(files);
        AddParamOptions(params);

        certtoolArgs.
        add(desc).
        add(config).
        add(init).
        add(functions).
        add(files).
        add(params);

        po::store(po::parse_command_line(argc, argv, certtoolArgs), argsMap);
        po::notify(argsMap);

        if (argsMap.count("help") || argc == 1) {

            if (argHelpModule.compare("init") == 0) {
                std::cout << init << "\n";
                return ERROR_SUCCESS;
            }

            if (argHelpModule.compare("functions") == 0) {
                std::cout << functions << "\n";
                return ERROR_SUCCESS;
            }

            if (argHelpModule.compare("config") == 0) {
                std::cout << config << "\n";
                return ERROR_SUCCESS;
            }

            if (argHelpModule.compare("files") == 0) {
                std::cout << files << "\n";
                return ERROR_SUCCESS;
            }

            std::cout << desc << "\n";
            return ERROR_SUCCESS;
        }
        return DispatchCmd(argsMap, config);

    }
    catch (std::bad_alloc& e)
    {
        std::cerr << "error - Allocation failed -" << e.what() << std::endl;
        return VMCA_OUT_MEMORY_ERR;
    }
    catch (std::exception& e)
    {
        std::cerr << "error: " << e.what() << "\n";
        return VMCA_UNKNOW_ERROR;
    } catch(...)
    {
        std::cerr << "Exception of unknown type!\n";
        return VMCA_UNKNOW_ERROR;
    }

}