int main ()
{
	Stock st1( "Company A", 5.12 );
	Stock st2( "Company B", 7.13 );
	Stock st3( "Company C", 50.00 );

	StockLogger logger( std::cout );
	st1.addChangeListener( logger );
	st2.addChangeListener( logger );

	BiggestChangeRecorder recorder;
	st1.addChangeListener( recorder );
	st2.addChangeListener( recorder );

	StockChangeImportanceFilter filteredLogger( 10.00, logger );
	StockChangeImportanceFilter filteredRecorder( 20.00, recorder );
	st3.addChangeListener( filteredLogger );
	st3.addChangeListener( filteredRecorder );

	st1.updatePrice( 6.21 );
	st2.updatePrice( 7.09 );
	st1.updatePrice( 6.01 );
	st3.updatePrice( 55.00 );
	st3.updatePrice( 44.00 );

	std::cout << "Biggest positive change : "
		<< recorder.getMaxPositiveChange ()
		<< std::endl;

	std::cout << "Biggest negative change : "
		<< recorder.getMaxNegativeChange ()
		<< std::endl;
}
Example #2
0
TEST(BaseCluster, Read)
{
    std::stringstream input;
    tawara::UIntElement tc(tawara::ids::Timecode, 42);
    tawara::UIntElement st1(tawara::ids::SilentTrackNumber, 1);
    tawara::UIntElement st2(tawara::ids::SilentTrackNumber, 2);
    tawara::UIntElement ps(tawara::ids::PrevSize, 0x1234);

    FakeCluster e;
    std::streamsize body_size(tc.size());
    tawara::vint::write(body_size, input);
    tc.write(input);
    EXPECT_EQ(tawara::vint::size(body_size) + body_size,
            e.read(input));
    EXPECT_EQ(42, e.timecode());
    EXPECT_TRUE(e.silent_tracks().empty());
    EXPECT_EQ(0, e.previous_size());

    body_size += tawara::ids::size(tawara::ids::SilentTracks) +
        tawara::vint::size(st1.size() + st2.size()) +
        st1.size() + st2.size() + ps.size();
    tawara::vint::write(body_size, input);
    tc.write(input);
    tawara::ids::write(tawara::ids::SilentTracks, input);
    tawara::vint::write(st1.size() + st2.size(), input);
    st1.write(input);
    st2.write(input);
    ps.write(input);
    EXPECT_EQ(tawara::vint::size(body_size) + body_size,
            e.read(input));
    EXPECT_EQ(42, e.timecode());
    EXPECT_FALSE(e.silent_tracks().empty());
    EXPECT_EQ(0x1234, e.previous_size());

    // Body size value wrong (too small)
    input.str(std::string());
    tawara::vint::write(2, input);
    tc.write(input);
    ps.write(input);
    EXPECT_THROW(e.read(input), tawara::BadBodySize);
    // Invalid child
    input.str(std::string());
    tawara::UIntElement ue(tawara::ids::EBML, 0xFFFF);
    tawara::vint::write(ue.size(), input);
    ue.write(input);
    EXPECT_THROW(e.read(input), tawara::InvalidChildID);
    // Missing timecode
    input.str(std::string());
    tawara::vint::write(ps.size(), input);
    ps.write(input);
    EXPECT_THROW(e.read(input), tawara::MissingChild);
}
Example #3
0
void SAMLTokenTest::TestSAML2Token() {
  Arc::SOAPEnvelope soap1(xml);
  CPPUNIT_ASSERT((bool)soap1);
  Arc::SAMLToken st1(soap1, certfile, keyfile, Arc::SAMLToken::SAML2);
  CPPUNIT_ASSERT((bool)st1);

  std::string str;
  st1.GetXML(str);

  Arc::SOAPEnvelope soap2(str);
  CPPUNIT_ASSERT((bool)soap2);
  Arc::SAMLToken st2(soap2);
  CPPUNIT_ASSERT((bool)st2);
  CPPUNIT_ASSERT(st2.Authenticate());
  CPPUNIT_ASSERT(st2.Authenticate("../../credential/test/ca_cert.pem", ""));
}
Example #4
0
// ============================================================================
// the main execution method 
// ============================================================================
StatusCode GaudiExamples::StatSvcAlg::execute    () 
{
  Stat st1 ( m_stat , "counter1" ) ;
  Stat st2 ( m_stat , "counter2" ) ;
  Stat st3 ( m_stat , "counter3" , 0.3 ) ;
  
  Stat eff ( m_stat , "eff" , 0 < sin( 10 * st1->flag() ) ) ;
  //
  st1 += 0.1     ;
  st1 -= 0.1000452  ;
  st2 += st1 ;
  ++st3 ;
  st2-- ;
  
  eff += 0 < cos ( 20 * st2->flag() ) ;
  
  //
  return StatusCode::SUCCESS ;
}
Example #5
0
		size_t SQLiteBundleSet::Factory::__create(SQLiteDatabase &db, const std::string &name, bool persistent) throw (SQLiteDatabase::SQLiteQueryException)
		{
			// create a new name (fails, if the name already exists)
			SQLiteDatabase::Statement st1(db._database, SQLiteDatabase::_sql_queries[SQLiteDatabase::BUNDLE_SET_NAME_ADD]);
			sqlite3_bind_text(*st1, 1, name.c_str(), static_cast<int>(name.length()), SQLITE_TRANSIENT);
			sqlite3_bind_int(*st1, 2, persistent ? 1 : 0);
			st1.step();

			// get the ID of the name
			SQLiteDatabase::Statement st2(db._database, SQLiteDatabase::_sql_queries[SQLiteDatabase::BUNDLE_SET_NAME_GET_ID]);
			sqlite3_bind_text(*st2, 1, name.c_str(), static_cast<int>(name.length()), SQLITE_TRANSIENT);
			sqlite3_bind_int(*st2, 2, persistent ? 1 : 0);

			if (st2.step() == SQLITE_ROW) {
				return sqlite3_column_int64(*st2, 0);
			}

			throw SQLiteDatabase::SQLiteQueryException("could not create the bundle-set name");
		}
Example #6
0
TEST(BaseCluster, Size)
{
    FakeCluster e;
    tawara::UIntElement tc(tawara::ids::Timecode, 0);
    std::streamsize body_size(tc.size());
    EXPECT_EQ(tawara::ids::size(tawara::ids::Cluster) + 8 + body_size, e.size());

    tawara::UIntElement st1(tawara::ids::SilentTrackNumber, 1);
    tawara::UIntElement st2(tawara::ids::SilentTrackNumber, 2);
    body_size += tawara::ids::size(tawara::ids::SilentTracks) +
        tawara::vint::size(st1.size() + st2.size()) +
        st1.size() + st2.size();
    e.silent_tracks().push_back(tawara::SilentTrackNumber(1));
    e.silent_tracks().push_back(tawara::SilentTrackNumber(2));
    EXPECT_EQ(tawara::ids::size(tawara::ids::Cluster) + 8 + body_size, e.size());

    tawara::UIntElement ps(tawara::ids::PrevSize, 0x1234);
    body_size += ps.size();
    e.previous_size(0x1234);
    EXPECT_EQ(tawara::ids::size(tawara::ids::Cluster) + 8 + body_size, e.size());
}
Example #7
0
TEST(BaseCluster, Write)
{
    std::ostringstream output;
    std::stringstream expected;
    tawara::UIntElement tc(tawara::ids::Timecode, 0);
    tawara::UIntElement st1(tawara::ids::SilentTrackNumber, 1);
    tawara::UIntElement st2(tawara::ids::SilentTrackNumber, 2);
    tawara::UIntElement ps(tawara::ids::PrevSize, 0x1234);

    FakeCluster e;
    std::streamsize expected_size(tc.size());
    tawara::ids::write(tawara::ids::Cluster, expected);
    tawara::vint::write(expected_size, expected, 8);
    tc.write(expected);
    EXPECT_EQ(tawara::ids::size(tawara::ids::Cluster) + 8 + expected_size,
            e.write(output));
    EXPECT_PRED_FORMAT2(test_utils::std_buffers_eq, output.str(),
            expected.str());

    expected_size += tawara::ids::size(tawara::ids::SilentTracks) +
        tawara::vint::size(st1.size() + st2.size()) +
        st1.size() + st2.size() + ps.size();
    e.silent_tracks().push_back(tawara::SilentTrackNumber(1));
    e.silent_tracks().push_back(tawara::SilentTrackNumber(2));
    e.previous_size(0x1234);
    output.str(std::string());
    expected.str(std::string());
    tawara::ids::write(tawara::ids::Cluster, expected);
    tawara::vint::write(expected_size, expected, 8);
    tc.write(expected);
    tawara::ids::write(tawara::ids::SilentTracks, expected);
    tawara::vint::write(st1.size() + st2.size(), expected);
    st1.write(expected);
    st2.write(expected);
    ps.write(expected);
    EXPECT_EQ(tawara::ids::size(tawara::ids::Cluster) + 8 + expected_size,
            e.write(output));
    EXPECT_PRED_FORMAT2(test_utils::std_buffers_eq, output.str(),
            expected.str());
}
Example #8
0
// wyciaga informacje z lini textu z pliku
void ConfFile::parse()
{
	string t;
	while (getline(cFile, t))
	{
		if (t.size() == 0)
			continue;

		istringstream st1(t);
		char c;
		st1 >> c;
		if (c == '#')
			continue;
		int t1 = t.find("=");
		t.replace(t1, 1, " ");
		istringstream st2(t);
		string v;
		string lab;
		st2 >> lab >> v;
		mLabels[lab] = v;
	};
}
Example #9
0
int sc_main(int ac, char *av[])
{
  sc_fifo<int> st1("ST1", 2), st2("ST2", 2);
  sc_fifo<int> a1("A1", 2), a2("A2", 2), a3("A3", 2);
  sc_fifo<int> b1("B1", 2), b2("B2", 2), b3("B3", 2);

  sc_clock clock("CLOCK");

  sawtooth ST("TB1", clock, st1, st2);

  delay D1("D1", clock, st1, a1);
  downsample DN1("DN1", clock, a1, a2);
  upsample UP1("UP1", clock, a2, a3);

  downsample DN2("DN2", clock, st2, b1);
  upsample UP2("UP2", clock, b1, b2);
  delay D2("D2", clock, b2, b3);

  adder A ("A", clock, a3, b3);

  sc_start(100, SC_NS);

  return 0;
}
Example #10
0
void prepare_data(string filename)
{/*{{{*/
    // create defect center
    double x =  0.0, y = 0.0, z = 0.89175;
    vec coord; coord << x << y << z;
    NVCenter nv(NVCenter::N14, coord);
    
    double magBx = 0.0,  magBy =  0.0, magBz = 1e-5;
    nv.set_magB(magBx, magBy, magBz);
    nv.make_espin_hamiltonian();

    cout << nv.get_eigen_state(0) << endl;
    cout << nv.get_eigen_state(1) << endl;

    cSPIN espin=nv.get_espin();
    PureState st0(nv.get_eigen_state(0));
    PureState st1(nv.get_eigen_state(1));
    espin.set_coordinate(coord);
    cout << "espin coordinate = " << espin.get_coordinate() << endl;

    // create bath spins
    cSpinSourceFromFile spin_file(filename);
    cSpinCollection spins(&spin_file);
    spins.make();

    vector<cSPIN> sl = spins.getSpinList();

    cout << sl[0].get_coordinate() << sl[0].get_gamma() << endl;
    cout << sl[1].get_coordinate() << sl[1].get_gamma() << endl;


    vec magB; magB << magBx << magBy << magBz;
    SpinZeemanInteraction zee(sl, magB);
    SpinDipolarInteraction dip(sl);
    DipolarField hf_field0(sl, espin, st0);
    DipolarField hf_field1(sl, espin, st1);

    Hamiltonian hami0(sl);
    hami0.addInteraction(zee);
    hami0.addInteraction(dip);
    hami0.addInteraction(hf_field0);
    hami0.make();

    Hamiltonian hami1(sl);
    hami1.addInteraction(zee);
    hami1.addInteraction(dip);
    hami1.addInteraction(hf_field1);
    hami1.make();


    cout << hami0.getMatrix() << endl;
    cout << hami1.getMatrix() << endl;

    Liouvillian lv0(hami0, SHARP);
    Liouvillian lv1(hami1, FLAT);
    Liouvillian lvH = lv0 - lv1;


    double rate = 2.0*datum::pi*1e4;
    vec axis; axis << 1.0 << 1.0 << 1.0;
    SpinDephasing dephasing(sl, rate, normalise(axis));
    LiouvilleSpaceOperator dephaseOperator(sl);
    dephaseOperator.addInteraction(dephasing);
    dephaseOperator.make();

    QuantumOperator lv = lvH + dephaseOperator;
    lv.saveMatrix("lv");


    vec _bath_polarization = zeros<vec>(3);
    SpinPolarization p(sl, _bath_polarization);
    DensityOperator ds(sl);
    ds.addStateComponent(p);
    ds.make();
    ds.makeVector();
    cout << ds.getVector() << endl;
    cout << ds.getMatrix() << endl;


}/*}}}*/
Example #11
0
//this constructor parses the input to get separated terms and add them to List_Terms
Polynomial::Polynomial(string& poly) 
{	
	//temporary variables to store the term, the coefficient and the exponent
	int expo = 0;
	int coef = 0;
	string coefSt;
	string expoSt;
	string currentTerm;

	// replace - with +-
	ReplaceStringInPlace (poly,string("-"),string("+-"));
	
	// split input by + to get separated terms
	String_Tokenizer st1(poly, "+");

	// continue to parse as long as there is a term
	while (st1.has_more_tokens())
	{
		currentTerm = trim(st1.next_token()); // get current Term

		if (currentTerm.find("x^") != string::npos) // term contains "x^"
		{ 
			string first_Token, second_Token; // variables to store the coefficient and the exponent
			// split currentTerm by x^
			String_Tokenizer st2(currentTerm, "x^");
			first_Token = trim(st2.next_token());
			second_Token = trim(st2.next_token());
			if (currentTerm.find(first_Token) < currentTerm.find("x^") ) // first_Token is the coefficient
			{
				if (first_Token == "-") //special case (user entered "-x^...")
					coefSt = "-1";
				else
					coefSt = first_Token;
				expoSt = second_Token != "" ? second_Token : throw invalid_argument( "Invalid Input" ); // only assign the exponent if second_Token is not empty
			}
			else if (currentTerm.find(first_Token) > currentTerm.find("x^") ) // first_Token is the exponent (the coefficient is hidden with value 1 )
			{
				coefSt = "1"; 
				expoSt = first_Token;
			}
			else throw invalid_argument( "Invalid Input" );
		} 
		else if (currentTerm.find("x") != string::npos) // term contains "x"
		{
			//split currentTerm by x
			String_Tokenizer st2(currentTerm, "x");
			if (!st2.has_more_tokens()) // the term is "x" only
			{
				coefSt = "1";
				expoSt = "1";
			}
			else // the term has a coefficient
			{
				coefSt = trim(st2.next_token());
				if (coefSt == "-") //special case (user entered "-x...")
					coefSt = "-1";
				expoSt = "1";
			}
		}
		else if (currentTerm.find("X") != string::npos) // term contains "X" uppercase
			throw invalid_argument( "Invalid Input" );
		else // term contains only the coefficient
		{
			coefSt = currentTerm;
			expoSt = "0";
		}

		//convert string to int
		coef= stoi(coefSt);
		expo=stoi(expoSt);

		//create the term and add to the list only if the coefficient is not 0
		if (coef != 0)
			List_Terms.push_back(Term(coef,expo));
	}
}
Example #12
0
int		main(void)
{
	FragTrap ft1("Alf");
	FragTrap ft2("Bob");
	FragTrap ft3(ft1);
	std::cout << std::endl;


	ft3 = ft2;
	std::cout << std::endl;

	ft1.rangedAttack("Bob");
	std::cout << std::endl;

	ft1.meleeAttack("Bob");
	std::cout << std::endl;

	ft1.takeDamage(3);
	std::cout << std::endl;

	ft1.beRepaired(3);
	std::cout << std::endl;

	ft1.takeDamage(1000);
	std::cout << std::endl;

	ft1.beRepaired(1000);
	std::cout << std::endl;

	ft1.beRepaired(3);
	std::cout << std::endl;

	ft1.Ep = 100;
	std::cout << std::endl;

	ft1.vaulthunter_dot_exe("1");
	ft1.vaulthunter_dot_exe("2");
	ft1.vaulthunter_dot_exe("3");
	ft1.vaulthunter_dot_exe("4");
	ft1.vaulthunter_dot_exe("5");
	std::cout << std::endl;

	ScavTrap st1("John");
    ScavTrap st2("Ben");
    ScavTrap st3;
	std::cout << std::endl;

    st1.meleeAttack("bob");
    st1.rangedAttack("Alf");
	std::cout << std::endl;

    st2.takeDamage(45);
    st2.beRepaired(21);
	std::cout << std::endl;

    st3.challengeNewcomer();
    st3.challengeNewcomer();
	std::cout << std::endl;

	return (0);
}
Example #13
0
int main(int argc, char *argv[])
{
  {
    std::string s = "a b\"MID\" c d";
    std::vector<std::string> result;
    unsigned int ret = stringTokenize(s, ' ', &result);
    assert(ret == 4);    
    assert(result.size() == 4);
    assert(result[0] == "a");
    assert(result[1] == "b\"MID\"");
    assert(result[2] == "c");
    assert(result[3] == "d");

    ret = stringTokenize(s, "\" ", &result);
    assert(result.size() == 6);
    assert(result[0] == "a");
    assert(result[1] == "b");
    assert(result[2] == "MID");
    assert(result[3] == "");
    assert(result[4] == "c");
    assert(result[5] == "d");

    s = "";
    ret = stringTokenize(s, " ", &result);
    assert(result.size() == 1);
    assert(result[0] == "");
  }
  {
    std::string s = "a b\"MID\" c d";
    std::string piece;
    std::vector <std::string> result;
    StringTokenizer st1(s, ' ');
    while (st1.next(&piece)) {
      //printf("piece = %s\n", piece.c_str());
      result.push_back(piece);
    }
    assert(result.size() == 4);
    assert(result[0] == "a");
    assert(result[1] == "b\"MID\"");
    assert(result[2] == "c");
    assert(result[3] == "d");

    result.clear();
    StringTokenizer st2(s, "\" ");
    while (st2.next(&piece)) {
      printf("piece = %s\n", piece.c_str());
      result.push_back(piece);
    }
    assert(result.size() == 6);
    assert(result[0] == "a");
    assert(result[1] == "b");
    assert(result[2] == "MID");
    assert(result[3] == "");
    assert(result[4] == "c");
    assert(result[5] == "d");

    result.clear();
    s = "";
    StringTokenizer st3(s, " ");
    while (st3.next(&piece)) {
      result.push_back(piece);
    }
    assert(result.size() == 1);
    assert(result[0] == "");
  }  
  {
      std::string s = "";
      std::string res = stringStrip(s);
      assert(res.size() == 0);

      s = "  ";
      res = stringStrip(s);
      assert(res.size() == 0);
  }

  return 0;
}
Example #14
0
int main()
{
	//Calka z sinusa
	cout << "CALKA Z SINUSA" << endl;
	double result = 0.0;
	TworzenieWatkow calka(0, M_PI, &result);
	boost::thread thread(calka);
	cout << "Hardware concurrency: " << boost::thread::hardware_concurrency
		<< endl;
	cout << "Thread ID" << thread.get_id() << endl;
	thread.join();
	cout << "result" << result << endl;
	cout << "DONE!";
	getchar();
	//-------------------------------------
	//Synchronizacja
	cout << "SYNCHRONIZACJA" << endl;
	mutex characterMutex;
	string lancuch;
	lancuch.resize(CHARACTERS_TO_WRITE);
	thread_group threads;
	for (unsigned int i = 0; i < NUMBER_OF_THREADS; ++i)
		threads.create_thread(Watek('a'+i,lancuch,characterMutex));
	threads.join_all();
	cout << lancuch << endl;
	cout << "DONE!";
	getchar();
	//----------------------------------------
	//Zmienne warunkowe
	cout << "ZMIENNE WARUNKOWE"<<endl;
	mutex dataMutex;
	Monitor<char>container(dataMutex);
	thread_group conditional;
	mutex consoleMutex;
	for (int i = 0; i < 5; i++) {
		conditional.create_thread(Consumer(container,i,consoleMutex));
		conditional.create_thread(Producer(container,i,consoleMutex));
	}
	conditional.join_all();
	cout << "DONE!";
	getchar();
	//------------------------------------
	//Pociagi/semafory
	cout << "STACJA KOLEJOWA"<<endl;
	Peron p1("p1"), p2("p2"), p3("p3");
	Train tr1 = Train("T1", p2, p1);
	boost::thread t1(tr1);
	boost::thread t2(Train("T2", p2, p3));
	boost::thread t3(Train("T3", p2, p1));
	boost::thread t4(Train("T4", p2, p3));
	t1.join();
	t2.join();
	t3.join();
	t4.join();
	cout << "DONE"<<endl;
	getchar();
	cout << "FILOZOFOWIE" << endl;
	Semafor eating(PHILOSOPHERS - 1);

	Fork* forks[5];
	thread_group philosophers;
	for (int i = 0; i<PHILOSOPHERS; i++)
	{
		forks[i] = new Fork(i);
	}
	for (int i = 0; i<PHILOSOPHERS; i++)
	{
		philosophers.create_thread(Philosopher(i, forks[i], forks[(i + (PHILOSOPHERS -1)) % PHILOSOPHERS], eating));
	}
	philosophers.join_all();
	cout << "DONE"<<endl;
	getchar();
	cout << "TASK 1" << endl;
	mutex tConsoleMutex;
	Task1 taskOne(tConsoleMutex,0);
	Task1 taskTwo(tConsoleMutex,1);
	boost::thread th1(taskOne);
	boost::thread th2(taskTwo);
	th1.join();
	th2.join();
	cout << "DONE" << endl;
	getchar();
	cout << "TASK 2" << endl;
	boost::mutex task2Mutex;
	Task2 task2DataGenerator(100);
	boost::thread task2Thread(task2DataGenerator);
	boost::unique_lock<mutex>task2Lock(task2Mutex);
	task2DataGenerator.task2isGeneratingData->wait(task2Lock);
	for (int i = 0; i < 100; i++)cout << task2Array[i] << endl;
	cout << "DONE" << endl; 
	getchar();
	cout << "TASK 3" << endl;
	thread_group task3Group;
	Semafor task3Semafor(1);
	Semafor task3Max3ThreadsSemafor(3);
	for (int i = 0; i < 10; i++) {
		task3Group.create_thread(Task3(task3Max3ThreadsSemafor,task3Semafor,i));
	}
	task3Group.join_all();
	cout << "DONE" << endl;
	getchar();
	cout << "SMOLKA EXAM"<<endl;
	cout << "TASK 1"<<endl;
	boost::mutex sConsoleMutex;
	STask1 st1(sConsoleMutex);
	STask1 st2(sConsoleMutex);
	boost::thread sTask1Thread(st1);
	boost::thread sTask1Thread2(st2);
	sTask1Thread.join();
	sTask1Thread2.join();
	cout << "DONE" << endl;
	getchar();
	cout << "TASK 2" << endl;
	sN = 75;
	boost::thread sTask2Thread(sTask2);
	boost::mutex sTask2Mutex;
	boost::unique_lock<mutex>sTask2Lock(sTask2Mutex);
	sTask2Condition.wait(sTask2Lock);
	for (int i = 0; i < 75; i++) {
		cout<< sTask2Array[i]<<endl;
	}
	getchar();
    return 0;
}
Example #15
0
void stratifysites::run ()  {
    cout << "# Parameters\n";
    cout << "# thresh1=" << thresh1 << "\n";
    cout << "# thresh2=" <<thresh2 << "\n";
    cout << "# tlength="<<tlength << "h\n";
    cout << "# genpos="<<usegenpos << "\n";
    cout << "# strict="<<strict << "\n";
    cout << "# bin="<<bins << "\n";
    cout << "# predfile="<<predfile << "\n";
    cout << "# snpfile="<<snpfile << "\n";
    cout << "# genofile="<<genofile << "\n";
    cout <<  "## SNP id\n";
    cout <<  "## Chromosome \n";
    cout <<  "## Genetic position\n";
    cout <<  "## Physical position\n";
    cout <<  "## Average posterior probability of N on derived alleles \n";
    cout <<  "## Average posterior probability of N on ancestral alleles \n";
    cout <<  "## Number of derived alleles that are predicted to be Neandertal \n";
    cout <<  "## Total number of derived alleles \n";
    cout <<  "## Number of ancestral alleles that are predicted to be Neandertal \n";
    cout <<  "## Total number of ancestral alleles \n";



    if (givenprefix) {
        
        cout.setf(ios::fixed,ios::floatfield); 
        cout.precision(3);
    }

    for (int c = 0 ; c < nchr; c++) { 
        vector<snp> snps = geno->snps[geno->chrs[c]];
        vector<int> tmppred (nind, 0);
        vector<double> reg (nind,0);
        vector<double> reg2 (nind,0);
        vector<double> st1 (nind,0);
        vector<double> st2 (nind,0);
        vector<int> startpos (nind, 0);
        
        vector<double> maxlengths(snps.size(), 0 );
        vector<double> avglengths(snps.size(), 0 );
        vector<double> maxglengths(snps.size(), 0 );
        vector<double> avgglengths(snps.size(), 0 );
        vector<int> denomlengths(snps.size(), 0 );

        unordered_map <string, double> plmap ;
        unordered_map <string, double> glmap ;

        int incontig = 0 ;
        int contigsnps  = 0;
        string contigchr;
        double contigstart = 0;
        double  contigend = 0 ;
        double contigl = 0 ;
        double contigavganc =  0;

        double avgpredanc  = 0;

        for (int i = 0 ; i < snps.size() ; i++) { 
            for (int j = 0 ; j < nind; j++) { 
                double p = (*predanc).get(c,i,j);
                tmppred [j] = (p>thresh1)?1:0;
                avgpredanc += p;
            }
            string id = snps[i].id;
            string chr = snps[i].chr;

            if (nind>0)
                avgpredanc /= nind ;

            if (i==0) { 
                for (int j = 0  ; j < nind ; j++) { 
                    reg[j]  =reg2[j] = 0;
                    st1[j] = st2[j] = tmppred[j];
                    startpos[j] = 0;
                }
            } else { 
                int count1 = 0 ; 
                int count2 = 0;
                for (int j = 0 ; j < nind; j++) { 
                    int flag1 = 0;
                    int flag2 = 0;
                    int len1 = 0 ;
                    double len2 = 0;
                    double avgconf = 0 ;
                    double trueconf = 0 ;
                    int denom = 0 ;
                    int start = 0 ;
                    int end = 0 ;

                    if (st1[j] == 0 && tmppred[j] > 0) {
                        st1[j] = 1;
                        startpos[j] = i;
                    } else if (st1[j]==1 && tmppred[j]==0) {
                        len1 = reg[j];
                        for (int k = i - 1; k >= 0 && k >= startpos[j] ; k--) {
                            if ( maxlengths[k] < len1) {
                                maxlengths[k] = len1;
                            }
                            avglengths[k] += len1;
                            denomlengths[k]++;

                            start = snps[k].physpos;
                            avgconf +=  (*predanc).get (c,k,j);
                            if (giventrue)
                                trueconf +=  (*trueanc)(c,k,j);
                            denom ++;

                            string key =  chr + ":" + tostring(k) +":"+ tostring(j);
                            plmap[key] = len1;

                        }
                        avgconf = (denom>0)?avgconf/denom:0;
                        trueconf = (denom>0)?trueconf/denom:0;
                        reg[j] = 0;
                        st1[j] = 0;
                        flag1 = 1;
                        end = snps[i-1].physpos;
                        if (len1 > 0) count1++;
                    } else if (st1[j]==1 && tmppred[j] > 0 ) {
                        reg[j] +=  tmppred[j] *(snps[i].physpos - snps[i-1].physpos);
                        count2 ++;
                    } else {
                    }


                    if (st2[j] == 0 && tmppred[j] > 0)
                        st2[j] = 1;
                    else if (st2[j]==1 && tmppred[j]==0) {
                        len2 = reg2[j];
                        for (int k = i - 1; k >= 0 && k >= startpos[j] ; k--) {
                            if (maxglengths[k] < len2) {
                                maxglengths[k] = len2;
                            }
                            avgglengths[k] += len2;
                            string key =  chr + ":" + tostring(k) +":"+ tostring(j);
                            glmap[key] = len2;
                        }
                        reg2[j] = 0; 
                        st2[j] = 0 ;
                        flag2 = 1;

                    } else if (st2[j]==1 && tmppred[j] > 0 ) {
                        reg2[j] +=  tmppred[j] *(snps[i].genpos - snps[i-1].genpos);
                    } else {
                    }

                    if (flag1 && flag2) {
                        if (givenprefix) {

                            len2 *= 100;
                        }
                    }
                }
                if (count2 > 0  ) { 
                    if (incontig) { 
                        contigsnps ++;
                        contigavganc += avgpredanc;
                    } else { 
                        contigchr = geno->chrs[c];
                        contigstart = snps[i-1].physpos;
                        incontig = 1;
                    }
                    contigl += (snps[i].physpos - snps[i-1].physpos);
                } else if (count2 == 0 && count1 >  0) { 
                    contigend = snps[i].physpos;
                    if (contigsnps > 0) 
                        contigavganc /= contigsnps;
                    long cs = contigstart;
                    long ce = contigend;
                    contigl = 0 ;
                    incontig = 0 ;
                    contigsnps = 0 ;
                    contigavganc = 0 ;
                }
            }
        }

        for (int i = 0 ; i < snps.size() ; i++) { 
            string id = snps[i].id;
            string chr = snps[i].chr;
            double pos = snps[i].physpos;
            double gpos = snps[i].genpos;

            int n1 = 0;
            int n2 = 0;
            double n3 = 0;
            double n3a = 0 ;
            double n4 = 0;
            double g = 0 ;
            double f = 0 ;
            double f2 = 0 ; 
            int denom2 = 0 ;
            double f1 = 0 ;
            int denom1 = 0 ;
            int d = 0 ;
            int a = 0 ;
            int dn = 0 ; 
            int an = 0;


            double maxl = 0 ;
            double maxgl  = 0;
            for (int j = 0 ; j < nind ; j++) { 
                string key = chr + ":" + tostring(i) + ":" + tostring(j);
                double panc = (*predanc).get(c,i,j);
                if (io::debug >= 1)
                    cout << "panc ( " << c <<","<<i<<","<<j<<") = " << panc << endl;
                int predn = 0 ;
                int predh = 0 ;
                double predl = 0 ;
                if (usegenpos) {
                    if ( glmap.find(key) != glmap.end())
                        predl = glmap[key] * 100;
                    if (maxgl < predl)
                        maxgl = predl;
                } else { 
                    if ( plmap.find(key) != plmap.end())
                        predl = plmap[key];
                    if (maxl < predl) 
                        maxl  = predl;
                }

                if ( panc >= thresh1 && predl >= tlength)
                    predn = 1;
                if (panc <= thresh2)
                    predh = 1;

                int allele = (*geno)(c,i,j);
                f += allele;

                if (allele==1) {
                    d ++;
                    n1 += predn;
                    n2 += predh;
                    n3 += panc;
                    if (predn )
                        dn ++;
                }
                if (allele==0) { 
                    n3a += panc;
                    a ++;
                    if (predn )
                        an ++;
                }

                n4 += panc;

                if (predn) {
                    f1 += allele;
                    denom1++;
                }
                if (predh) { 
                    f2 += allele;
                    denom2 ++;
                }

            }
            f /= nind;
            g /= nind;
            f1 = denom1>0?(f1/denom1):0;
            f2 = denom2>0?(f2/denom2):0;

            if (d>0) { 
                n1/=d; n2/=d; n3/=d; 
            }
            if (a>0) { 
                n3a /= a;
            }
            if (nind > 0)
                n4 /= nind;
            int m1 = (n1>=1)?1:0;
            int m2 = ( (n1>0)&&(n2>0))?1:0;

            cout << id << "\t" << chr << "\t" << gpos*100 << "\t" << snps[i].getphyspos ();
            cout <<  "\t" << n3 << "\t" << n3a  ;
            cout << "\t" << dn  << "\t" << d << "\t" << an << "\t" << a;
            cout << endl;

            if (denomlengths[i]>0) { 
                avglengths[i] /= denomlengths[i];
                avgglengths[i] /= denomlengths[i];
            }

            if (givenprefix) {
                maxglengths[i] *= 100;
                avgglengths[i] *= 100;
                long ml = maxlengths[i];
                long al = avglengths[i];
            }

        }


    }
}
US_USE_NAMESPACE

int usServiceTrackerTest(int /*argc*/, char* /*argv*/[])
{
  US_TEST_BEGIN("ServiceTrackerTest")

  ModuleContext* mc = GetModuleContext();
  SharedLibraryHandle libS("TestModuleS");

  // Start the test target to get a service published.
  try
  {
    libS.Load();
  }
  catch (const std::exception& e)
  {
    US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() );
  }

  // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null

  std::string s1("org.cppmicroservices.TestModuleSService");
  ServiceReference servref = mc->GetServiceReference(s1 + "0");

  US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0");

  ServiceControlInterface* serviceController = mc->GetService<ServiceControlInterface>(servref);
  US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller");

  std::auto_ptr<ServiceTracker<> > st1(new ServiceTracker<>(mc, servref));

  // 2. Check the size method with an unopened service tracker

  US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0");

  // 3. Open the service tracker and see what it finds,
  // expect to find one instance of the implementation,
  // "org.cppmicroservices.TestModuleSService0"

  st1->Open();
  std::string expName  = "TestModuleS";
  std::list<ServiceReference> sa2;
  st1->GetServiceReferences(sa2);

  US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size");
  std::string name(us_service_impl_name(mc->GetService(sa2.front())));
  US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name");

  // 5. Close this service tracker
  st1->Close();

  // 6. Check the size method, now when the servicetracker is closed
  US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size");

  // 7. Check if we still track anything , we should get null
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size");

  // 8. A new Servicetracker, this time with a filter for the object
  std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")";
  LDAPFilter f1(fs);
  st1.reset(new ServiceTracker<>(mc, f1));
  // add a service
  serviceController->ServiceControl(1, "register", 7);

  // 9. Open the service tracker and see what it finds,
  // expect to find two instances of references to
  // "org.cppmicroservices.TestModuleSService*"
  // i.e. they refer to the same piece of code

  st1->Open();
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count");
  for (std::list<ServiceReference>::const_iterator i = sa2.begin();  i != sa2.end(); ++i)
  {
    std::string name(mc->GetService(*i)->GetNameOfClass());
    US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name");
  }

  // 10. Get libTestModuleS to register one more service and see if it appears
  serviceController->ServiceControl(2, "register", 1);
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count");
  for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i)
  {
    std::string name(mc->GetService(*i)->GetNameOfClass());
    US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name");
  }

  // 11. Get libTestModuleS to register one more service and see if it appears
  serviceController->ServiceControl(3, "register", 2);
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count");
  for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i)
  {
    std::string name = mc->GetService(*i)->GetNameOfClass();
    US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name");
  }

  // 12. Get libTestModuleS to unregister one service and see if it disappears
  serviceController->ServiceControl(3, "unregister", 0);
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count");
  for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i)
  {
    std::string name = mc->GetService(*i)->GetNameOfClass();
    US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name");
  }

  // 13. Get the highest ranking service reference, it should have ranking 7
  ServiceReference h1 = st1->GetServiceReference();
  int rank = any_cast<int>(h1.GetProperty(ServiceConstants::SERVICE_RANKING()));
  US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank");

  // 14. Get the service of the highest ranked service reference

  US_BASECLASS_NAME* o1 = st1->GetService(h1);
  US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service");

  // 14a Get the highest ranked service, directly this time
  US_BASECLASS_NAME* o3 = st1->GetService();
  US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service");
  US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances");

  // 15. Now release the tracking of that service and then try to get it
  //     from the servicetracker, which should yield a null object
  serviceController->ServiceControl(1, "unregister", 7);
  US_BASECLASS_NAME* o2 = st1->GetService(h1);
  US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null");

  // 16. Get all service objects this tracker tracks, it should be 2
  std::list<US_BASECLASS_NAME*> ts1;
  st1->GetServices(ts1);
  US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count");

  // 17. Test the remove method.
  //     First register another service, then remove it being tracked
  serviceController->ServiceControl(1, "register", 7);
  h1 = st1->GetServiceReference();
  std::list<ServiceReference> sa3;
  st1->GetServiceReferences(sa3);
  US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count");
  for (std::list<ServiceReference>::const_iterator i = sa3.begin(); i != sa3.end(); ++i)
  {
    std::string name = mc->GetService(*i)->GetNameOfClass();
    US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name");
  }

  st1->Remove(h1);           // remove tracking on one servref
  sa2.clear();
  st1->GetServiceReferences(sa2);
  US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count");

  // 18. Test the addingService method,add a service reference

  // 19. Test the removedService method, remove a service reference


  // 20. Test the waitForService method
  US_BASECLASS_NAME* o9 = st1->WaitForService(50);
  US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method");

  US_TEST_END()
}
	double simulate_with_dependence (string treeFile, double PI_1, double init_k, int total_positions, int num_pos_with_same_k, double k_increase, int is_gamma, double alpha, double beta, int num_cat)
	{

		//read Newick format tree
		tree treeIn(treeFile);
	
		//four states alphabet A C G T (will later be rplaced to 00,01,10,11)
		alphabet* alph = new nucleotide;

		sequenceContainer SC_all; //this will contain all positions
	
		//parameters:
		double PI_0 = 1-PI_1;
		double k = init_k; //will be increased with each iteration

		//parameters:
		int jump_size = total_positions / num_pos_with_same_k;

		for(int i=0; i<jump_size; i++)
		{
			Vdouble freqs; //stationary probabilities PI_00, PI_01, PI_10, PI_11
			double TOTAL = k*PI_1*PI_1 + 2*PI_0*PI_1 + k*PI_0*PI_0;
			freqs.push_back(k*PI_0*PI_0 / TOTAL); //PI_00 = k*PI_0*PI_0 / TOTAL
			freqs.push_back(PI_0*PI_1 / TOTAL); //PI_01 = PI_0*PI_1 / TOTAL
			freqs.push_back(PI_0*PI_1 / TOTAL); //PI_10 = PI_0*PI_1 / TOTAL
			freqs.push_back(k*PI_1*PI_1 / TOTAL); //PI_11 = k*PI_1*PI_1 / TOTAL
	
			//Q matrix (partial values - the rest are calculated by gtrModel using freqs and these values)
			MDOUBLE a2c = PI_1; // --> c2a = freqs[a]*a2c/freqs[c] --> c2a = ((k*PI_0*PI_0 / TOTAL)*PI_1)/(PI_0*PI_1 / TOTAL) = k*PI_0
			MDOUBLE a2g = PI_1;
			MDOUBLE a2t = 0;
			MDOUBLE c2g = 0;
			MDOUBLE c2t = k*PI_1;
			MDOUBLE g2t = k*PI_1;

			//starting the evolutionary model
			distribution *currDist = NULL;
			if(is_gamma == 1)
			{
				currDist = new generalGammaDistribution(alpha,beta,num_cat); // ---> in the future we might want to turn these into param
			}
			else
			{
				currDist = new uniDistribution; // no among site rate variation
			}
		
			replacementModel *probMod = NULL;
			pijAccelerator *pijAcc = NULL;

			probMod = new gtrModel(freqs,a2c,a2g,a2t,c2g,c2t,g2t);
			pijAcc = new trivialAccelerator(probMod);
			stochasticProcess* _sp = new stochasticProcess(currDist, pijAcc);

			//simulate:
			simulateTree st1(treeIn, *_sp, alph);
			st1.generate_seq(num_pos_with_same_k); //simulate num_pos_with_same_k positions with the current k

			if(i == 0)
			{
				SC_all = st1.toSeqDataWithoutInternalNodes(); //first time
			}
			else
			{
				sequenceContainer SC = st1.toSeqDataWithoutInternalNodes(); //concatenate new positions to the ones you have
				SC_all.concatenate(SC);
			}
		
			delete currDist;
			delete probMod;
			delete pijAcc;
			delete _sp;

			k = k + k_increase; //k = 1 , 1.05 , 1.1 , ... , 5.5
		}

		//prepare out file name:
		std::stringstream sstm;
		if(is_gamma == 1)
		{
			sstm << treeFile << ".gammaRateNoInv.PI_1=" << PI_1 << ".init_k=" << init_k << ".k_group_size=" << num_pos_with_same_k << ".k_increase=" << k_increase << ".fas";
		}
		else
		{
			sstm << treeFile << ".NoRate.PI_1=" << PI_1 << ".init_k=" << init_k << ".k_group_size=" << num_pos_with_same_k << ".k_increase=" << k_increase << ".fas";
		}
		std::string seqOutputFile = sstm.str();

		//write out:
		ofstream seq_sim(seqOutputFile.c_str());
		fastaFormat::write(seq_sim,SC_all);
		seq_sim.close();
	
	
		delete alph;
		
		return 0;
	
	}
Example #18
0
main ()
{
    // CL_StringSequence tst (18000); // Testing big sequences
    CL_StringSequence a;
    a.Add ("world!");
    a.Add ("Hello,");
    a.Add ("this is");
    a.Add ("a great day.");
    PrintOut (a);

    a.Insert ("world! 2", 1);
    PrintOut (a);
    a.Insert ("Hello, 2", -1);
    PrintOut (a);
    a.Insert ("this is 2", 2);
    PrintOut (a);
    a.Insert ("a great day. 2", 3);
    PrintOut (a);


    a.Sort();
    PrintOut (a);

#ifndef __GNUC__  // GCC Still has bugs!
    CL_IntegerSet st1(2,4);
    st1.Add (4);
    st1.Add (7);
    st1.Add (8);
    st1.Add (9);
    CL_StringSequence sq = a - st1;
    PrintOut (sq);
#endif
    
    a.ShiftRightAt (2);
    PrintOut (a);

    a[2] = "Some string here";
    PrintOut (a);
    
    a.ShiftLeftAt (2, 2);
    PrintOut (a);

    CL_StringSequence* b = new CL_StringSequence(10);
    *b = a;
    PrintOut (*b);

    *b += a;
    PrintOut (*b);
    
    b->Sort();
    PrintOut (*b);
    
    CL_BinaryFile f ("seqtest.dat", TRUE);
    f << *b; // Testing persistent sequences
    b->MakeEmpty ();
    

    // CL_Builder<CL_String> aBuilder;
    // CL_ObjectSequence a2(0, &aBuilder);
    CL_ObjectSequence a2;
    CL_String* pStrg;
    pStrg = new CL_String ("1"); a2.Add (pStrg);
    pStrg = new CL_String ("2"); a2.Add (pStrg);
    pStrg = new CL_String ("3"); a2.Add (pStrg);
    pStrg = new CL_String ("10"); a2.Add (pStrg);
    pStrg = new CL_String ("20"); a2.Add (pStrg);
    pStrg = new CL_String ("30"); a2.Add (pStrg);
    pStrg = new CL_String ("11"); a2.Add (pStrg);
    pStrg = new CL_String ("22"); a2.Add (pStrg);
    pStrg = new CL_String ("31"); a2.Add (pStrg);
    pStrg = new CL_String ("10"); a2.Add (pStrg);
    printf ("a2's size: %ld\n", a2.Size());

    f << a2;             // Testing persistent sequences
    f.SeekToBegin();
    f >> *b;
    // b->ReadFrom (f);
    
    printf ("Restored b is: \n"); PrintOut (*b);
    delete b;

    long i;
    for (i = 0; i < a2.Size(); i++) {
        printf ("'%s'\n", ((CL_String*) a2[i])->AsPtr());
    }
    pStrg = (CL_String*) a2.ExtractLeftmost();
    printf ("Leftmost: '%s'\n", pStrg->AsPtr());
    for (i = 0; i < a2.Size(); i++) {
        printf ("'%s'\n", ((CL_String*) a2[i])->AsPtr());
    }
    delete pStrg;

    pStrg = (CL_String*) a2[4];
    a2.Remove (4);
    delete pStrg;
    for (i = 0; i < a2.Size(); i++) {
        printf ("'%s'\n", ((CL_String*) a2[i])->AsPtr());
    }
    
    a2.DestroyContents ();
    f >> a2;
    printf ("Restored a2 is:\n");
    for (i = 0; i < a2.Size(); i++) {
        printf ("'%s'\n", ((CL_String*) a2[i])->AsPtr());
    }
    printf ("------------------------------------\n");
    a2.DestroyContents ();
    
    
    

    CL_IntegerSequence iseq;
    for (i = 0; i < 100; i++) {
        iseq.Add (i);
        iseq.Add (5*i);
    }
    for (i = 5; i < 80; i++)
        iseq.Remove (2);
    iseq.Add (253);
    printf ("iseq size %ld\n", iseq.Size());
    long j;
    for (j = 0; j < iseq.Size(); j++) {
        printf ("iseq[%ld] = %ld\n", j, iseq[j]);
    }
    iseq.Sort();
    printf ("==============================\niseq size %ld\n", iseq.Size());
    for (j = 0; j < iseq.Size(); j++) {
        printf ("iseq[%ld] = %ld\n", j, iseq[j]);
    }
    iseq.Sort();

    return 0;
}