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;
}
Esempio n. 2
0
int main()
{
	Stack st1;
	Stack st2(st1);
	Stack st3;

	cout << st1.isempty() << endl;
	
	st1.push(12123124);
	st1.push(12222222);
	st1.push(33333333);
	cout << "St1: " << endl;
	st1.showItems();

	st2 = Stack(st1);
	cout << "St2: " << endl;
	st2.showItems();

	st1 = Stack();
	cout << "St1 empty:" << endl;
	st1.showItems();

	cout << endl;

	cout << "St2: " << endl;
	st2.showItems();

	st3 = st2;
	cout << "St3: " << endl;
	st3.showItems();

	system("Pause");
    return 0; 
}
Esempio n. 3
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);
}
Esempio n. 4
0
// pobiera int wartosc klucza
int ConfFile::getIntValue(string label)
{
	int t = mLabels.count(label);
	if (t == 0)
	{
		error = true;
		return 0;
	};
	map<string, string>::iterator i = mLabels.find(label);
	int v;
	istringstream st2((*i).second);
	st2 >> v;
	return v;
}
Esempio n. 5
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", ""));
}
Esempio n. 6
0
void
ODMatrix::readO(LineReader& lr, double scale,
                std::string vehType, bool matrixHasVehType) {
    PROGRESS_BEGIN_MESSAGE("Reading matrix '" + lr.getFileName() + "' stored as OR");
    // parse first defs
    std::string line;
    if (matrixHasVehType) {
        line = getNextNonCommentLine(lr);
        int type = TplConvert::_2int(StringUtils::prune(line).c_str());
        if (vehType == "") {
            vehType = toString(type);
        }
    }

    // parse time
    std::pair<SUMOTime, SUMOTime> times = readTime(lr);
    SUMOTime begin = times.first;
    SUMOTime end = times.second;

    // factor
    double factor = readFactor(lr, scale);

    // parse the cells
    while (lr.hasMore()) {
        line = getNextNonCommentLine(lr);
        if (line.length() == 0) {
            continue;
        }
        StringTokenizer st2(line, StringTokenizer::WHITECHARS);
        if (st2.size() == 0) {
            continue;
        }
        try {
            std::string sourceD = st2.next();
            std::string destD = st2.next();
            double vehNumber = TplConvert::_2double(st2.next().c_str()) * factor;
            if (vehNumber != 0) {
                add(vehNumber, begin, end, sourceD, destD, vehType);
            }
        } catch (OutOfBoundsException&) {
            throw ProcessError("Missing at least one information in line '" + line + "'.");
        } catch (NumberFormatException&) {
            throw ProcessError("Not numeric vehicle number in line '" + line + "'.");
        }
    }
    PROGRESS_DONE_MESSAGE();
}
Esempio n. 7
0
void splay_tree_copy_ctor_asignment_operator() {
    fwk::splay_tree<int, int> st;
    st.insert(1, 1);
    st.insert(2, 2);
    st.insert(3, 3);
    st.insert(5, 5);
    st.insert(4, 4);
    st.insert(20, 20);
    ASSERT_EQ(st.empty(), false);
    ASSERT_EQ(st.size(), 6);
    fwk::splay_tree<int, int> st2(st);
    fwk::splay_tree<int, int> st3;
    st3 = st2;
    st2.pre_order([](int &i) { std::cout << i << " "; });
    std::cout << std::endl;
    st3.pre_order([](int &i) { std::cout << i << " "; });
    std::cout << std::endl;
}
Esempio n. 8
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");
		}
Esempio n. 9
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 ;
}
Esempio n. 10
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());
}
Esempio n. 11
0
int main() {

    Stack<std::string> st1;
    st1.push("Jack").push("Zack").push("Sam").push("Maria");
    std::cout << "number of elements: " << st1.size() << std::endl;
    std::cout << "Is stack empty? " << st1.is_empty() << std::endl;
    print(st1, std::cout);
    
    Stack<std::string> st2(st1);
    st2.pop().pop();
    st2.top() = "Marty";
    std::cout << "number of elements: " << st2.size() << std::endl;
    std::cout << "Is stack empty? " << st2.is_empty() << std::endl;
    print(st2, std::cout);
    
    Stack<std::string> st3;
    std::cout << "number of elements: " << st3.size() << std::endl;
    std::cout << "Is stack empty? " << st3.is_empty() << std::endl;
    st3 = st1;
    std::cout << "number of elements: " << st3.size() << std::endl;
    std::cout << "Is stack empty? " << st3.is_empty() << std::endl;
    print(st3, std::cout);
    
    while (!st3.is_empty()) {st3.pop();}
    std::cout << "number of elements: " << st3.size() << std::endl;
    std::cout << "Is stack empty? " << st3.is_empty() << std::endl;
    print(st3, std::cout);
    
    st3.swap(st2);
    
    std::cout << "number of elements: " << st3.size() << std::endl;
    std::cout << "Is stack empty? " << st3.is_empty() << std::endl;
    print(st3, std::cout);
    
    std::cout << "number of elements: " << st2.size() << std::endl;
    std::cout << "Is stack empty? " << st2.is_empty() << std::endl;
    print(st2, std::cout);
    
    return 0;
}
Esempio n. 12
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());
}
Esempio n. 13
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;
	};
}
Esempio n. 14
0
int		main()
{
	FragTrap	ft("#YOLO");
	FragTrap	ft2(ft);
	FragTrap	ft3 = ft2;

	ScavTrap	st("#YOLO");
	ScavTrap	st2(st);
	ScavTrap	st3 = st2;

	ft.rangedAttack("other");
	ft.meleeAttack("other");
	ft.takeDamage(32);
	ft2.takeDamage(150);
	ft3.takeDamage(0);
	ft3.beRepaired(0);
	ft3.beRepaired(150);
	ft.vaulthunter_dot_exe("other");
	ft.vaulthunter_dot_exe("other");
	ft.vaulthunter_dot_exe("other");
	ft.vaulthunter_dot_exe("other");
	ft.vaulthunter_dot_exe("other");
	ft.vaulthunter_dot_exe("other");
	
	st.rangedAttack("other");
	st.meleeAttack("other");
	st.takeDamage(32);
	st2.takeDamage(150);
	st3.takeDamage(0);
	st3.beRepaired(0);
	st3.beRepaired(150);
	st.challengeNewcomer("other");
	st.challengeNewcomer("other");
	st.challengeNewcomer("other");
	st.challengeNewcomer("other");
	st.challengeNewcomer("other");
	st.challengeNewcomer("other");
}
Esempio n. 15
0
Distribution_Points
ODMatrix::parseTimeLine(const std::vector<std::string>& def, bool timelineDayInHours) {
    Distribution_Points result("N/A");
    if (timelineDayInHours) {
        if (def.size() != 24) {
            throw ProcessError("Assuming 24 entries for a day timeline, but got " + toString(def.size()) + ".");
        }
        for (int chour = 0; chour < 24; ++chour) {
            result.add(chour * 3600., TplConvert::_2double(def[chour].c_str()));
        }
        result.add(24 * 3600., 0.); // dummy value to finish the last interval
    } else {
        for (int i = 0; i < (int)def.size(); i++) {
            StringTokenizer st2(def[i], ":");
            if (st2.size() != 2) {
                throw ProcessError("Broken time line definition: missing a value in '" + def[i] + "'.");
            }
            const double time = TplConvert::_2double(st2.next().c_str());
            result.add(time, TplConvert::_2double(st2.next().c_str()));
        }
    }
    return result;
}
Esempio n. 16
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;
}
Esempio n. 17
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));
	}
}
Esempio n. 18
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);
}
Esempio n. 19
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;
}
Esempio n. 20
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;
}
Esempio n. 21
0
void
ODMatrix::readV(LineReader& lr, double scale,
                std::string vehType, bool matrixHasVehType) {
    PROGRESS_BEGIN_MESSAGE("Reading matrix '" + lr.getFileName() + "' stored as VMR");
    // parse first defs
    std::string line;
    if (matrixHasVehType) {
        line = getNextNonCommentLine(lr);
        if (vehType == "") {
            vehType = StringUtils::prune(line);
        }
    }

    // parse time
    std::pair<SUMOTime, SUMOTime> times = readTime(lr);
    SUMOTime begin = times.first;
    SUMOTime end = times.second;

    // factor
    double factor = readFactor(lr, scale);

    // districts
    line = getNextNonCommentLine(lr);
    const int numDistricts = TplConvert::_2int(StringUtils::prune(line).c_str());
    // parse district names (normally ints)
    std::vector<std::string> names;
    while ((int)names.size() != numDistricts) {
        line = getNextNonCommentLine(lr);
        StringTokenizer st2(line, StringTokenizer::WHITECHARS);
        while (st2.hasNext()) {
            names.push_back(st2.next());
        }
    }

    // parse the cells
    for (std::vector<std::string>::iterator si = names.begin(); si != names.end(); ++si) {
        std::vector<std::string>::iterator di = names.begin();
        //
        do {
            line = getNextNonCommentLine(lr);
            if (line.length() == 0) {
                continue;
            }
            try {
                StringTokenizer st2(line, StringTokenizer::WHITECHARS);
                while (st2.hasNext()) {
                    assert(di != names.end());
                    double vehNumber = TplConvert::_2double(st2.next().c_str()) * factor;
                    if (vehNumber != 0) {
                        add(vehNumber, begin, end, *si, *di, vehType);
                    }
                    if (di == names.end()) {
                        throw ProcessError("More entries than districts found.");
                    }
                    ++di;
                }
            } catch (NumberFormatException&) {
                throw ProcessError("Not numeric vehicle number in line '" + line + "'.");
            }
            if (!lr.hasMore()) {
                break;
            }
        } while (di != names.end());
    }
    PROGRESS_DONE_MESSAGE();
}
Esempio n. 22
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];
            }

        }


    }
}
Esempio n. 23
0
    int _tmain(void)
    {
        MDate d(TEXT("2014.7.1"));
        assert(d.GetYear() == 2014);
        assert(d.GetMonth() == 7);
        assert(d.GetDay() == 1);
        #ifdef UNICODE
            std::wcout << d << std::endl;
        #else
            std::cout << d << std::endl;
        #endif

        MTime t(TEXT("12:00"));
        assert(t.GetHour() == 12);
        assert(t.GetMinute() == 0);
        assert(t.GetSecond() == 0);
        assert(t.GetMilliseconds() == 0);
        #ifdef UNICODE
            std::wcout << t << std::endl;
        #else
            std::cout << t << std::endl;
        #endif

        MSystemTime st1;
        st1.SetDate(d);
        st1.SetTimeOfDay(t);
        MSystemTime st2(TEXT("20140701120000"));
        assert(st1 == st2);

        st2.SetDay(2);
        #ifdef UNICODE
            std::wcout << st1 << std::endl;
            std::wcout << st2 << std::endl;
        #else
            std::cout << st1 << std::endl;
            std::cout << st2 << std::endl;
        #endif

        MTimeSpan ts = st2 - st1;
        assert(ts.GetTotalDays() == 1);
        assert(ts.GetTotalHours() == 24);
        assert(ts.GetTotalMinutes() == 24 * 60);
        assert(ts.GetTotalSeconds() == 24 * 60 * 60);
        st1 += ts;
        assert(st1 == st2);
        #ifdef UNICODE
            std::wcout << ts << std::endl;
        #else
            std::cout << ts << std::endl;
        #endif

        st1 -= ts;
        assert(ts.GetTotalDays() == 1);

        st2.SetDay(0);
        st2.FixDay();
        assert(st2.GetDay() == 30);
        #ifdef UNICODE
            std::wcout << st2 << std::endl;
        #else
            std::cout << st2 << std::endl;
        #endif

        st2.SetDay(31);
        st2.FixDay();
        assert(st2.GetMonth() == 7);
        assert(st2.GetDay() == 1);
        #ifdef UNICODE
            std::wcout << st2 << std::endl;
        #else
            std::cout << st2 << std::endl;
        #endif

        ts.Parse("1days and 01:02:03");
        #ifdef UNICODE
            std::wcout << ts << std::endl;
        #else
            std::cout << ts << std::endl;
        #endif
        ts.Parse("21:22:23");
        #ifdef UNICODE
            std::wcout << ts << std::endl;
        #else
            std::cout << ts << std::endl;
        #endif

        return 0;
    }