void visitSetGlobal(SetGlobal* curr) {
   if (reachable.count(ModuleElement(ModuleElementKind::Global, curr->name)) == 0) {
     queue.emplace_back(ModuleElementKind::Global, curr->name);
   }
 }
Пример #2
0
 bool WasWrapped(uint64 guid)
 {
     return lWrappedPlayers.count(guid);
 }
	bool contains(EdgeId e) const {
		return edges_.count(e) > 0;
	}
Пример #4
0
 inline bool find( unsigned int hash ) { return images.count( hash ) > 0; }
Пример #5
0
static int compileLispFragment(char const*& d, char const* e, bool _quiet, bytes& o_code, vector<unsigned>& o_locs, map<string, unsigned>& _vars)
{
	std::map<std::string, Instruction> const c_arith = { { "+", Instruction::ADD }, { "-", Instruction::SUB }, { "*", Instruction::MUL }, { "/", Instruction::DIV }, { "%", Instruction::MOD } };
	std::map<std::string, pair<Instruction, bool>> const c_binary = { { "<", { Instruction::LT, false } }, { "<=", { Instruction::GT, true } }, { ">", { Instruction::GT, false } }, { ">=", { Instruction::LT, true } }, { "=", { Instruction::EQ, false } }, { "!=", { Instruction::EQ, true } } };
	std::map<std::string, Instruction> const c_unary = { { "!", Instruction::NOT } };
	std::set<char> const c_allowed = { '+', '-', '*', '/', '%', '<', '>', '=', '!' };

	bool exec = false;
	int outs = 0;
	bool seq = false;

	while (d != e)
	{
		// skip to next token
		for (; d != e && !isalnum(*d) && *d != '(' && *d != ')' && *d != '{' && *d != '}' && *d != '_' && *d != '"' && *d != '@' && *d != '[' && !c_allowed.count(*d) && *d != ';'; ++d) {}
		if (d == e)
			break;

		switch (*d)
		{
		case ';':
			for (; d != e && *d != '\n'; ++d) {}
			break;
		case '(':
			exec = true;
			++d;
			break;
		case '{':
			++d;
			while (d != e)
			{
				bytes codes;
				vector<unsigned> locs;
				outs = 0;
				int o;
				if ((o = compileLispFragment(d, e, _quiet, codes, locs, _vars)) > -1)
				{
					for (int i = 0; i < outs; ++i)
						o_code.push_back((byte)Instruction::POP);	// pop additional items off stack for the previous item (final item's returns get left on).
					outs = o;
					appendCode(o_code, o_locs, codes, locs);
				}
				else
					break;
			}
			seq = true;
			break;
		case '}':
			if (seq)
			{
				++d;
				return outs;
			}
			return -1;
		case ')':
			if (exec)
			{
				++d;
				return outs;
			}
			else
				// unexpected - return false as we don't know what to do with it.
				return -1;

		case '@':
		{
			if (exec)
				return -1;
			bool store = false;
			++d;
			if (*d == '@')
			{
				++d;
				store = true;
			}
			bytes codes;
			vector<unsigned> locs;
			if (compileLispFragment(d, e, _quiet, codes, locs, _vars) != 1)
				return -1;
			while (d != e && isspace(*d))
				++d;
			appendCode(o_code, o_locs, codes, locs);
			o_code.push_back((byte)(store ? Instruction::SLOAD : Instruction::MLOAD));
			return 1;
		}
		case '[':
		{
			if (exec)
				return -1;
			bool store = false;
			++d;
			if (*d == '[')
			{
				++d;
				store = true;
			}
			bytes codes;
			vector<unsigned> locs;
			if (compileLispFragment(d, e, _quiet, codes, locs, _vars) != 1)
				return -1;
			while (d != e && isspace(*d))
				++d;

			if (*d != ']')
				return -1;
			++d;
			if (store)
			{
				if (*d != ']')
					return -1;
				++d;
			}

			if (compileLispFragment(d, e, _quiet, o_code, o_locs, _vars) != 1)
				return -1;

			appendCode(o_code, o_locs, codes, locs);
			o_code.push_back((byte)(store ? Instruction::SSTORE: Instruction::MSTORE));
			return 0;
		}
		default:
		{
			bool haveLiteral = false;
			u256 literalValue = 0;
			string t;

			if (*d == '"')
			{
				string s = readQuoted(d, e);
				if (s.size() > 32)
				{
					if (!_quiet)
						cwarn << "String literal > 32 characters. Cropping.";
					s.resize(32);
				}
				h256 valHash;
				memcpy(valHash.data(), s.data(), s.size());
				memset(valHash.data() + s.size(), 0, 32 - s.size());
				literalValue = (u256)valHash;
				haveLiteral = true;
			}
			else
			{
				char const* s = d;
				for (; d != e && (isalnum(*d) || *d == '_' || c_allowed.count(*d)); ++d) {}
				t = string(s, d - s);
				if (isdigit(t[0]))
				{
					literalValue = readNumeric(t, _quiet);
					haveLiteral = true;
				}
			}

			if (haveLiteral)
			{
				bool bareLoad = true;
				if (exec)
				{
					bytes codes;
					vector<unsigned> locs;
					if (compileLispFragment(d, e, _quiet, codes, locs, _vars) != -1)
					{
						appendCode(o_code, o_locs, codes, locs);
						while (compileLispFragment(d, e, _quiet, codes, locs, _vars) != -1)
							if (!_quiet)
								cwarn << "Additional items in bare store. Ignoring.";
						bareLoad = false;
					}
				}
				pushLiteral(o_code, literalValue);
				if (exec)
					o_code.push_back(bareLoad ? (byte)Instruction::SLOAD : (byte)Instruction::SSTORE);
				outs = bareLoad ? 1 : 0;
			}
			else
			{
				boost::algorithm::to_upper(t);
				if (t == "IF")
				{
					// Compile all the code...
					bytes codes[4];
					vector<unsigned> locs[4];
					for (int i = 0; i < 3; ++i)
					{
						int o = compileLispFragment(d, e, _quiet, codes[i], locs[i], _vars);
						if (i == 1)
							outs = o;
						if ((i == 0 && o != 1) || o == -1 || (i == 2 && o != outs))
							return -1;
					}
					if (compileLispFragment(d, e, _quiet, codes[3], locs[3], _vars) != -1)
						return false;

					// First fragment - predicate
					appendCode(o_code, o_locs, codes[0], locs[0]);

					// Push the positive location.
					unsigned posLocation = (unsigned)o_code.size();
					o_locs.push_back(posLocation);
					pushLocation(o_code, 0);

					// Jump to negative if false.
					o_code.push_back((byte)Instruction::JUMPI);

					// Second fragment - negative.
					appendCode(o_code, o_locs, codes[2], locs[2]);

					// Jump to end after negative.
					unsigned endLocation = (unsigned)o_code.size();
					o_locs.push_back(endLocation);
					pushLocation(o_code, 0);
					o_code.push_back((byte)Instruction::JUMP);

					// Third fragment - positive.
					increaseLocation(o_code, posLocation, o_code.size());
					appendCode(o_code, o_locs, codes[1], locs[1]);

					// At end now.
					increaseLocation(o_code, endLocation, o_code.size());
				}
				else if (t == "WHEN" || t == "UNLESS")
				{
					outs = 0;
					// Compile all the code...
					bytes codes[3];
					vector<unsigned> locs[3];
					for (int i = 0; i < 2; ++i)
					{
						int o = compileLispFragment(d, e, _quiet, codes[i], locs[i], _vars);
						if (o == -1 || (i == 0 && o != 1))
							return false;
						if (i == 1)
							for (int j = 0; j < o; ++j)
								codes[i].push_back((byte)Instruction::POP);	// pop additional items off stack for the previous item (final item's returns get left on).
					}
					if (compileLispFragment(d, e, _quiet, codes[2], locs[2], _vars) != -1)
						return false;

					// First fragment - predicate
					appendCode(o_code, o_locs, codes[0], locs[0]);
					if (t == "WHEN")
						o_code.push_back((byte)Instruction::NOT);

					// Push the positive location.
					unsigned endLocation = (unsigned)o_code.size();
					o_locs.push_back(endLocation);
					pushLocation(o_code, 0);

					// Jump to end...
					o_code.push_back((byte)Instruction::JUMPI);

					// Second fragment - negative.
					appendCode(o_code, o_locs, codes[1], locs[1]);

					// At end now.
					increaseLocation(o_code, endLocation, o_code.size());
				}
				else if (t == "WHILE")
				{
					outs = 0;
					// Compile all the code...
					bytes codes[3];
					vector<unsigned> locs[3];
					for (int i = 0; i < 2; ++i)
					{
						int o = compileLispFragment(d, e, _quiet, codes[i], locs[i], _vars);
						if (o == -1 || (i == 0 && o != 1))
							return false;
						if (i == 1)
							for (int j = 0; j < o; ++j)
								codes[i].push_back((byte)Instruction::POP);	// pop additional items off stack for the previous item (final item's returns get left on).
					}
					if (compileLispFragment(d, e, _quiet, codes[2], locs[2], _vars) != -1)
						return false;

					unsigned startLocation = (unsigned)o_code.size();

					// First fragment - predicate
					appendCode(o_code, o_locs, codes[0], locs[0]);
					o_code.push_back((byte)Instruction::NOT);

					// Push the positive location.
					unsigned endInsertion = (unsigned)o_code.size();
					o_locs.push_back(endInsertion);
					pushLocation(o_code, 0);

					// Jump to positive if true.
					o_code.push_back((byte)Instruction::JUMPI);

					// Second fragment - negative.
					appendCode(o_code, o_locs, codes[1], locs[1]);

					// Jump to end after negative.
					o_locs.push_back((unsigned)o_code.size());
					pushLocation(o_code, startLocation);
					o_code.push_back((byte)Instruction::JUMP);

					// At end now.
					increaseLocation(o_code, endInsertion, o_code.size());
				}
				else if (t == "FOR")
				{
					compileLispFragment(d, e, _quiet, o_code, o_locs, _vars);
					outs = 0;
					// Compile all the code...
					bytes codes[4];
					vector<unsigned> locs[4];
					for (int i = 0; i < 3; ++i)
					{
						int o = compileLispFragment(d, e, _quiet, codes[i], locs[i], _vars);
						if (o == -1 || (i == 0 && o != 1))
							return false;
						cnote << "FOR " << i << o;
						if (i > 0)
							for (int j = 0; j < o; ++j)
								codes[i].push_back((byte)Instruction::POP);	// pop additional items off stack for the previous item (final item's returns get left on).
					}
					if (compileLispFragment(d, e, _quiet, codes[3], locs[3], _vars) != -1)
						return false;

					unsigned startLocation = (unsigned)o_code.size();

					// First fragment - predicate
					appendCode(o_code, o_locs, codes[0], locs[0]);
					o_code.push_back((byte)Instruction::NOT);

					// Push the positive location.
					unsigned endInsertion = (unsigned)o_code.size();
					o_locs.push_back(endInsertion);
					pushLocation(o_code, 0);

					// Jump to positive if true.
					o_code.push_back((byte)Instruction::JUMPI);

					// Second fragment - negative.
					appendCode(o_code, o_locs, codes[1], locs[1]);

					// Third fragment - incrementor.
					appendCode(o_code, o_locs, codes[2], locs[2]);

					// Jump to beginning afterwards.
					o_locs.push_back((unsigned)o_code.size());
					pushLocation(o_code, startLocation);
					o_code.push_back((byte)Instruction::JUMP);

					// At end now.
					increaseLocation(o_code, endInsertion, o_code.size());
				}
				else if (t == "SEQ")
				{
					while (d != e)
					{
						bytes codes;
						vector<unsigned> locs;
						outs = 0;
						int o;
						if ((o = compileLispFragment(d, e, _quiet, codes, locs, _vars)) > -1)
						{
							for (int i = 0; i < outs; ++i)
								o_code.push_back((byte)Instruction::POP);	// pop additional items off stack for the previous item (final item's returns get left on).
							outs = o;
							appendCode(o_code, o_locs, codes, locs);
						}
						else
							break;
					}
				}
				/*else if (t == "CALL")
				{
					if (exec)
					{
						vector<pair<bytes, vector<unsigned>>> codes(1);
						int totalArgs = 0;
						while (d != e)
						{
							int o = compileLispFragment(d, e, _quiet, codes.back().first, codes.back().second, _vars);
							if (o < 1)
								break;
							codes.push_back(pair<bytes, vector<unsigned>>());
							totalArgs += o;
						}
						if (totalArgs < 7)
						{
							cwarn << "Expected at least 7 arguments to CALL; got" << totalArgs << ".";
							break;
						}

						for (auto it = codes.rbegin(); it != codes.rend(); ++it)
							appendCode(o_code, o_locs, it->first, it->second);
						o_code.push_back((byte)Instruction::CALL);
						outs = 1;
					}
				}*/
				else if (t == "MULTI")
				{
					while (d != e)
					{
						bytes codes;
						vector<unsigned> locs;
						outs = 0;
						int o;
						if ((o = compileLispFragment(d, e, _quiet, codes, locs, _vars)) > -1)
						{
							outs += o;
							appendCode(o_code, o_locs, codes, locs);
						}
						else
							break;
					}
				}
				else if (t == "AND")
				{
					vector<bytes> codes;
					vector<vector<unsigned>> locs;
					while (d != e)
					{
						codes.resize(codes.size() + 1);
						locs.resize(locs.size() + 1);
						{
							int o = compileLispFragment(d, e, _quiet, codes.back(), locs.back(), _vars);
							if (o != 1)
								return false;
						}
						if (compileLispFragment(d, e, _quiet, codes.back(), locs.back(), _vars) != -1)
							break;
					}

					// last one is empty.
					if (codes.size() < 2)
						return false;

					codes.pop_back();
					locs.pop_back();

					vector<unsigned> ends;

					if (codes.size() > 1)
					{
						pushLiteral(o_code, 0);

						for (unsigned i = 1; i < codes.size(); ++i)
						{
							// Check if true - predicate
							appendCode(o_code, o_locs, codes[i - 1], locs[i - 1]);

							// Push the false location.
							ends.push_back((unsigned)o_code.size());
							o_locs.push_back(ends.back());
							pushLocation(o_code, 0);

							// Jump to end...
							o_code.push_back((byte)Instruction::NOT);
							o_code.push_back((byte)Instruction::JUMPI);
						}
						o_code.push_back((byte)Instruction::POP);
					}

					// Check if true - predicate
					appendCode(o_code, o_locs, codes.back(), locs.back());

					// At end now.
					for (auto i: ends)
						increaseLocation(o_code, i, o_code.size());
					outs = 1;
				}
				else if (t == "OR")
				{
					vector<bytes> codes;
					vector<vector<unsigned>> locs;
					while (d != e)
					{
						codes.resize(codes.size() + 1);
						locs.resize(locs.size() + 1);
						{
							int o = compileLispFragment(d, e, _quiet, codes.back(), locs.back(), _vars);
							if (o != 1)
								return false;
						}
					}

					// last one is empty.
					if (codes.size() < 2)
						return false;

					codes.pop_back();
					locs.pop_back();

					vector<unsigned> ends;

					if (codes.size() > 1)
					{
						pushLiteral(o_code, 1);

						for (unsigned i = 1; i < codes.size(); ++i)
						{
							// Check if true - predicate
							appendCode(o_code, o_locs, codes[i - 1], locs[i - 1]);

							// Push the false location.
							ends.push_back((unsigned)o_code.size());
							o_locs.push_back(ends.back());
							pushLocation(o_code, 0);

							// Jump to end...
							o_code.push_back((byte)Instruction::JUMPI);
						}
						o_code.push_back((byte)Instruction::POP);
					}

					// Check if true - predicate
					appendCode(o_code, o_locs, codes.back(), locs.back());

					// At end now.
					for (auto i: ends)
						increaseLocation(o_code, i, o_code.size());
					outs = 1;
				}
				else
				{
					auto it = c_instructions.find(t);
					if (it != c_instructions.end())
					{
						if (exec)
						{
							vector<pair<bytes, vector<unsigned>>> codes(1);
							int totalArgs = 0;
							while (d != e)
							{
								int o = compileLispFragment(d, e, _quiet, codes.back().first, codes.back().second, _vars);
								if (o < 1)
									break;
								codes.push_back(pair<bytes, vector<unsigned>>());
								totalArgs += o;
							}
							int ea = c_instructionInfo.at(it->second).args;
							if ((ea >= 0 && totalArgs != ea) || (ea < 0 && totalArgs < -ea))
							{
								cwarn << "Expected " << (ea < 0 ? "at least" : "exactly") << abs(ea) << "arguments to operation" << t << "; got" << totalArgs << ".";
								break;
							}

							for (auto it = codes.rbegin(); it != codes.rend(); ++it)
								appendCode(o_code, o_locs, it->first, it->second);
							o_code.push_back((byte)it->second);
							outs = c_instructionInfo.at(it->second).ret;
						}
						else
						{
							o_code.push_back((byte)Instruction::PUSH1);
							o_code.push_back((byte)it->second);
							outs = 1;
						}
					}
					else
					{
						auto it = c_arith.find(t);
						if (it != c_arith.end())
						{
							vector<pair<bytes, vector<unsigned>>> codes(1);
							int totalArgs = 0;
							while (d != e)
							{
								int o = compileLispFragment(d, e, _quiet, codes.back().first, codes.back().second, _vars);
								if (o < 1)
									break;
								codes.push_back(pair<bytes, vector<unsigned>>());
								totalArgs += o;
							}
							codes.pop_back();
							if (!totalArgs)
							{
								cwarn << "Expected at least one argument to operation" << t;
								break;
							}
							for (auto jt = codes.rbegin(); jt != codes.rend(); ++jt)
								appendCode(o_code, o_locs, jt->first, jt->second);
							o_code.push_back((byte)it->second);
							outs = 1;
						}
						else
						{
							auto it = c_binary.find(t);
							if (it != c_binary.end())
							{
								vector<pair<bytes, vector<unsigned>>> codes(1);
								int totalArgs = 0;
								while (d != e)
								{
									int o = compileLispFragment(d, e, _quiet, codes.back().first, codes.back().second, _vars);
									if (o < 1)
										break;
									codes.push_back(pair<bytes, vector<unsigned>>());
									totalArgs += o;
								}
								codes.pop_back();
//								int i = (int)codes.size();
								if (totalArgs != 2)
								{
									cwarn << "Expected two arguments to binary operator" << t << "; got" << totalArgs << ".";
									break;
								}
								for (auto jt = codes.rbegin(); jt != codes.rend(); ++jt)
									appendCode(o_code, o_locs, jt->first, jt->second);
								if (it->second.second)
									o_code.push_back((byte)Instruction::NOT);
								o_code.push_back((byte)it->second.first);
								outs = 1;
							}
							else
							{
								auto it = c_unary.find(t);
								if (it != c_unary.end())
								{
									vector<pair<bytes, vector<unsigned>>> codes(1);
									int totalArgs = 0;
									while (d != e)
									{
										int o = compileLispFragment(d, e, _quiet, codes.back().first, codes.back().second, _vars);
										if (o == -1)
											break;
										totalArgs += o;
										codes.push_back(pair<bytes, vector<unsigned>>());
									}
									codes.pop_back();
//									int i = (int)codes.size();
									if (totalArgs != 1)
									{
										cwarn << "Expected one argument to unary operator" << t << "; got" << totalArgs << ".";
										break;
									}
									for (auto it = codes.rbegin(); it != codes.rend(); ++it)
										appendCode(o_code, o_locs, it->first, it->second);
									o_code.push_back((byte)it->second);
									outs = 1;
								}
								else
								{
									auto it = _vars.find(t);
									if (it == _vars.end())
									{
										bool ok;
										tie(it, ok) = _vars.insert(make_pair(t, _vars.size() * 32));
									}
									pushLiteral(o_code, it->second);
									outs = 1;
									// happens when it's an actual literal, escapes with -1 :-(
								}
							}
						}
					}
				}
			}

			if (!exec)
				return outs;
		}
		}
	}
	return -1;
}
Пример #6
0
void sfx::do_footstep() {
    end_sfx_timestamp = std::chrono::high_resolution_clock::now();
    sfx_time = end_sfx_timestamp - start_sfx_timestamp;
    if( std::chrono::duration_cast<std::chrono::milliseconds> ( sfx_time ).count() > 400 ) {
        int heard_volume = sfx::get_heard_volume( g->u.pos() );
        const auto terrain = g->m.ter_at( g->u.pos() ).id.str();
        static std::set<ter_type> const grass = {
            ter_type( "t_grass" ),
            ter_type( "t_shrub" ),
            ter_type( "t_underbrush" ),
        };
        static std::set<ter_type> const dirt = {
            ter_type( "t_dirt" ),
            ter_type( "t_sand" ),
            ter_type( "t_dirtfloor" ),
            ter_type( "t_palisade_gate_o" ),
            ter_type( "t_sandbox" ),
        };
        static std::set<ter_type> const metal = {
            ter_type( "t_ov_smreb_cage" ),
            ter_type( "t_metal_floor" ),
            ter_type( "t_grate" ),
            ter_type( "t_bridge" ),
            ter_type( "t_elevator" ),
            ter_type( "t_guardrail_bg_dp" ),
        };
        static std::set<ter_type> const water = {
            ter_type( "t_water_sh" ),
            ter_type( "t_water_dp" ),
            ter_type( "t_swater_sh" ),
            ter_type( "t_swater_dp" ),
            ter_type( "t_water_pool" ),
            ter_type( "t_sewage" ),
        };
        static std::set<ter_type> const chain_fence = {
            ter_type( "t_chainfence_h" ),
            ter_type( "t_chainfence_v" ),
        };
        if( !g->u.wearing_something_on( bp_foot_l ) ) {
            play_variant_sound( "plmove", "walk_barefoot", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else if( grass.count( terrain ) > 0 ) {
            play_variant_sound( "plmove", "walk_grass", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else if( dirt.count( terrain ) > 0 ) {
            play_variant_sound( "plmove", "walk_dirt", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else if( metal.count( terrain ) > 0 ) {
            play_variant_sound( "plmove", "walk_metal", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else if( water.count( terrain ) > 0 ) {
            play_variant_sound( "plmove", "walk_water", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else if( chain_fence.count( terrain ) > 0 ) {
            play_variant_sound( "plmove", "clear_obstacle", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        } else {
            play_variant_sound( "plmove", "walk_tarmac", heard_volume, 0, 0.8, 1.2 );
            start_sfx_timestamp = std::chrono::high_resolution_clock::now();
            return;
        }
    }
}
Пример #7
0
void ViewController::cut()
{
  cout << "Image is " << img_.rows << " rows and " << img_.cols << " cols." << endl;

  HighResTimer hrt("Graph setup");
  hrt.start();

  // -- Put image data into the graph.
  CutSegment graph(img_.cols, img_.rows);
  int num_nodes = img_.rows * img_.cols;
  uchar rchan[num_nodes];
  uchar gchan[num_nodes];
  uchar bchan[num_nodes];
  uchar gray[num_nodes];
  int idx = 0;
  for(int y = 0; y < img_.rows; ++y) {
    for(int x = 0; x < img_.cols; ++x) {
      bchan[idx] = img_.at<cv::Vec3b>(y, x)[0];
      gchan[idx] = img_.at<cv::Vec3b>(y, x)[1];
      rchan[idx] = img_.at<cv::Vec3b>(y, x)[2];
      gray[idx] = img_.at<cv::Vec3b>(y, x)[2];

      ++idx;
    }
  }
  //graph.setImageData(rchan, gchan, bchan);
  graph.setImageData(gray);

  // -- Put seed labels into the graph.
  uchar unl = 0;
  uchar source_id = 1;
  uchar sink_id = 2;
  uchar mask[num_nodes];
  idx = 0;
  for(int y = 0; y < img_.rows; ++y) { 
    for(int x = 0; x < img_.cols; ++x) {
      if(source_points_.count(pair<int, int>(y, x)))
        mask[idx] = source_id;
      else if(sink_points_.count(pair<int, int>(y, x)))
        mask[idx] = sink_id;
      else
        mask[idx] = unl;

      ++idx;
    }
  }
  graph.setSourceSink(mask, source_id, sink_id);

  hrt.stop();
  cout << hrt.reportMilliseconds() << endl;
  
  hrt.reset("planar cut");
  hrt.start();
  graph.segment();
  hrt.stop();
  cout << hrt.reportMilliseconds() << endl;

  cv::Mat output = img_.clone();
  for(int y = 0; y < output.rows; ++y) {
    for(int x = 0; x < output.cols; ++x) {
      if(graph.getLabel(y, x) == CutPlanar::LABEL_SOURCE)
        output.at<cv::Vec3b>(y, x) = img_.at<cv::Vec3b>(y, x);
      else if(graph.getLabel(y, x) == CutPlanar::LABEL_SINK)
        output.at<cv::Vec3b>(y, x) = cv::Vec3b(0, 0, 0);
      else
        output.at<cv::Vec3b>(y, x) = cv::Vec3b(0, 0, 255);
    }
  }

  cv::imshow("output", output);
  view_.cvWaitKey(0);
  cv::destroyWindow("output");
}
Пример #8
0
 bool symbolExistsInSearchPath(const std::string& symbol,
                               const std::set<std::string>& searchPathObjects) const
 {
    return searchPathObjects.count(symbol) != 0;
 }
Пример #9
0
void AudioKaraoke::OnFileChanged(int type, std::set<const AssEntry *> const& changed) {
	if (enabled && (type & AssFile::COMMIT_DIAG_FULL) && (changed.empty() || changed.count(active_line))) {
		LoadFromLine();
		split_area->Refresh(false);
	}
}
Пример #10
0
void ammo_effects(int x, int y, const std::set<std::string> &effects)
{
    if (effects.count("EXPLOSIVE")) {
        g->explosion(x, y, 24, 0, false);
    }

    if (effects.count("FRAG")) {
        g->explosion(x, y, 12, 28, false);
    }

    if (effects.count("NAPALM")) {
        g->explosion(x, y, 18, 0, true);
    }

    if (effects.count("NAPALM_BIG")) {
        g->explosion(x, y, 72, 0, true);
    }

    if (effects.count("MININUKE_MOD")) {
        g->explosion(x, y, 300, 0, false);
        int junk;
        for (int i = -6; i <= 6; i++) {
            for (int j = -6; j <= 6; j++) {
                if (g->m.sees(x, y, x + i, y + j, 3, junk) &&
                    g->m.move_cost(x + i, y + j) > 0) {
                    g->m.add_field(x + i, y + j, fd_nuke_gas, 3);
                }
            }
        }
    }

    if (effects.count("ACIDBOMB")) {
        for (int i = x - 1; i <= x + 1; i++) {
            for (int j = y - 1; j <= y + 1; j++) {
                g->m.add_field(i, j, fd_acid, 3);
            }
        }
    }

    if (effects.count("EXPLOSIVE_BIG")) {
        g->explosion(x, y, 40, 0, false);
    }

    if (effects.count("EXPLOSIVE_HUGE")) {
        g->explosion(x, y, 80, 0, false);
    }

    if (effects.count("TEARGAS")) {
        for (int i = -2; i <= 2; i++) {
            for (int j = -2; j <= 2; j++) {
                g->m.add_field(x + i, y + j, fd_tear_gas, 3);
            }
        }
    }

    if (effects.count("SMOKE")) {
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                g->m.add_field(x + i, y + j, fd_smoke, 3);
            }
        }
    }
    if (effects.count("SMOKE_BIG")) {
        for (int i = -6; i <= 6; i++) {
            for (int j = -6; j <= 6; j++) {
                g->m.add_field(x + i, y + j, fd_smoke, 18);
            }
        }
    }

    if (effects.count("FLASHBANG")) {
        g->flashbang(x, y);
    }

    if (effects.count("FLAME")) {
        g->explosion(x, y, 4, 0, true);
    }

    if (effects.count("FLARE")) {
        g->m.add_field(x, y, fd_fire, 1);
    }

    if (effects.count("LIGHTNING")) {
        for (int i = x - 1; i <= x + 1; i++) {
            for (int j = y - 1; j <= y + 1; j++) {
                g->m.add_field(i, j, fd_electricity, 3);
            }
        }
    }

    if (effects.count("PLASMA")) {
        for (int i = x - 1; i <= x + 1; i++) {
            for (int j = y - 1; j <= y + 1; j++) {
                if (one_in(2)) {
                    g->m.add_field(i, j, fd_plasma, rng(2, 3));
                }
            }
        }
    }

}
Пример #11
0
void DoReboot(unsigned int cmd, const std::string& reason, const std::string& rebootTarget,
              bool runFsck) {
    Timer t;
    LOG(INFO) << "Reboot start, reason: " << reason << ", rebootTarget: " << rebootTarget;

    android::base::WriteStringToFile(StringPrintf("%s\n", reason.c_str()), LAST_REBOOT_REASON_FILE,
                                     S_IRUSR | S_IWUSR, AID_SYSTEM, AID_SYSTEM);

    bool is_thermal_shutdown = false;
    if (cmd == ANDROID_RB_THERMOFF) {
        is_thermal_shutdown = true;
        runFsck = false;
    }

    auto shutdown_timeout = 0ms;
    if (!SHUTDOWN_ZERO_TIMEOUT) {
        if (is_thermal_shutdown) {
            constexpr unsigned int thermal_shutdown_timeout = 1;
            shutdown_timeout = std::chrono::seconds(thermal_shutdown_timeout);
        } else {
            constexpr unsigned int shutdown_timeout_default = 6;
            auto shutdown_timeout_property = android::base::GetUintProperty(
                "ro.build.shutdown_timeout", shutdown_timeout_default);
            shutdown_timeout = std::chrono::seconds(shutdown_timeout_property);
        }
    }
    LOG(INFO) << "Shutdown timeout: " << shutdown_timeout.count() << " ms";

    // keep debugging tools until non critical ones are all gone.
    const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
    // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
    const std::set<std::string> to_starts{"watchdogd"};
    ServiceManager::GetInstance().ForEachService([&kill_after_apps, &to_starts](Service* s) {
        if (kill_after_apps.count(s->name())) {
            s->SetShutdownCritical();
        } else if (to_starts.count(s->name())) {
            s->Start();
            s->SetShutdownCritical();
        } else if (s->IsShutdownCritical()) {
            s->Start();  // start shutdown critical service if not started
        }
    });

    Service* bootAnim = ServiceManager::GetInstance().FindServiceByName("bootanim");
    Service* surfaceFlinger = ServiceManager::GetInstance().FindServiceByName("surfaceflinger");
    if (bootAnim != nullptr && surfaceFlinger != nullptr && surfaceFlinger->IsRunning()) {
        ServiceManager::GetInstance().ForEachServiceInClass("animation", [](Service* s) {
            s->SetShutdownCritical();  // will not check animation class separately
        });
    }

    // optional shutdown step
    // 1. terminate all services except shutdown critical ones. wait for delay to finish
    if (shutdown_timeout > 0ms) {
        LOG(INFO) << "terminating init services";

        // Ask all services to terminate except shutdown critical ones.
        ServiceManager::GetInstance().ForEachService([](Service* s) {
            if (!s->IsShutdownCritical()) s->Terminate();
        });

        int service_count = 0;
        // Only wait up to half of timeout here
        auto termination_wait_timeout = shutdown_timeout / 2;
        while (t.duration() < termination_wait_timeout) {
            ServiceManager::GetInstance().ReapAnyOutstandingChildren();

            service_count = 0;
            ServiceManager::GetInstance().ForEachService([&service_count](Service* s) {
                // Count the number of services running except shutdown critical.
                // Exclude the console as it will ignore the SIGTERM signal
                // and not exit.
                // Note: SVC_CONSOLE actually means "requires console" but
                // it is only used by the shell.
                if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
                    service_count++;
                }
            });

            if (service_count == 0) {
                // All terminable services terminated. We can exit early.
                break;
            }

            // Wait a bit before recounting the number or running services.
            std::this_thread::sleep_for(50ms);
        }
        LOG(INFO) << "Terminating running services took " << t
                  << " with remaining services:" << service_count;
    }

    // minimum safety steps before restarting
    // 2. kill all services except ones that are necessary for the shutdown sequence.
    ServiceManager::GetInstance().ForEachService([](Service* s) {
        if (!s->IsShutdownCritical()) s->Stop();
    });
    ServiceManager::GetInstance().ReapAnyOutstandingChildren();

    // 3. send volume shutdown to vold
    Service* voldService = ServiceManager::GetInstance().FindServiceByName("vold");
    if (voldService != nullptr && voldService->IsRunning()) {
        ShutdownVold();
        voldService->Stop();
    } else {
        LOG(INFO) << "vold not running, skipping vold shutdown";
    }
    // logcat stopped here
    ServiceManager::GetInstance().ForEachService([&kill_after_apps](Service* s) {
        if (kill_after_apps.count(s->name())) s->Stop();
    });
    // 4. sync, try umount, and optionally run fsck for user shutdown
    sync();
    UmountStat stat = TryUmountAndFsck(runFsck, shutdown_timeout - t.duration());
    // Follow what linux shutdown is doing: one more sync with little bit delay
    sync();
    if (!is_thermal_shutdown) std::this_thread::sleep_for(100ms);
    LogShutdownTime(stat, &t);
    // Reboot regardless of umount status. If umount fails, fsck after reboot will fix it.
    RebootSystem(cmd, rebootTarget);
    abort();
}
Пример #12
0
		virtual Json::Value run(int key, int pid, int sid, const Json::Value &submission)
		{
#ifdef DEBUG
			std::clog << "run" << std::endl;
			std::clog << " pid=" << pid << " sid=" << sid << " key=" << key << std::endl;
#endif
			pthread_mutex_lock(&cntLock);
			if (!boardingPass.count(key))
			{
				pthread_mutex_unlock(&cntLock);
				Json::Value ret;
				ret["error"] = "not preserved";
				return ret;
			}
			boardingPass.erase(boardingPass.find(key));
			runningCnt++, totCnt++;
			const int _totCnt_ = totCnt;
			pthread_mutex_unlock(&cntLock);
			
			Json::Value ret;
			std::ostringstream ss;
			ss << runPath << "/" << _totCnt_;
			std::string runDir = ss.str();
			pthread_mutex_lock(&cmdLock);
#ifdef DEBUG
			std::clog << "mkdir -p "+runDir << std::endl;
#endif
			system(("mkdir -p "+runDir).c_str());
#ifdef DEBUG
			std::clog << "rm -r "+runDir+"/*" << std::endl;
#endif
			system(("rm -r "+runDir+"/*").c_str());
			pthread_mutex_unlock(&cmdLock);
			try
			{
				ss.str("");
				ss << "cp " + dataPath + "/" << pid << "/* " << runDir;
				pthread_mutex_lock(&syncLock);
				if (syncing.count(pid)) pthread_mutex_unlock(&syncLock), throw std::string("data updated when copying files.");
#ifdef DEBUG
				std::clog << ss.str() << std::endl;
#endif
				pthread_mutex_lock(&cmdLock), system(ss.str().c_str()), pthread_mutex_unlock(&cmdLock);
				pthread_mutex_unlock(&syncLock);
				ss.str("");
				ss << "cp " + sourcePath + "/" << sid/10000 << '/' << sid%10000 << "/* " << runDir;
#ifdef DEBUG
				std::clog << ss.str() << std::endl;
#endif
				pthread_mutex_lock(&cmdLock), system((ss.str()).c_str()), pthread_mutex_unlock(&cmdLock);
				ss.str("");
				ss << "./yauj_judge run";
				for (Json::Value::const_iterator i=submission.begin(); i!=submission.end(); i++)
					ss << " " << (*i)["language"].asString() << " " << (*i)["source"].asString();
				ret=dumpCmd(ss.str(),runDir);
#ifndef NCLEAN
				pthread_mutex_lock(&cmdLock), system(("rm -r "+runDir).c_str()), pthread_mutex_unlock(&cmdLock);
#endif
			} catch (std::string &e)
			{
#ifdef DEBUG
				std::clog << " run: catched " << e << std::endl;
#endif
				pthread_mutex_lock(&cntLock);
				runningCnt--, preserveCnt--;
				pthread_mutex_unlock(&cntLock);
				ret["error"] = e;
				return ret;
			}
			pthread_mutex_lock(&cntLock);
			runningCnt--, preserveCnt--;
			pthread_mutex_unlock(&cntLock);
			return ret;
		}
Пример #13
0
 void visitCallImport(CallImport *curr) {
   auto name = curr->target;
   if (visitedTargets.count(name) > 0) return;
   visitedTargets.insert(name);
   std::cout << "  \"" << currFunction->name << "\" -> \"" << name << "\"; // callImport\n";
 }
Пример #14
0
 void visitCall(Call *curr) {
   auto* target = module->getFunction(curr->target);
   if (visitedTargets.count(target->name) > 0) return;
   visitedTargets.insert(target->name);
   std::cout << "  \"" << currFunction->name << "\" -> \"" << target->name << "\"; // call\n";
 }
Пример #15
0
 bool convert(const std::string& method, const std::string& name) {
     return (membersByName.count(std::make_pair(method, name)) > 0);
 }
Пример #16
0
void getUnclosedNeighbours(cell current,tilemap& t_map,std::set<cell >& closed,std::set<cell >& neighbours)
{
	int height = 0;
	int width  = 0;

	int x = current.first;
	int y = current.second;

	height = t_map.size();
	width  = t_map[0].size();
	neighbours.clear();
	
	switch(t_map[y][x])
	{
		case model::VERTICAL:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x,y+1));
			break;
		}
		case model::HORIZONTAL:{
			neighbours.insert(cell(x+1,y));
			neighbours.insert(cell(x-1,y));
			break;
		}
		case model::LEFT_TOP_CORNER:{
			neighbours.insert(cell(x,y+1));
			neighbours.insert(cell(x+1,y));
			break;
		}
		case model::RIGHT_TOP_CORNER:{
			neighbours.insert(cell(x-1,y));
			neighbours.insert(cell(x,y+1));
			break;
		}
		case model::LEFT_BOTTOM_CORNER:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x+1,y));
			break;
		}
		case model::RIGHT_BOTTOM_CORNER:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x-1,y));
			break;
		}
		case model::LEFT_HEADED_T:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x,y+1));
			neighbours.insert(cell(x-1,y));
			break;
		}
		case model::RIGHT_HEADED_T:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x,y+1));
			neighbours.insert(cell(x+1,y));
			break;
		}
		case model::TOP_HEADED_T:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x+1,y));
			neighbours.insert(cell(x-1,y));
			break;
		}
		case model::BOTTOM_HEADED_T:{
			neighbours.insert(cell(x,y+1));
			neighbours.insert(cell(x+1,y));
			neighbours.insert(cell(x-1,y));
			break;
		}	
		case model::CROSSROADS:{
			neighbours.insert(cell(x,y-1));
			neighbours.insert(cell(x,y+1));
			neighbours.insert(cell(x+1,y));
			neighbours.insert(cell(x-1,y));
			break;
		}	
		default:{
			break;
		}	
	}

	for(auto it = neighbours.begin();it != neighbours.end();it++)
	{
		if( it->first >= width || it->first < 0){ neighbours.erase(*it);continue; }
		if( it->second >= height || it->second < 0){ neighbours.erase(*it);continue; }
		if(t_map[it->second][it->first] == model::_UNKNOWN_TILE_TYPE_){ neighbours.erase(*it); }
		if(t_map[it->second][it->first] == model::EMPTY){ neighbours.erase(*it); }
		if(closed.count(*it) > 0){ neighbours.erase(*it); }
	}

	return;
}
Пример #17
0
void apply_ammo_effects( const tripoint &p, const std::set<std::string> &effects )
{
    if( effects.count( "EXPLOSIVE_SMALL" ) > 0 ) {
        g->explosion( p, 24, 0.4 );
    }

    if( effects.count( "EXPLOSIVE" ) > 0 ) {
        g->explosion( p, 24 );
    }

    if( effects.count( "FRAG" ) > 0 ) {
        explosion_data frag;
        frag.power = 1.0f;
        frag.shrapnel.count = 50;
        frag.shrapnel.mass = 5;
        frag.shrapnel.recovery = 100;
        frag.shrapnel.drop = "shrapnel";
        g->explosion( p, frag );
    }

    if( effects.count( "NAPALM" ) > 0 ) {
        g->explosion( p, 4, 0.7, true );
        // More intense fire near the center
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "NAPALM_BIG" ) > 0 ) {
        g->explosion( p, 24, 0.8, true );
        // More intense fire near the center
        for( auto &pt : g->m.points_in_radius( p, 3, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "MININUKE_MOD" ) > 0 ) {
        g->explosion( p, 450 );
        for( auto &pt : g->m.points_in_radius( p, 6, 0 ) ) {
            if( g->m.sees( p, pt, 3 ) &&
                g->m.passable( pt ) ) {
                g->m.add_field( pt, fd_nuke_gas, 3, 0 );
            }
        }
    }

    if( effects.count( "ACIDBOMB" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_acid, 3, 0 );
        }
    }


    if( effects.count( "EXPLOSIVE_BIG" ) > 0 ) {
        g->explosion( p, 40 );
    }

    if( effects.count( "EXPLOSIVE_HUGE" ) > 0 ) {
        g->explosion( p, 80 );
    }

    if( effects.count( "TOXICGAS" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_toxic_gas, 3, 0 );
        }
    }
    if( effects.count( "GAS_FUNGICIDAL" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fungicidal_gas, 3, 0 );
        }
    }
    if( effects.count( "SMOKE" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_smoke, MAX_FIELD_DENSITY );
        }
    }
    if( effects.count( "SMOKE_BIG" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 6, 0 ) ) {
            g->m.add_field( pt, fd_smoke, MAX_FIELD_DENSITY );
        }
    }

    if( effects.count( "FLASHBANG" ) ) {
        g->flashbang( p );
    }

    if( effects.count( "EMP" ) ) {
        g->emp_blast( p );
    }

    if( effects.count( "NO_BOOM" ) == 0 && effects.count( "FLAME" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "FLARE" ) > 0 ) {
        g->m.add_field( p, fd_fire, 1, 0 );
    }

    if( effects.count( "LIGHTNING" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_electricity, 3, 0 );
        }
    }

    if( effects.count( "PLASMA" ) > 0 ) {
        for( auto &pt : g->m.points_in_radius( p, 1, 0 ) ) {
            if( one_in( 2 ) ) {
                g->m.add_field( pt, fd_plasma, rng( 2, 3 ), 0 );
            }
        }
    }
}
// Test multiple master nodes that disagree about set membership
TEST(ReplicaSetMonitorTests, MultipleMastersDisagree) {
    SetStatePtr state = boost::make_shared<SetState>("name", basicSeedsSet);
    Refresher refresher(state);

    BSONArray hostsForSeed[3];
    hostsForSeed[0] = BSON_ARRAY("a" << "b" << "c" << "d");
    hostsForSeed[1] = BSON_ARRAY("a" << "b" << "c" << "e");
    hostsForSeed[2] = hostsForSeed[0];

    set<HostAndPort> seen;

    for (size_t i = 0; i != basicSeeds.size(); ++i) {
        NextStep ns = refresher.getNextStep();
        ASSERT_EQUALS(ns.step, NextStep::CONTACT_HOST);
        ASSERT(basicSeedsSet.count(ns.host));
        ASSERT(!seen.count(ns.host));
        seen.insert(ns.host);
    }

    const ReadPreferenceSetting primaryOnly(ReadPreference_PrimaryOnly, TagSet());

    // mock all replies
    for (size_t i = 0; i != basicSeeds.size(); ++i) {
        refresher.receivedIsMaster(basicSeeds[i], -1, BSON(
                                       "setName" << "name"
                                       << "ismaster" << true
                                       << "secondary" << false
                                       << "hosts" << hostsForSeed[i % 2]
                                       << "ok" << true
                                   ));

        // Ensure the primary is the host we just got a reply from
        HostAndPort currentPrimary = state->getMatchingHost(primaryOnly);
        ASSERT_EQUALS(currentPrimary.host(), basicSeeds[i].host());

        // Ensure each primary discovered becomes source of truth
        if (i == 1) {
            // "b" thinks node "e" is a member but "d" is not
            ASSERT(state->findNode(HostAndPort("e")));
            ASSERT(!state->findNode(HostAndPort("d")));
        }
        else {
            // "a" and "c" think node "d" is a member but "e" is not
            ASSERT(state->findNode(HostAndPort("d")));
            ASSERT(!state->findNode(HostAndPort("e")));
        }
    }

    // next step should be to contact "d"
    NextStep ns = refresher.getNextStep();
    ASSERT_EQUALS(ns.step, NextStep::CONTACT_HOST);
    ASSERT_EQUALS(ns.host.host(), "d");
    seen.insert(ns.host);

    // reply from "d"
    refresher.receivedIsMaster(HostAndPort("d"), -1, BSON(
                                   "setName" << "name"
                                   << "ismaster" << false
                                   << "secondary" << true
                                   << "hosts" << hostsForSeed[0]
                                   << "ok" << true
                               ));

    // scan should be complete
    ns = refresher.getNextStep();
    ASSERT_EQUALS(ns.step, NextStep::DONE);
    ASSERT(ns.host.empty());

    // Validate final state (only "c" should be master and "d" was added)
    ASSERT_EQUALS(state->nodes.size(), basicSeeds.size() + 1);

    std::vector<Node> nodes = state->nodes;
    for (std::vector<Node>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
        const Node& node = *it;
        ASSERT(node.isUp);
        ASSERT_EQUALS(node.isMaster, node.host.host() == "c");
        ASSERT(seen.count(node.host));
    }
}
Пример #19
0
    // Returns:
    //   false - invalid move tx
    //   true  - non-move tx or valid tx
    bool IsValid(const CTransaction& tx, Move &outMove)
    {
        if (tx.nVersion != NAMECOIN_TX_VERSION)
          return true;

        std::vector<vchType> vvchArgs;
        int op, nOut;
        if (!DecodeNameTx (tx, op, nOut, vvchArgs))
          return error ("GameStepValidator: could not decode a name tx");

        vchType vchName, vchValue;
        switch (op)
        {
        case OP_NAME_FIRSTUPDATE:
          vchName = vvchArgs[0];
          vchValue = vvchArgs[2];
          break;

        case OP_NAME_UPDATE:
          vchName = vvchArgs[0];
          vchValue = vvchArgs[1];
          break;

        case OP_NAME_NEW:
          return true;

        default:
          return error ("GameStepValidator: invalid name tx found");
        }

        const std::string sName = stringFromVch(vchName);
        const std::string sValue = stringFromVch(vchValue);
        if (dup.count(sName))
            return error ("GameStepValidator: duplicate player name %s",
                          sName.c_str ());
        dup.insert(sName);

        Move m;
        m.Parse(sName, sValue);
        if (!m)
            return error("GameStepValidator: cannot parse move %s for player %s", sValue.c_str(), sName.c_str());
        if (!m.IsValid(*pstate))
            return error("GameStepValidator: invalid move for the game state: move %s for player %s", sValue.c_str(), sName.c_str());

        /* If this is a spawn move, find out the coin's value and set
           the spawned player's value to it.  */
        if (m.IsSpawn ())
          {
            if (op != OP_NAME_FIRSTUPDATE)
              return error ("GameStepValidator: spawn is not firstupdate");

            m.coinAmount = tx.vout[nOut].nValue;
          }
        else if (op != OP_NAME_UPDATE)
          return error ("GameStepValidator: name_firstupdate is not spawn");

        std::string addressLock = m.AddressOperationPermission(*pstate);
        if (!addressLock.empty())
        {
            // If one of inputs has address equal to addressLock, then that input has been signed by the address owner
            // and thus authorizes the address change operation
            bool found = false;
            if (!pdbset)
            {
                pdbset = new DatabaseSet("r");
                fOwnDb = true;
            }
            for (int i = 0; i < tx.vin.size(); i++)
            {
                COutPoint prevout = tx.vin[i].prevout;
                CTransaction txPrev;
                CTxIndex txindex;
                if (!pdbset->tx ().ReadTxIndex (prevout.hash, txindex)
                    || txindex.pos == CDiskTxPos(1,1,1))
                    continue;
                else if (!txPrev.ReadFromDisk(txindex.pos))
                    continue;
                if (prevout.n >= txPrev.vout.size())
                    continue;
                const CTxOut &vout = txPrev.vout[prevout.n];
                std::string address;
                if (ExtractDestination(vout.scriptPubKey, address) && address == addressLock)
                {
                    found = true;
                    break;
                }
            }
            if (!found)
                return error("GameStepValidator: address operation permission denied: move %s for player %s", sValue.c_str(), sName.c_str());
        }
        outMove = m;
        return true;
    }
// Stale Primary with obsolete electionId
TEST(ReplicaSetMonitorTests, StalePrimaryWithObsoleteElectionId) {
    SetStatePtr state = boost::make_shared<SetState>("name", basicSeedsSet);
    Refresher refresher(state);

    const OID firstElectionId = OID::gen();
    const OID secondElectionId = OID::gen();

    set<HostAndPort> seen;

    // contact first host claiming to be primary with greater electionId
    {
        NextStep ns = refresher.getNextStep();
        ASSERT_EQUALS(ns.step, NextStep::CONTACT_HOST);
        ASSERT(basicSeedsSet.count(ns.host));
        ASSERT(!seen.count(ns.host));
        seen.insert(ns.host);

        refresher.receivedIsMaster(ns.host,
                                   -1,
                                   BSON("setName" << "name"
                                        << "ismaster" << true
                                        << "secondary" << false
                                        << "electionId" << secondElectionId
                                        << "hosts" << BSON_ARRAY("a" << "b" << "c")
                                        << "ok" << true));

        Node* node = state->findNode(ns.host);
        ASSERT(node);
        ASSERT_TRUE(node->isMaster);
        ASSERT_EQUALS(state->maxElectionId, secondElectionId);
    }

    // contact second host claiming to be primary with smaller electionId
    {
        NextStep ns = refresher.getNextStep();
        ASSERT_EQUALS(ns.step, NextStep::CONTACT_HOST);
        ASSERT(basicSeedsSet.count(ns.host));
        ASSERT(!seen.count(ns.host));
        seen.insert(ns.host);

        refresher.receivedIsMaster(ns.host,
                                   -1,
                                   BSON("setName" << "name"
                                        << "ismaster" << true
                                        << "secondary" << false
                                        << "electionId" << firstElectionId
                                        << "hosts" << BSON_ARRAY("a" << "b" << "c")
                                        << "ok" << true));

        Node* node = state->findNode(ns.host);
        ASSERT(node);
        // The SetState shouldn't see this host as master
        ASSERT_FALSE(node->isMaster);
        // the max electionId should remain the same
        ASSERT_EQUALS(state->maxElectionId, secondElectionId);
    }

    // third host is a secondary
    {
        NextStep ns = refresher.getNextStep();
        ASSERT_EQUALS(ns.step, NextStep::CONTACT_HOST);
        ASSERT(basicSeedsSet.count(ns.host));
        ASSERT(!seen.count(ns.host));
        seen.insert(ns.host);

        refresher.receivedIsMaster(ns.host,
                                   -1,
                                   BSON("setName" << "name"
                                        << "ismaster" << false
                                        << "secondary" << true
                                        << "hosts" << BSON_ARRAY("a" << "b" << "c")
                                        << "ok" << true));

        Node* node = state->findNode(ns.host);
        ASSERT(node);
        ASSERT_FALSE(node->isMaster);
        // the max electionId should remain the same
        ASSERT_EQUALS(state->maxElectionId, secondElectionId);
    }

    // Now all hosts have returned data
    NextStep ns = refresher.getNextStep();
    ASSERT_EQUALS(ns.step, NextStep::DONE);
    ASSERT(ns.host.empty());
}
Пример #21
0
//--------------------------------------------------------------------------------------------------------算法函数实现
void Dijkstra(const Graph & graph, const EdgeInfoDict & edgeInfoDict,int source, ShortestPathDict & pathDict,const std::set<int> & withoutPoint) {


    std::set<int> processed;        // 已处理过的结点
    std::set<Candidate> candidates; // 待处理的结点, 配合上Candidate的定义, 这便是一个小顶堆

    // 算法初始化, 起点加入processed集合, 起点的邻接点加入candidates集合
    processed.insert(source);
    Graph::const_iterator pSourceAdjs = graph.find(source);         // 指向graph[source]的迭代器
    if(pSourceAdjs != graph.end()) {                                // 这是一个肯定会满足的条件, 除非source结点不在图中
        const std::set<int> & sourceAdjs = pSourceAdjs->second;
        for(std::set<int>::const_iterator iter = sourceAdjs.begin(); iter != sourceAdjs.end(); ++iter) {
            // 排除必须要排除的点
            if(withoutPoint.count(*iter))
                continue;

            EdgeInfoDict::const_iterator pEdgeInfo = edgeInfoDict.find(Edge(source, *iter));
            if(pEdgeInfo != edgeInfoDict.end()) {
                Candidate candidate;
                candidate.nodeNo = *iter;
                const EdgeInfo & edgeInfo = pEdgeInfo->second;
                candidate.edgePath.push_back(edgeInfo.first);
                candidate.nodePath.push_back(source);
                candidate.pathCost = edgeInfo.second;
                candidates.insert(candidate);
            }
        }
    }

    // 算法主体开始
    // 第一步: 从候选区挑一个最佳结点, 加入processed集合中去
    // 第二步: 访问最佳结点的所有邻接点, 刷新或扩充候选人集合
    while(!candidates.empty()) {
        // 取出候选区最近的结点, 加入已处理集合中, 并将该结点当前的路径存储到最短路径字典中
        Candidate bestCandidate = *(candidates.begin());
        candidates.erase(bestCandidate);
        processed.insert(bestCandidate.nodeNo);
        Path path;
        path.first = bestCandidate.pathCost;
        path.second.first = bestCandidate.nodePath;
        path.second.second = bestCandidate.edgePath;
        pathDict[std::pair<int, int>(source, bestCandidate.nodeNo)] = path;

        // 访问最佳候选人的所有邻接点, 以刷新或扩充候选结点
        Graph::const_iterator PBestCandidateAdjs = graph.find(bestCandidate.nodeNo);
        // 如果最佳候选人没有邻接点, 直接开始下一轮循环
        if(PBestCandidateAdjs == graph.end())
            continue;

        const std::set<int> & bestCandidateAdjs = PBestCandidateAdjs->second;
        for(std::set<int>::const_iterator iter = bestCandidateAdjs.begin(); iter != bestCandidateAdjs.end(); ++iter) {
            int adjNode = *iter;
            if(processed.count(adjNode) || withoutPoint.count(adjNode))
                continue;

            Candidate candidate;
            candidate.nodeNo = adjNode;
            candidate.edgePath = bestCandidate.edgePath;
            candidate.nodePath = bestCandidate.nodePath;
            candidate.pathCost = bestCandidate.pathCost;
            EdgeInfoDict::const_iterator PBestCanToCanInfo = edgeInfoDict.find(Edge(bestCandidate.nodeNo, candidate.nodeNo));
            if(PBestCanToCanInfo != edgeInfoDict.end()) {
                const EdgeInfo & edgeBestCanToCanInfo = PBestCanToCanInfo->second;
                candidate.edgePath.push_back(edgeBestCanToCanInfo.first);
                candidate.nodePath.push_back(bestCandidate.nodeNo);
                candidate.pathCost += edgeBestCanToCanInfo.second;
            }

            std::set<Candidate>::iterator temp = candidates.find(candidate);
            if(temp == candidates.end() || (*temp).pathCost > candidate.pathCost){
                // 清除原有记录
                candidates.erase(candidate);
                // 更新记录
                candidates.insert(candidate);
            }
        }
    }
}
bool InstallationTester::isTopLevelSuffix(const FileNameString &fileName)
{
  static std::set<FileNameString> tlSuffixes = { "esp", "esm", "bsa" };
  return tlSuffixes.count(QFileInfo(fileName.toQString()).suffix()) != 0;
}
Пример #23
0
void StageObjectsData::storeFxs(const std::set<TFx *> &fxs, TXsheet *xsh, int fxFlags)
{
	bool doClone = (fxFlags & eDoClone);
	bool resetFxDagPositions = (fxFlags & eResetFxDagPositions);

	TFxSet *terminalFxs = xsh->getFxDag()->getTerminalFxs();

	// Traverse specified fxs
	std::set<TFx *>::const_iterator it;
	for (it = fxs.begin(); it != fxs.end(); ++it) {
		TFx *fxOrig = *it, *fx = fxOrig;

		if (doClone) {
			// If required, clone them
			fx = fxOrig->clone(false);

			fx->setName(fxOrig->getName());
			fx->getAttributes()->setId(fxOrig->getAttributes()->getId());
			fx->getAttributes()->passiveCacheDataIdx() = -1;

			if (resetFxDagPositions)
				fx->getAttributes()->setDagNodePos(TConst::nowhere);
		}

		// Store them (and the original/clone pairing even if not cloning)
		m_fxTable[fxOrig] = fx;
		fx->addRef();
		m_fxs.insert(fx);

		// Find out if the fx is a terminal one in the selection. If so, store it there too.
		bool isTerminal = true;
		if (!terminalFxs->containsFx(fxOrig)) // If it's terminal in the xsheet, no doubt
		{
			// Otherwise, check terminality with respect to the selection
			int i, outputConnectionsCount = fxOrig->getOutputConnectionCount();
			for (i = 0; i < outputConnectionsCount; ++i) {
				TFx *outputFx = fxOrig->getOutputConnection(i)->getOwnerFx();
				if (outputFx && fxs.count(outputFx) > 0) {
					isTerminal = false;
					break;
				}
			}
		}

		// Well, excluding true TOutputFxs...
		TOutputFx *outFx = dynamic_cast<TOutputFx *>(fx);
		if (isTerminal && !outFx) {
			fx->addRef();
			m_terminalFxs.insert(fx);
		}
	}

	// Updating terminality of the column fxs too!
	// WARNING: This requires that storeObjects() is invoked BEFORE this !
	for (it = m_originalColumnFxs.begin(); it != m_originalColumnFxs.end(); ++it) {
		TFx *fxOrig = *it;

		bool isTerminal = true;
		if (!terminalFxs->containsFx(fxOrig)) {
			int i, outputConnectionsCount = fxOrig->getOutputConnectionCount();
			for (i = 0; i < outputConnectionsCount; ++i) {
				TFx *outputFx = fxOrig->getOutputConnection(i)->getOwnerFx();
				if (outputFx && fxs.count(outputFx) > 0) {
					isTerminal = false;
					break;
				}
			}
		}

		if (isTerminal) {
			TFx *fx = m_fxTable[fxOrig];

			fx->addRef();
			m_terminalFxs.insert(fx);
		}
	}

	if (!m_fxTable.empty() && doClone)
		updateFxLinks(m_fxTable); // Apply original/clone pairings
								  // to fx relatives
}
Пример #24
0
bool CzTNXTracker::UpdateStatusInternal(const std::set<uint256>& setMempool, CMintMeta& mint)
{
    //! Check whether this mint has been spent and is considered 'pending' or 'confirmed'
    // If there is not a record of the block height, then look it up and assign it
    uint256 txidMint;
    bool isMintInChain = zerocoinDB->ReadCoinMint(mint.hashPubcoin, txidMint);

    //See if there is internal record of spending this mint (note this is memory only, would reset on restart)
    bool isPendingSpend = static_cast<bool>(mapPendingSpends.count(mint.hashSerial));

    // See if there is a blockchain record of spending this mint
    uint256 txidSpend;
    bool isConfirmedSpend = zerocoinDB->ReadCoinSpend(mint.hashSerial, txidSpend);

    // Double check the mempool for pending spend
    if (isPendingSpend) {
        uint256 txidPendingSpend = mapPendingSpends.at(mint.hashSerial);
        if (!setMempool.count(txidPendingSpend) || isConfirmedSpend) {
            RemovePending(txidPendingSpend);
            isPendingSpend = false;
            LogPrintf("%s : Pending txid %s removed because not in mempool\n", __func__, txidPendingSpend.GetHex());
        }
    }

    bool isUsed = isPendingSpend || isConfirmedSpend;

    if (!mint.nHeight || !isMintInChain || isUsed != mint.isUsed) {
        CTransaction tx;
        uint256 hashBlock;

        // Txid will be marked 0 if there is no knowledge of the final tx hash yet
        if (mint.txid == 0) {
            if (!isMintInChain) {
                LogPrintf("%s : Failed to find mint in zerocoinDB %s\n", __func__, mint.hashPubcoin.GetHex().substr(0, 6));
                mint.isArchived = true;
                Archive(mint);
                return true;
            }
            mint.txid = txidMint;
        }

        if (setMempool.count(mint.txid))
            return true;

        // Check the transaction associated with this mint
        if (!IsInitialBlockDownload() && !GetTransaction(mint.txid, tx, hashBlock, true)) {
            LogPrintf("%s : Failed to find tx for mint txid=%s\n", __func__, mint.txid.GetHex());
            mint.isArchived = true;
            Archive(mint);
            return true;
        }

        // An orphan tx if hashblock is in mapBlockIndex but not in chain active
        if (mapBlockIndex.count(hashBlock) && !chainActive.Contains(mapBlockIndex.at(hashBlock))) {
            LogPrintf("%s : Found orphaned mint txid=%s\n", __func__, mint.txid.GetHex());
            mint.isUsed = false;
            mint.nHeight = 0;
            if (tx.IsCoinStake()) {
                mint.isArchived = true;
                Archive(mint);
            }

            return true;
        }

        // Check that the mint has correct used status
        if (mint.isUsed != isUsed) {
            LogPrintf("%s : Set mint %s isUsed to %d\n", __func__, mint.hashPubcoin.GetHex(), isUsed);
            mint.isUsed = isUsed;
            return true;
        }
    }

    return false;
}
Пример #25
0
void ammo_effects( const tripoint &p, const std::set<std::string> &effects )
{
    if( effects.count( "EXPLOSIVE" ) > 0 ) {
        g->explosion( p, 24, 0, false );
    }

    if( effects.count( "FRAG" ) > 0 ) {
        g->explosion( p, 12, 28, false );
    }

    if( effects.count( "NAPALM" ) > 0 ) {
        g->explosion( p, 4, 0, true );
        // More intense fire near the center
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "NAPALM_BIG" ) > 0 ) {
        g->explosion( p, 48, 0, true );
        // More intense fire near the center
        for( auto &&pt : g->m.points_in_radius( p, 3, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "MININUKE_MOD" ) > 0 ) {
        g->explosion( p, 450, 0, false );
        for( auto &&pt : g->m.points_in_radius( p, 6, 0 ) ) {
            if( g->m.sees( p, pt, 3 ) &&
                g->m.move_cost( pt ) > 0 ) {
                g->m.add_field( pt, fd_nuke_gas, 3, 0 );
            }
        }
    }

    if( effects.count( "ACIDBOMB" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_acid, 3, 0 );
        }
    }

    if( effects.count( "ACID_DROP" ) > 0 ) {
        g->m.add_field( p, fd_acid, 1, 0 );
    }

    if( effects.count( "EXPLOSIVE_BIG" ) > 0 ) {
        g->explosion( p, 40, 0, false );
    }

    if( effects.count( "EXPLOSIVE_HUGE" ) > 0 ) {
        g->explosion( p, 80, 0, false );
    }

    if( effects.count( "TEARGAS" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 2, 0 ) ) {
            g->m.add_field( pt, fd_tear_gas, 3, 0 );
        }
    }
    if( effects.count( "GAS_FUNGICIDAL" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fungicidal_gas, 3, 0 );
        }
    }
    if( effects.count( "SMOKE" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_smoke, 3, 0 );
        }
    }
    if( effects.count( "SMOKE_BIG" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 6, 0 ) ) {
            g->m.add_field( pt, fd_smoke, 18, 0 );
        }
    }

    if( effects.count( "FLASHBANG" ) ) {
        g->flashbang( p );
    }

    if( effects.count( "NO_BOOM" ) == 0 && effects.count( "FLAME" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_fire, 1, 0 );
        }
    }

    if( effects.count( "FLARE" ) > 0 ) {
        g->m.add_field( p, fd_fire, 1, 0 );
    }

    if( effects.count( "LIGHTNING" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            g->m.add_field( pt, fd_electricity, 3, 0 );
        }
    }

    if( effects.count( "PLASMA" ) > 0 ) {
        for( auto &&pt : g->m.points_in_radius( p, 1, 0 ) ) {
            if( one_in( 2 ) ) {
                g->m.add_field( pt, fd_plasma, rng( 2, 3 ), 0 );
            }
        }
    }

}
Пример #26
0
// Does the pair of MVertex pointers v1 and v2 exist in the set 'edges'?
static int edgeExists(MVertex *v1, MVertex *v2,
                      std::set<std::pair<MVertex*, MVertex*> > &edges)
{
  std::pair<MVertex*, MVertex*> p(std::min(v1, v2), std::max(v1, v2));
  return edges.count(p);
}
Пример #27
0
 bool convert(const std::string& method, int idx)
 {
     return (members.count(std::make_pair(method, idx)) > 0);
 }
Пример #28
0
 void visitBlock(Block *curr) {
   if (curr->name.is() && branchesSeen.count(curr->name) == 0) {
     curr->name = Name();
   }
 }
	bool contains(VertexId v) const {
		return vertices_.count(v) > 0;
	}
 void visitCall(Call* curr) {
   if (reachable.count(ModuleElement(ModuleElementKind::Function, curr->target)) == 0) {
     queue.emplace_back(ModuleElementKind::Function, curr->target);
   }
 }