Пример #1
0
		bool CornerRadius::Equals(Object const * const obj) const
		{
			return is(obj, this) ? *this == *(CornerRadius*)obj : false;
		}
Пример #2
0
wxBitmap
BossaBitmaps::GetBitmapFromMemory(const unsigned char *data, int length)
{
    wxMemoryInputStream is(data, length);
    return wxBitmap(wxImage(is, wxBITMAP_TYPE_ANY, -1), -1);
}
Пример #3
0
int configcontainer::get_configvalue_as_int(const std::string& key) {
	std::istringstream is(config_data[lookup_alias(key)].value);
	int i;
	is >> i;
	return i;
}
Пример #4
0
int main(int argc, char ** argv)
{
  try {
    options(argc, argv);
    
    feature_list_type features_confidence;
    feature_list_type features_count;

    if (! confidence_feature_file.empty()) {
      if (confidence_feature_file != "-" && ! boost::filesystem::exists(confidence_feature_file))
	throw std::runtime_error("no confidence feature file? " + confidence_feature_file.string());
      
      utils::compress_istream is(confidence_feature_file);
      std::string feature;
      while (is >> feature)
	features_confidence.push_back(feature);
    }
    
    if (! count_feature_file.empty()) {
      if (count_feature_file != "-" && ! boost::filesystem::exists(count_feature_file))
	throw std::runtime_error("no count feature file? " + count_feature_file.string());
      
      utils::compress_istream is(count_feature_file);
      std::string feature;
      while (is >> feature)
	features_count.push_back(feature);
    }

    const bool flush_output = (output_file == "-"
                               || (boost::filesystem::exists(output_file)
                                   && ! boost::filesystem::is_regular_file(output_file)));
    
    hypergraph_type merged;
    hypergraph_type hypergraph;
    
    cicada::Feature feature_confidence(confidence);
    cicada::Feature feature_count(count);
    
    if (input_files.empty())
      input_files.push_back("-");
    
    if (multiple_mode) {
      namespace qi = boost::spirit::qi;
      namespace standard = boost::spirit::standard;
      
      // forest ||| forest ||| forest

      utils::compress_ostream os(output_file, 1024 * 1024 * (! flush_output));
      
      for (path_set_type::const_iterator iter = input_files.begin(); iter != input_files.end(); ++ iter) {
	utils::compress_istream is(input_files.front(), 1024 * 1024);
	std::string line;
	
	while (utils::getline(is, line)) {
	  int rank = 1;
	  int id = 0;
	  
	  merged.clear();
	  hypergraph.clear();
	  
	  std::string::const_iterator iter = line.begin();
	  std::string::const_iterator end = line.end();
	  
	  for (/**/; iter != end; ++ id, ++ rank) {
	    if (id != 0)
	      if (! qi::phrase_parse(iter, end, "|||", standard::space))
		break;
	    
	    if (! hypergraph.assign(iter, end))
	      throw std::runtime_error("invalid hypergraph format");
	    if (! hypergraph.is_valid()) continue;
	    
	    const double conf = 1.0 / (1.0 + rank);
	      
	    feature_set_type features;
	      
	    if (! features_confidence.empty()) {
	      if (id >= static_cast<int>(features_confidence.size()))
		throw std::runtime_error("# of confidence features do not match");
	      features[features_confidence[id]] = conf;
	    }
	    if (! features_count.empty()) {
	      if (id >= static_cast<int>(features_count.size()))
		throw std::runtime_error("# of count features do not match");
	      features[features_count[id]] = count_weight;
	    }
	    if (! feature_confidence.empty())
	      features[feature_confidence] = conf;
	    if (! feature_count.empty())
	      features[feature_count] = count_weight;
	      
	    if (! features.empty()) {
	      hypergraph_type::edge_set_type::iterator eiter_end = hypergraph.edges.end();
	      for (hypergraph_type::edge_set_type::iterator eiter = hypergraph.edges.begin(); eiter != eiter_end; ++ eiter)
		eiter->features += features;
	    }
	    
	    merged.unite(hypergraph);
	  }
	  
	  os << merged << '\n';
	}
      }
    } else if (input_files.size() == 1) {
      utils::compress_istream is(input_files.front(), 1024 * 1024);
      std::string line;
      
      int rank = 1;
      int id = 0;
      for (/**/; utils::getline(is, line); ++ id, ++ rank) {
	std::string::const_iterator iter = line.begin();
	std::string::const_iterator end = line.end();
	
	if (! hypergraph.assign(iter, end))
	  throw std::runtime_error("invalid hypergraph format");
	if (! hypergraph.is_valid()) continue;
	
	const double conf = 1.0 / (1.0 + rank);
	
	feature_set_type features;
	if (! features_confidence.empty()) {
	  if (id >= static_cast<int>(features_confidence.size()))
	    throw std::runtime_error("# of confidence features do not match");
	  features[features_confidence[id]] = conf;
	}
	if (! features_count.empty()) {
	  if (id >= static_cast<int>(features_count.size()))
	    throw std::runtime_error("# of count features do not match");
	  features[features_count[id]] = count_weight;
	}
	if (! feature_confidence.empty())
	  features[feature_confidence] = conf;
	if (! feature_count.empty())
	  features[feature_count] = count_weight;
	
	if (! features.empty()) {
	  hypergraph_type::edge_set_type::iterator eiter_end = hypergraph.edges.end();
	  for (hypergraph_type::edge_set_type::iterator eiter = hypergraph.edges.begin(); eiter != eiter_end; ++ eiter)
	    eiter->features += features;
	} 
	
	merged.unite(hypergraph);
      }
      
      utils::compress_ostream os(output_file, 1024 * 1024 * (! flush_output));
      
      os << merged << '\n';
      
    } else {
      // we will handle multiple files!
      
      if (! features_confidence.empty())
	if (input_files.size() != features_confidence.size())
	  throw std::runtime_error("input file do not match with # of confidence feature");

      if (! features_count.empty())
	if (input_files.size() != features_count.size())
	  throw std::runtime_error("input file do not match with # of count feature");
      
      typedef std::vector<std::istream*, std::allocator<std::istream*> > istream_set_type;
      
      istream_set_type istreams(input_files.size());
      for (size_t i = 0; i != input_files.size(); ++ i)
	istreams[i] = new utils::compress_istream(input_files[i], 1024 * 1024);
      
      utils::compress_ostream os(output_file, 1024 * 1024 * (! flush_output));
      
      std::string line;
      
      for (;;) {
	int rank = 1;
	
	merged.clear();
	hypergraph.clear();
	
	size_t num_failed = 0;
	for (size_t id = 0; id != istreams.size(); ++ id, ++ rank) {
	  if (utils::getline(*istreams[id], line)) {
	    std::string::const_iterator iter = line.begin();
	    std::string::const_iterator end = line.end();
	    
	    if (! hypergraph.assign(iter, end))
	      throw std::runtime_error("invalid hypergraph format");
	    if (! hypergraph.is_valid()) continue;
	    
	    const double conf = 1.0 / (1.0 + rank);
	    
	    feature_set_type features;
	    if (! features_confidence.empty())
	      features[features_confidence[id]] = conf;
	    if (! features_count.empty())
	      features[features_count[id]] = count_weight;
	    if (! feature_confidence.empty())
	      features[feature_confidence] = conf;
	    if (! feature_count.empty())
	      features[feature_count] = count_weight;
	    
	    if (! features.empty()) {
	      hypergraph_type::edge_set_type::iterator eiter_end = hypergraph.edges.end();
	      for (hypergraph_type::edge_set_type::iterator eiter = hypergraph.edges.begin(); eiter != eiter_end; ++ eiter)
		eiter->features += features;
	    } 
	    
	    merged.unite(hypergraph);
	  } else
	    ++ num_failed;
	}
	
	if (num_failed) {
	  if (num_failed != istreams.size())
	    throw std::runtime_error("# of lines do not match");
	  break;
	}
	
	os << merged << '\n';
      }
      
      for (size_t i = 0; i != istreams.size(); ++ i)
	delete istreams[i];
    }
  }
  catch (const std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}
Пример #5
0
int main(int , char ** argv) {
    try {
        /* sometimes the local env's locales are broken on POSIX. Boost <=
         * 1.56 uses the std::locale("") constructor which respects user
         * preferred locales, and might crash. If this is the case, and
         * we're on a non-windows system (assuming POSIX), in case of an
         * exception, set the environment to "C" and keep going.
         *
         * Can be removed once boost < 1.57 is no longer supported
         */
        std::locale( "" );
    } catch( const std::runtime_error& ) {
        #if !defined(WIN32)
        setenv( "LC_ALL", "C", 1 );
        #endif
        auto loc = boost::filesystem::path::imbue( std::locale::classic() );
        boost::filesystem::path::imbue( loc );
        std::cout << "User preferred locale setting is invalid "
            << "which breaks Boost <= 1.56 "
            << "- forcing to 'C' as workaround for Boost <= 1.56. "
            << "This workaround only applies to compile opm-parser, "
            << "but your locale settings seem BROKEN, "
            << "and opm-parser is likely NOT GOING TO WORK. "
            << "If you're on linux you can try setting the LANG "
            << "or LC_ALL environment variables to C or POSIX."
            << std::endl;
    }
    const char * keyword_list_file = argv[1];
    const char * source_file_name = argv[2];
    const char * header_file_base_path = argv[3];
    const char * header_file_name = argv[4];
    const char * test_file_name = argv[5];


    Opm::KeywordGenerator generator( true );
    Opm::KeywordLoader loader( false );

    {
        size_t start = 0;
        std::string keyword_list;

        {
            std::ifstream is(keyword_list_file);
            std::getline( is , keyword_list );
            is.close();
        }

        while (true) {
            size_t end = keyword_list.find( ";" , start);
            if (end == std::string::npos) {
                loader.loadKeyword( keyword_list.substr( start ));
                break;
            }

            loader.loadKeyword( keyword_list.substr( start , end - start ));
            start = end + 1;
        }
    }

    generator.updateSource(loader , source_file_name );
    generator.updateHeader(loader, header_file_base_path, header_file_name );
    generator.updateTest( loader , test_file_name );
}
Пример #6
0
/*
 * TODO - make this more portable and dependable.
 *
 * https://issues.labcollab.net/browse/ACSDK-380
 */
bool fileExists(const std::string& filePath) {
    std::ifstream is(filePath);
    return is.good();
}
Пример #7
0
void test_atomic()
{
  std::random_device rd;
  std::mt19937 gen(rd());

  for(int ii=0; ii<100; ++ii)
  {
    std::atomic<bool> o_ab(std::uniform_int_distribution<int>(0,1)(gen));
    std::atomic<signed char> o_asc(std::uniform_int_distribution<signed char>(
      std::numeric_limits<signed char>::min(),
      std::numeric_limits<signed char>::max()
    )(gen));
    std::atomic<unsigned short> o_aus(std::uniform_int_distribution<unsigned short>(
      std::numeric_limits<unsigned short>::min(),
      std::numeric_limits<unsigned short>::max()
    )(gen));
    std::atomic<int> o_asi(std::uniform_int_distribution<int>(
      std::numeric_limits<int>::min(),
      std::numeric_limits<int>::max()
    )(gen));
    std::atomic<long> o_asl(std::uniform_int_distribution<long>(
      std::numeric_limits<long>::min(),
      std::numeric_limits<long>::max()
    )(gen));
    std::atomic<unsigned long long> o_aull(std::uniform_int_distribution<unsigned long long>(
      std::numeric_limits<unsigned long long>::min(),
      std::numeric_limits<unsigned long long>::max()
    )(gen));

    std::ostringstream os;
    {
      OArchive oar(os);

      oar(o_ab);
      oar(o_asc);
      oar(o_aus);
      oar(o_asi);
      oar(o_asl);
      oar(o_aull);
    }

    std::atomic<bool> i_ab;
    std::atomic<signed char> i_asc;
    std::atomic<unsigned short> i_aus;
    std::atomic<int> i_asi;
    std::atomic<long> i_asl;
    std::atomic<unsigned long long> i_aull;

    std::istringstream is(os.str());
    {
      IArchive iar(is);

      iar(i_ab);
      iar(i_asc);
      iar(i_aus);
      iar(i_asi);
      iar(i_asl);
      iar(i_aull);
    }

    BOOST_CHECK_EQUAL(o_ab.load(),i_ab.load());
    BOOST_CHECK_EQUAL(o_asc.load(),i_asc.load());
    BOOST_CHECK_EQUAL(o_aus.load(),i_aus.load());
    BOOST_CHECK_EQUAL(o_asi.load(),i_asi.load());
    BOOST_CHECK_EQUAL(o_asl.load(),i_asl.load());
    BOOST_CHECK_EQUAL(o_aull.load(),i_aull.load());
  }
}
Пример #8
0
int player_obj::clt_pick_up_item(const char *msg, const int len)
{
  int dropped_item_id = 0;
  in_stream is(msg, len);
  is >> dropped_item_id;

  dropped_item *di = dropped_item_mgr::instance()->find(dropped_item_id);
  if (di == NULL)
    return this->send_respond_err(NTF_OPERATE_RESULT, ERR_DROPPED_ITEM_NOT_EXIST);

  if (di->owner_id_ != 0
      && di->owner_id_ != this->id_)
  {
    team_info *ti = team_mgr::instance()->find_by_char(di->owner_id_);
    if (ti == NULL
        || !ti->have_player(this->id_))
      return this->send_respond_err(NTF_OPERATE_RESULT, ERR_DROPPED_ITEM_NOT_YOURS);
  }

  // ok
  item_obj notice_item;
  notice_item.cid_ = di->cid();
  notice_item.amount_ = di->amount_;
  notice_item.bind_ = di->bind_type_;
  if (clsid::is_tui_tu_scp_scene(this->scene_cid_))
  {
    package_module::do_insert_or_mail_item(this,
                                           di->cid(),
                                           di->amount_,
                                           di->bind_type_,
                                           mail_config::TUI_TU_MST_DROP,
                                           MONEY_GOT_PICK_UP,
                                           ITEM_GOT_PICKUP,
                                           this->scene_cid_,
                                           0);
  }else
  {
    if (item_config::item_is_money(di->cid()))
    {
      this->do_got_item_money(di->cid(),
                              di->amount_,
                              MONEY_GOT_PICK_UP,
                              0);
    }else
    {
      if (package_module::would_be_full(this,
                                        PKG_PACKAGE,
                                        di->cid(),
                                        di->amount_,
                                        di->bind_type_))
        return this->send_respond_err(NTF_OPERATE_RESULT, ERR_PACKAGE_SPACE_NOT_ENOUGH);
      item_obj *new_item = package_module::do_insert_item(this,
                                                          PKG_PACKAGE,
                                                          di->cid(),
                                                          di->amount_,
                                                          di->bind_type_,
                                                          ITEM_GOT_PICKUP,
                                                          this->scene_cid_,
                                                          0);
      if (item_config::instance()->dj_upper_limit(di->cid()) == 1)
        notice_item = *new_item;
    }
    if (di->notice_ && di->src_cid_ != 0)
    {
      notice_module::pick_up_dropped_item(this->id(),
                                          this->name(),
                                          this->scene_cid_,
                                          di->src_cid_,
                                          &notice_item);
    }
  }
  di->do_exit_scene();
  dropped_item_mgr::instance()->remove(di->id());
  dropped_item_pool::instance()->release(di);

  out_stream os(client::send_buf, client::send_buf_len);
  os << dropped_item_id;
  return this->send_respond_ok(RES_PICK_UP_ITEM, &os);
}
Пример #9
0
	bool Object::Equals(Object const * const obj) const
	{
		return is(this, obj);
	}
Пример #10
0
/** Print a terse human-readable description of this window to this ostream. 
  Does not print a header.
*/
void COM_print_window(const char *wName, std::ostream &ostr) {
  std::string w(wName); w+=".";
  
  // Obtain the list of panes
  int np, *pane_ids;
  COM_get_panes( wName, &np, &pane_ids);
  
  int  nnodes = 0;  // total number of nodes
  int  nelems = 0;  // total number of elems

  // Loop through the panes to find the meshes
  for ( int i=0; i<np; ++i) {
    int nconn;    // Number of connectivity tables
    char *cnames; // Names of connectivity tables separated by space
    ostr << "Pane "<<pane_ids[i]<< " ";

    // Obtain the connectivity tables
    COM_get_connectivities( wName, pane_ids[i], &nconn, &cnames);

    if ( nconn == 1 && strncmp(cnames,":st",3)==0) { // Structured mesh
      int ndims;     // Number of dimensions
      int nglayers; // Number of ghost layers.
      COM_get_size( (w+cnames).c_str(), pane_ids[i], &ndims, &nglayers);

      // Obtain the dimensions (must be a const array) of the pane and set them
      const int *dims;
      COM_get_array_const((w+cnames).c_str(), pane_ids[i], &dims);

      ostr << "Structured mesh: " 
	   << ndims << "-D (" << nglayers << " ghost layers);"
	   <<" grid is " << dims[0];
      nnodes = dims[0];
      nelems = std::max(1, dims[0] - 1);
      if ( ndims>1) {
        ostr << "x" << dims[1];
        nnodes *= dims[1];
        nelems *= std::max(1, dims[1] - 1);
      }
      if ( ndims>2) {
        ostr << "x" << dims[2];
        nnodes *= dims[2];
        nelems *= std::max(1, dims[2] - 1);
      }
      ostr << std::endl;
    }
    else { // Unstructured mesh
      int  ngnodes; // Number of ghost nodes

      // Obtain the size of nodes
      COM_get_size((w+"nc").c_str(), pane_ids[i], &nnodes, &ngnodes);
      ostr << "Unstructured mesh: " 
                << nnodes << " nodes (" << ngnodes << " ghosts)";
      
      // Obtain the sizes of connectivity tables
      if ( nconn>0) {
	std::istringstream is( cnames);
	for ( int c=0; c<nconn; ++c) {
	  std::string cname;
	  is >> cname;
	  int ne, ng;
	  COM_get_size((w+cname).c_str(), pane_ids[i], &ne, &ng);
          nelems += ne;
	  if (nconn>1)
	    ostr << "\n    Connectivity table " << c << " has ";
	  else ostr<<" / ";
	  ostr << ne << " elements (" << ng << " ghosts)";
	}
      }
      ostr<<std::endl;

      // free the buffer of cnames
      COM_free_buffer( &cnames);
    }
  }
Пример #11
0
// Simulate a debugger via the DDD log LOGNAME.  If a command matches
// a DDD command in LOGNAME, issue the appropriate answer.
void logplayer(const string& logname)
{
    // All this is really ugly.  Works well as a hack for debugging DDD,
    // but not really worth anything else.

    static std::ifstream log(logname.chars());
    if (log.bad())
    {
	(void) fopen(logname.chars(), "r");
	perror(logname.chars());
	exit(EXIT_FAILURE);
    }

    put("[Playing " + quote(logname) + ".  Use `?' for help]\n");

    static string out;
    static string ddd_line;
    static string last_prompt;
    static bool initializing = true;
    static bool scanning = false;
    static bool out_seen = false;
    static bool wrapped = false;
    static bool echoing = false;
    static STREAMPOS scan_start, last_input;
    static string expecting;
    static int command_no = 0;
    static int command_no_start = 0;
    static bool ignore_next_input = false;

    signal(SIGINT, (SignalProc)intr);
    if (setjmp(main_loop_env) != 0)
    {
	put("Quit\n");

	scanning = false;
	wrapped  = false;
	log.clear();
	log.seekg(last_input);
	command_no = command_no_start;
	out = "";
	ddd_line = "";
	ignore_next_input = true;
    }

    for (;;)
    {
	STREAMPOS current = log.tellg();
	if (!scanning)
	{
	    scan_start = current;
	    command_no_start = command_no;
	}

	// Read line from log
	char buffer[65536];
	log.getline(buffer, sizeof buffer);
	if (!log.fail())
	{
	    string log_line(buffer);

	    if (out_seen && log_line.contains("   ", 0))
	    {
		// Continuation line
		out += unquote(log_line.from('"'));
	    }
	    else if (!out.empty())
	    {
		// Send out accumulated output
		if (!scanning)
		{
		    if (out.contains(ddd_line, 0))
			echoing = true;
		    put(out);
		}
		out = "";
	    }

	    if (log_line.contains("<- ", 0))
	    {
		assert(out.empty());

		// Output line
		out = unquote(log_line.from('"'));
		out_seen = true;
	    }

	    if (out_seen && log_line.contains("-> ", 0))
	    {
		// Handle input
		string in = unquote(log_line.from('"'));
		if (in.contains('\n', -1))
		    in = in.before('\n', -1);
		command_no++;

		if (ddd_line.contains('/', 0) || ddd_line.contains(':', 0))
		{
		    static string pattern;
		    char c = ddd_line[0];
		    string p = ddd_line.after(0);
		    if (!p.empty() || c == ':')
			pattern = p;
		    if (pattern.empty() ||
			(c == ':' && command_no == atoi(pattern.chars())) ||
			(c == '/' && (pattern.empty() || in.contains(pattern))))
		    {
			// Report line
			char buffer[256];
			sprintf(buffer, "%4d", command_no);
			std::ostringstream os;
			os << buffer << " " << in << "\n";
			put(os);

			if (c == '/' || !pattern.empty())
			{
			    // Stop here
			    scanning = false;
			    scan_start = current;
			    command_no_start = command_no - 1;
			}
		    }
		}

		if (!scanning)
		{
		    last_input = scan_start;
		    initializing = false;

		    // Read command from DDD
		    if (last_output.contains('\n'))
		    {
			string prompt = last_output.after('\n', -1);
			if (!prompt.empty() && !prompt.contains('\\', 0))
			{
			    if (prompt.contains('('))
				prompt = prompt.from('(', -1);

			    last_prompt = prompt;
			}
		    }

		    if (!last_output.contains(last_prompt, -1))
			put(last_prompt);

		    last_output = "";

		    char *s = fgets(buffer, sizeof buffer, stdin);
		    if (ignore_next_input)
		    {
			s = fgets(buffer, sizeof buffer, stdin);
			ignore_next_input = false;
		    }
		    if (s == 0)
			exit(EXIT_SUCCESS);

		    ddd_line = buffer;
		    if (ddd_line.contains('\n', -1))
			ddd_line = ddd_line.before('\n', -1);

		    if (echoing && !ddd_line.empty() && !isalpha(ddd_line[0]))
			put(ddd_line + "\r\n");

		    if (ddd_line.contains('q', 0))
			exit(EXIT_SUCCESS);

		    if ((ddd_line.contains("list ", 0) || 
			 ddd_line.contains("l ", 0)) && 
			(ddd_line.contains(" 1,") || 
			 ddd_line.contains(":1,") || 
			 ddd_line.contains(" 1-")))
		    {
			// Send the log file instead of a source
			if (echoing)
			    put(ddd_line + "\r\n");

			std::ifstream is(logname.chars());
			int line = 1;
			bool at_start_of_line = true;

			std::ostringstream os;
			for (;;)
			{
			    char c;
			    is.get(c);
			    if (is.eof())
				break;

			    if (at_start_of_line)
			    {
				os << line << '\t';
				at_start_of_line = false;
			    }

			    os << c;

			    if (c == '\n')
			    {
				line++;
				at_start_of_line = true;
			    }
			}

			put(string(os));
			scanning = false;
		    }
		}

		if (!scanning && ddd_line == ".")
		{
		    std::ostringstream os;
		    os << "Expecting " 
		       << command_no << " " << quote(in) << "\n";
		    put(os);
		    log.seekg(scan_start);
		    command_no = command_no_start;
		}
		else if (!scanning && ddd_line == "?")
		{
		    put(usage);
		    log.seekg(scan_start);
		    command_no = command_no_start;
		}
		else if (ddd_line == in || ddd_line == "!" || ddd_line.empty())
		{
		    // Okay, got it
		    scanning = false;
		}
		else if (!scanning)
		{
		    // Bad match: try to find this command in the log
		    expecting = in;
		    scanning = true;
		    wrapped = false;
		}
	    }
	}

	if (log.eof() || log.fail())
	{
	    if (scanning && wrapped)
	    {
		// Nothing found.  Don't reply.
		if (echoing && (ddd_line.empty() || isalpha(ddd_line[0])))
		    put(ddd_line + "\r\n");

		scanning = false;
		log.clear();
		log.seekg(scan_start);
		out = "";
		command_no = command_no_start;
	    }
	    else if (initializing)
	    {
		// No prompt found
		std::cerr << logname << ": invalid or incomplete log\n";
		exit(EXIT_FAILURE);
	    }
	    else
	    {
		// Try from the start
		wrapped = true;
		out_seen = false;
		log.clear();
		log.seekg(0);
		command_no = 0;
	    }
	}
    }
}
bool loadRomeGraph(Graph &G, const char *fileName) {
	std::ifstream is(fileName);
	if(!is.good()) return false;
	return loadRomeGraphStream(G, is);
}
bool loadBenchHypergraph(Graph &G, List<node>& hypernodes, List<edge>* shell, const char *fileName) {
	std::ifstream is(fileName);
	if(!is.good()) return false;
	return loadBenchHypergraphStream(G, hypernodes, shell, is);
}
Пример #14
0
MemEffects memory_effects_impl(const IRInstruction& inst) {
  switch (inst.op()) {

  //////////////////////////////////////////////////////////////////////
  // Region exits

  // These exits don't leave the current php function, and could head to code
  // that could read or write anything as far as we know (including frame
  // locals).
  case ReqBindJmp:
    return ExitEffects {
      AUnknown,
      stack_below(inst.src(0), inst.extra<ReqBindJmp>()->irSPOff.offset - 1)
    };
  case JmpSwitchDest:
    return ExitEffects {
      AUnknown,
      *stack_below(inst.src(1),
                   inst.extra<JmpSwitchDest>()->irSPOff.offset - 1).
        precise_union(AMIStateAny)
    };
  case JmpSSwitchDest:
    return ExitEffects {
      AUnknown,
      *stack_below(inst.src(1),
                   inst.extra<JmpSSwitchDest>()->offset.offset - 1).
        precise_union(AMIStateAny)
    };
  case ReqRetranslate:
  case ReqRetranslateOpt:
    return UnknownEffects {};

  //////////////////////////////////////////////////////////////////////
  // Unusual instructions

  /*
   * The ReturnHook sets up the ActRec so the unwinder knows everything is
   * already released (i.e. it calls ar->setLocalsDecRefd()).
   *
   * The eval stack is also dead at this point (the return value is passed to
   * ReturnHook as src(1), and the ReturnHook may not access the stack).
   */
  case ReturnHook:
    // Note, this instruction can re-enter, but doesn't need the may_reenter()
    // treatmeant because of the special kill semantics for locals and stack.
    return may_load_store_kill(
      AHeapAny, AHeapAny,
      *AStackAny.precise_union(AFrameAny)->precise_union(AMIStateAny)
    );

  // The suspend hooks can load anything (re-entering the VM), but can't write
  // to frame locals.
  case SuspendHookE:
  case SuspendHookR:
    // TODO: may-load here probably doesn't need to include AFrameAny normally.
    return may_reenter(inst,
                       may_load_store_kill(AUnknown, AHeapAny, AMIStateAny));

  /*
   * If we're returning from a function, it's ReturnEffects.  The RetCtrl
   * opcode also suspends resumables, which we model as having any possible
   * effects.
   *
   * Note that marking AFrameAny as dead isn't quite right, because that
   * ought to mean that the preceding StRetVal is dead; but memory effects
   * ignores StRetVal so the AFrameAny is fine.
   */
  case RetCtrl:
    if (inst.extra<RetCtrl>()->suspendingResumed) {
      // Suspending can go anywhere, and doesn't even kill locals.
      return UnknownEffects {};
    }
    return ReturnEffects {
      AStackAny | AFrameAny | AMIStateAny
    };

  case AsyncRetFast:
  case AsyncRetCtrl:
    if (inst.extra<RetCtrlData>()->suspendingResumed) {
      return UnknownEffects {};
    }
    return ReturnEffects {
      *stack_below(
        inst.src(0),
        inst.extra<RetCtrlData>()->spOffset.offset - 1
      ).precise_union(AMIStateAny)
    };

  case GenericRetDecRefs:
    /*
     * The may-store information here is AUnknown: even though we know it
     * doesn't really "store" to the frame locals, the values that used to be
     * there are no longer available because they are DecRef'd, which we are
     * required to report as may-store information to make it visible to
     * reference count optimizations.  It's conceptually the same as if it was
     * storing an Uninit over each of the locals, but the stores of uninits
     * would be dead so we're not actually doing that.
     */
    return may_reenter(inst,
                       may_load_store_kill(AUnknown, AUnknown, AMIStateAny));

  case EndCatch: {
    auto const stack_kills = stack_below(
      inst.src(1),
      inst.extra<EndCatch>()->offset.offset - 1
    );
    return ExitEffects {
      AUnknown,
      stack_kills | AMIStateTempBase | AMIStateBase
    };
  }

  /*
   * DefInlineFP has some special treatment here.
   *
   * It's logically `publishing' a pointer to a pre-live ActRec, making it
   * live.  It doesn't actually load from this ActRec, but after it's done this
   * the set of things that can load from it is large enough that the easiest
   * way to model this is to consider it as a load on behalf of `publishing'
   * the ActRec.  Once it's published, it's a live activation record, and
   * doesn't get written to as if it were a stack slot anymore (we've
   * effectively converted AStack locations into a frame until the
   * InlineReturn).
   *
   * TODO(#3634984): Additionally, DefInlineFP is marking may-load on all the
   * locals of the outer frame.  This is probably not necessary anymore, but we
   * added it originally because a store sinking prototype needed to know it
   * can't push StLocs past a DefInlineFP, because of reserved registers.
   * Right now it's just here because we need to think about and test it before
   * removing that set.
   */
  case DefInlineFP:
    return may_load_store_kill(
      AFrameAny | inline_fp_frame(&inst),
      /*
       * This prevents stack slots from the caller from being sunk into the
       * callee. Note that some of these stack slots overlap with the frame
       * locals of the callee-- those slots are inacessible in the inlined
       * call as frame and stack locations may not alias.
       */
      stack_below(inst.dst(), 0),
      /*
       * While not required for correctness adding these slots to the kill set
       * will hopefully avoid some extra stores.
       */
      stack_below(inst.dst(), 0)
    );

  case InlineReturn:
    return ReturnEffects { stack_below(inst.src(0), 2) | AMIStateAny };

  case InlineReturnNoFrame:
    return ReturnEffects {
      AliasClass(AStack {
        inst.extra<InlineReturnNoFrame>()->frameOffset.offset,
        std::numeric_limits<int32_t>::max()
      }) | AMIStateAny
    };

  case InterpOne:
    return interp_one_effects(inst);
  case InterpOneCF:
    return ExitEffects {
      AUnknown,
      stack_below(inst.src(1), -inst.marker().spOff().offset - 1) | AMIStateAny
    };

  case NativeImpl:
    return UnknownEffects {};

  // NB: on the failure path, these C++ helpers do a fixup and read frame
  // locals before they throw.  They can also invoke the user error handler and
  // go do whatever they want to non-frame locations.
  //
  // TODO(#5372569): if we combine dv inits into the same regions we could
  // possibly avoid storing KindOfUninits if we modify this.
  case VerifyParamCallable:
  case VerifyParamCls:
  case VerifyParamFail:
    return may_raise(inst, may_load_store(AUnknown, AHeapAny));
  // However the following ones can't read locals from our frame on the way
  // out, except as a side effect of raising a warning.
  case VerifyRetCallable:
  case VerifyRetCls:
    return may_raise(inst, may_load_store(AHeapAny, AHeapAny));
  // In PHP 7 VerifyRetFail can coerce the return type in weak files-- even in
  // a strict file we may still coerce int to float. This is not true of HH
  // files.
  case VerifyRetFail: {
    auto func = inst.marker().func();
    auto mayCoerce =
      RuntimeOption::PHP7_ScalarTypes &&
      !RuntimeOption::EnableHipHopSyntax &&
      !func->unit()->isHHFile();
    auto stores = mayCoerce ? AHeapAny | AStackAny : AHeapAny;
    return may_raise(inst, may_load_store(AHeapAny | AStackAny, stores));
  }

  case CallArray:
    return CallEffects {
      inst.extra<CallArray>()->destroyLocals,
      AMIStateAny,
      // The AStackAny on this is more conservative than it could be; see Call
      // and CallBuiltin.
      AStackAny
    };
  case ContEnter:
    return CallEffects { false, AMIStateAny, AStackAny };

  case Call:
    {
      auto const extra = inst.extra<Call>();
      return CallEffects {
        extra->destroyLocals,
        // kill
        stack_below(inst.src(0), extra->spOffset.offset - 1) | AMIStateAny,
        // We might side-exit inside the callee, and interpret a return.  So we
        // can read anything anywhere on the eval stack above the call's entry
        // depth here.
        AStackAny
      };
    }

  case CallBuiltin:
    {
      auto const extra = inst.extra<CallBuiltin>();
      auto const stk = [&] () -> AliasClass {
        AliasClass ret = AEmpty;
        for (auto i = uint32_t{2}; i < inst.numSrcs(); ++i) {
          if (inst.src(i)->type() <= TPtrToGen) {
            auto const cls = pointee(inst.src(i));
            if (cls.maybe(AStackAny)) {
              ret = ret | cls;
            }
          }
        }
        return ret;
      }();
      auto const locs = extra->destroyLocals ? AFrameAny : AEmpty;
      return may_raise(
        inst, may_load_store_kill(stk | AHeapAny | locs, locs, AMIStateAny));
    }

  // Resumable suspension takes everything from the frame and moves it into the
  // heap.
  case CreateAFWH:
  case CreateAFWHNoVV:
  case CreateCont:
    return may_load_store_move(AFrameAny, AHeapAny, AFrameAny);

  // This re-enters to call extension-defined instance constructors.
  case ConstructInstance:
    return may_reenter(inst, may_load_store(AHeapAny, AHeapAny));

  case CheckStackOverflow:
  case CheckSurpriseFlagsEnter:
  case CheckSurpriseAndStack:
    return may_raise(inst, may_load_store(AEmpty, AEmpty));

  case InitExtraArgs:
    return UnknownEffects {};

  //////////////////////////////////////////////////////////////////////
  // Iterator instructions

  case IterInit:
  case MIterInit:
  case WIterInit:
    return iter_effects(
      inst,
      inst.src(1),
      AFrame { inst.src(1), inst.extra<IterData>()->valId }
    );
  case IterNext:
  case MIterNext:
  case WIterNext:
    return iter_effects(
      inst,
      inst.src(0),
      AFrame { inst.src(0), inst.extra<IterData>()->valId }
    );

  case IterInitK:
  case MIterInitK:
  case WIterInitK:
    {
      AliasClass key = AFrame { inst.src(1), inst.extra<IterData>()->keyId };
      AliasClass val = AFrame { inst.src(1), inst.extra<IterData>()->valId };
      return iter_effects(inst, inst.src(1), key | val);
    }

  case IterNextK:
  case MIterNextK:
  case WIterNextK:
    {
      AliasClass key = AFrame { inst.src(0), inst.extra<IterData>()->keyId };
      AliasClass val = AFrame { inst.src(0), inst.extra<IterData>()->valId };
      return iter_effects(inst, inst.src(0), key | val);
    }

  //////////////////////////////////////////////////////////////////////
  // Instructions that explicitly manipulate locals

  case StLoc:
    return PureStore {
      AFrame { inst.src(0), inst.extra<StLoc>()->locId },
      inst.src(1)
    };

  case StLocRange:
    {
      auto const extra = inst.extra<StLocRange>();
      auto acls = AEmpty;

      for (auto locId = extra->start; locId < extra->end; ++locId) {
        acls = acls | AFrame { inst.src(0), locId };
      }
      return PureStore { acls, inst.src(1) };
    }

  case LdLoc:
    return PureLoad { AFrame { inst.src(0), inst.extra<LocalId>()->locId } };

  case CheckLoc:
  case LdLocPseudoMain:
    // Note: LdLocPseudoMain is both a guard and a load, so it must not be a
    // PureLoad.
    return may_load_store(
      AFrame { inst.src(0), inst.extra<LocalId>()->locId },
      AEmpty
    );

  case StLocPseudoMain:
    // This can store to globals or locals, but we don't have globals supported
    // in AliasClass yet.
    return PureStore { AUnknown, inst.src(1) };

  case ClosureStaticLocInit:
    return may_load_store(AFrameAny, AFrameAny);

  //////////////////////////////////////////////////////////////////////
  // Pointer-based loads and stores

  case LdMem:
    return PureLoad { pointee(inst.src(0)) };
  case StMem:
    return PureStore { pointee(inst.src(0)), inst.src(1) };

  // TODO(#5962341): These take non-constant offset arguments, and are
  // currently only used for collections and class property inits, so we aren't
  // hooked up yet.
  case StElem:
    return PureStore {
      inst.src(0)->type() <= TPtrToRMembCell
        ? AHeapAny
        : AUnknown,
      inst.src(2)
    };
  case LdElem:
    return PureLoad {
      inst.src(0)->type() <= TPtrToRMembCell
        ? AHeapAny
        : AUnknown
    };

  case LdMBase:
    return PureLoad { AMIStateBase };

  case StMBase:
    return PureStore { AMIStateBase, inst.src(0) };

  case FinishMemberOp:
    return may_load_store_kill(AEmpty, AEmpty, AMIStateAny);

  case BoxPtr:
    {
      auto const mem = pointee(inst.src(0));
      return may_load_store(mem, mem);
    }
  case UnboxPtr:
    return may_load_store(pointee(inst.src(0)), AEmpty);

  case IsNTypeMem:
  case IsTypeMem:
  case CheckTypeMem:
  case CheckInitMem:
  case DbgAssertPtr:
    return may_load_store(pointee(inst.src(0)), AEmpty);

  //////////////////////////////////////////////////////////////////////
  // Object/Ref loads/stores

  case CheckRefInner:
    return may_load_store(ARef { inst.src(0) }, AEmpty);
  case LdRef:
    return PureLoad { ARef { inst.src(0) } };
  case StRef:
    return PureStore { ARef { inst.src(0) }, inst.src(1) };

  case InitObjProps:
    return may_load_store(AEmpty, APropAny);

  //////////////////////////////////////////////////////////////////////
  // Array loads and stores

  case InitPackedArray:
    return PureStore {
      AElemI { inst.src(0), inst.extra<InitPackedArray>()->index },
      inst.src(1)
    };

  case LdStructArrayElem:
    assertx(inst.src(1)->strVal()->isStatic());
    return PureLoad { AElemS { inst.src(0), inst.src(1)->strVal() } };

  case InitPackedArrayLoop:
    {
      auto const extra = inst.extra<InitPackedArrayLoop>();
      auto const stack_in = AStack {
        inst.src(1),
        extra->offset.offset + static_cast<int32_t>(extra->size) - 1,
        static_cast<int32_t>(extra->size)
      };
      return may_load_store_move(stack_in, AElemIAny, stack_in);
    }

  case NewStructArray:
    {
      // NewStructArray is reading elements from the stack, but writes to a
      // completely new array, so we can treat the store set as empty.
      auto const extra = inst.extra<NewStructArray>();
      auto const stack_in = AStack {
        inst.src(0),
        extra->offset.offset + static_cast<int32_t>(extra->numKeys) - 1,
        static_cast<int32_t>(extra->numKeys)
      };
      return may_load_store_move(stack_in, AEmpty, stack_in);
    }

  case ArrayIdx:
    return may_load_store(AElemAny | ARefAny, AEmpty);
  case MapIdx:
    return may_load_store(AHeapAny, AEmpty);
  case AKExistsArr:
    return may_load_store(AElemAny, AEmpty);
  case AKExistsObj:
    return may_reenter(inst, may_load_store(AHeapAny, AHeapAny));

  //////////////////////////////////////////////////////////////////////
  // Member instructions

  /*
   * Various minstr opcodes that take a PtrToGen in src 0, which may or may not
   * point to a frame local or the evaluation stack.  These instructions can
   * all re-enter the VM and access arbitrary heap locations, and some of them
   * take pointers to MinstrState locations, which they may both load and store
   * from if present.
   */
  case CGetElem:
  case EmptyElem:
  case IssetElem:
  case SetElem:
  case SetNewElemArray:
  case SetNewElem:
  case UnsetElem:
  case ElemArrayD:
  case ElemArrayU:
    // Right now we generally can't limit any of these better than general
    // re-entry rules, since they can raise warnings and re-enter.
    assertx(inst.src(0)->type() <= TPtrToGen);
    return may_raise(inst, may_load_store(
      AHeapAny | all_pointees(inst),
      AHeapAny | all_pointees(inst)
    ));

  case ElemX:
  case ElemDX:
  case ElemUX:
  case BindElem:
  case BindNewElem:
  case IncDecElem:
  case SetOpElem:
  case SetWithRefElem:
  case SetWithRefNewElem:
  case VGetElem:

    assertx(inst.src(0)->isA(TPtrToGen));
    return minstr_with_tvref(inst);

  /*
   * These minstr opcodes either take a PtrToGen or an Obj as the base.  The
   * pointer may point at frame locals or the stack.  These instructions can
   * all re-enter the VM and access arbitrary non-frame/stack locations, as
   * well.
   */
  case CGetProp:
  case CGetPropQ:
  case EmptyProp:
  case IssetProp:
  case UnsetProp:
  case IncDecProp:
  case SetProp:
    return may_raise(inst, may_load_store(
      AHeapAny | all_pointees(inst),
      AHeapAny | all_pointees(inst)
    ));

  case PropX:
  case PropDX:
  case PropQ:
  case BindProp:
  case SetOpProp:
  case VGetProp:
    return minstr_with_tvref(inst);

  /*
   * Collection accessors can read from their inner array buffer, but stores
   * COW and behave as if they only affect collection memory locations.  We
   * don't track those, so it's returning AEmpty for now.
   */
  case MapIsset:
  case PairIsset:
  case VectorDoCow:
  case VectorIsset:
    return may_load_store(AHeapAny, AEmpty /* Note */);
  case MapGet:
  case MapSet:
    return may_reenter(inst, may_load_store(AHeapAny, AEmpty /* Note */));


  //////////////////////////////////////////////////////////////////////
  // Instructions that allocate new objects, without reading any other memory
  // at all, so any effects they have on some types of memory locations we
  // track are isolated from anything else we care about.

  case NewArray:
  case NewCol:
  case NewInstanceRaw:
  case NewMixedArray:
  case AllocPackedArray:
  case ConvBoolToArr:
  case ConvDblToStr:
  case ConvDblToArr:
  case ConvIntToArr:
  case ConvIntToStr:
  case Box:  // conditional allocation
    return IrrelevantEffects {};

  case AllocObj:
    // AllocObj re-enters to call constructors, but if it weren't for that we
    // could ignore its loads and stores since it's a new object.
    return may_reenter(inst, may_load_store(AEmpty, AEmpty));

  //////////////////////////////////////////////////////////////////////
  // Instructions that explicitly manipulate the stack.

  case LdStk:
    return PureLoad {
      AStack { inst.src(0), inst.extra<LdStk>()->offset.offset, 1 }
    };

  case StStk:
    return PureStore {
      AStack { inst.src(0), inst.extra<StStk>()->offset.offset, 1 },
      inst.src(1)
    };

  case SpillFrame:
    {
      auto const spOffset = inst.extra<SpillFrame>()->spOffset;
      return PureSpillFrame {
        AStack {
          inst.src(0),
          // SpillFrame's spOffset is to the bottom of where it will store the
          // ActRec, but AliasClass needs an offset to the highest cell it will
          // store.
          spOffset.offset + int32_t{kNumActRecCells} - 1,
          int32_t{kNumActRecCells}
        },
        AStack {
          inst.src(0),
          // The context is in the highest slot.
          spOffset.offset + int32_t{kNumActRecCells} - 1,
          1
        }
      };
    }

  case CheckStk:
    return may_load_store(
      AStack { inst.src(0), inst.extra<CheckStk>()->irSpOffset.offset, 1 },
      AEmpty
    );
  case CufIterSpillFrame:
    return may_load_store(AEmpty, AStackAny);

  // The following may re-enter, and also deal with a stack slot.
  case CastStk:
    {
      auto const stk = AStack {
        inst.src(0), inst.extra<CastStk>()->offset.offset, 1
      };
      return may_raise(inst, may_load_store(stk, stk));
    }
  case CoerceStk:
    {
      auto const stk = AStack {
        inst.src(0),
        inst.extra<CoerceStk>()->offset.offset, 1
      };
      return may_raise(inst, may_load_store(stk, stk));
    }

  case CastMem:
  case CoerceMem:
    {
      auto aInst = inst.src(0)->inst();
      if (aInst->is(LdLocAddr)) {
        return may_raise(inst, may_load_store(AFrameAny, AFrameAny));
      }
      return may_raise(inst, may_load_store(AUnknown, AUnknown));
    }

  case LdARFuncPtr:
    // This instruction is essentially a PureLoad, but we don't handle non-TV's
    // in PureLoad so we have to treat it as may_load_store.  We also treat it
    // as loading an entire ActRec-sized part of the stack, although it only
    // loads the slot containing the Func.
    return may_load_store(
      AStack {
        inst.src(0),
        inst.extra<LdARFuncPtr>()->offset.offset + int32_t{kNumActRecCells} - 1,
        int32_t{kNumActRecCells}
      },
      AEmpty
    );

  //////////////////////////////////////////////////////////////////////
  // Instructions that never do anything to memory

  case AssertStk:
  case HintStkInner:
  case AbsDbl:
  case AddDbl:
  case AddInt:
  case AddIntO:
  case AndInt:
  case AssertLoc:
  case AssertType:
  case DefFP:
  case DefSP:
  case EndGuards:
  case EqBool:
  case EqCls:
  case EqDbl:
  case EqInt:
  case GteBool:
  case GteInt:
  case GtBool:
  case GtInt:
  case HintLocInner:
  case Jmp:
  case JmpNZero:
  case JmpZero:
  case LdPropAddr:
  case LdStkAddr:
  case LdPackedArrayElemAddr:
  case LteBool:
  case LteDbl:
  case LteInt:
  case LtBool:
  case LtInt:
  case GtDbl:
  case GteDbl:
  case LtDbl:
  case DivDbl:
  case DivInt:
  case MulDbl:
  case MulInt:
  case MulIntO:
  case NeqBool:
  case NeqDbl:
  case NeqInt:
  case SameObj:
  case NSameObj:
  case EqRes:
  case NeqRes:
  case CmpBool:
  case CmpInt:
  case CmpDbl:
  case SubDbl:
  case SubInt:
  case SubIntO:
  case XorBool:
  case XorInt:
  case OrInt:
  case AssertNonNull:
  case CheckNonNull:
  case CheckNullptr:
  case Ceil:
  case Floor:
  case DefLabel:
  case CheckInit:
  case Nop:
  case Mod:
  case Conjure:
  case Halt:
  case ConvBoolToInt:
  case ConvBoolToDbl:
  case DbgAssertType:
  case DbgAssertFunc:
  case DefConst:
  case LdLocAddr:
  case Sqrt:
  case LdResumableArObj:
  case Shl:
  case Shr:
  case IsNType:
  case IsType:
  case Mov:
  case ConvClsToCctx:
  case ConvDblToBool:
  case ConvDblToInt:
  case IsScalarType:
  case LdMIStateAddr:
  case LdPairBase:
  case LdStaticLocCached:
  case CheckCtxThis:
  case CastCtxThis:
  case LdARNumParams:
  case LdRDSAddr:
  case ExitPlaceholder:
  case CheckRange:
  case ProfileObjClass:
  case LdIfaceMethod:
  case InstanceOfIfaceVtable:
  case CheckARMagicFlag:
  case LdARNumArgsAndFlags:
  case StARNumArgsAndFlags:
  case LdARInvName:
  case StARInvName:
  case MethodExists:
    return IrrelevantEffects {};

  //////////////////////////////////////////////////////////////////////
  // Instructions that technically do some things w/ memory, but not in any way
  // we currently care about.  They however don't return IrrelevantEffects
  // because we assume (in refcount-opts) that IrrelevantEffects instructions
  // can't even inspect Countable reference count fields, and several of these
  // can.  All GeneralEffects instructions are assumed to possibly do so.

  case DecRefNZ:
  case AFWHBlockOn:
  case IncRef:
  case IncRefCtx:
  case LdClosureCtx:
  case StClosureCtx:
  case StClosureArg:
  case StContArKey:
  case StContArValue:
  case StRetVal:
  case ConvStrToInt:
  case ConvResToInt:
  case OrdStr:
  case CreateSSWH:
  case NewLikeArray:
  case CheckRefs:
  case LdClsCctx:
  case BeginCatch:
  case CheckSurpriseFlags:
  case CheckType:
  case FreeActRec:
  case RegisterLiveObj:
  case StContArResume:
  case StContArState:
  case ZeroErrorLevel:
  case RestoreErrorLevel:
  case CheckCold:
  case CheckInitProps:
  case CheckInitSProps:
  case ContArIncIdx:
  case ContArIncKey:
  case ContArUpdateIdx:
  case ContValid:
  case ContStarted:
  case IncProfCounter:
  case IncStat:
  case IncStatGrouped:
  case CountBytecode:
  case ContPreNext:
  case ContStartedCheck:
  case ConvArrToBool:
  case ConvArrToDbl:
  case ConvArrToInt:
  case NewColFromArray:
  case ConvBoolToStr:
  case CountArray:
  case CountArrayFast:
  case StAsyncArResult:
  case StAsyncArResume:
  case StAsyncArSucceeded:
  case InstanceOf:
  case InstanceOfBitmask:
  case NInstanceOfBitmask:
  case InstanceOfIface:
  case InterfaceSupportsArr:
  case InterfaceSupportsDbl:
  case InterfaceSupportsInt:
  case InterfaceSupportsStr:
  case IsWaitHandle:
  case IsCol:
  case HasToString:
  case DbgAssertRefCount:
  case GtStr:
  case GteStr:
  case LtStr:
  case LteStr:
  case EqStr:
  case NeqStr:
  case SameStr:
  case NSameStr:
  case CmpStr:
  case GtStrInt:
  case GteStrInt:
  case LtStrInt:
  case LteStrInt:
  case EqStrInt:
  case NeqStrInt:
  case CmpStrInt:
  case SameArr:
  case NSameArr:
  case GtRes:
  case GteRes:
  case LtRes:
  case LteRes:
  case CmpRes:
  case IncTransCounter:
  case LdBindAddr:
  case LdAsyncArParentChain:
  case LdSSwitchDestFast:
  case RBTraceEntry:
  case RBTraceMsg:
  case ConvIntToBool:
  case ConvIntToDbl:
  case ConvStrToArr:   // decrefs src, but src is a string
  case ConvStrToBool:
  case ConvStrToDbl:
  case ConvResToDbl:
  case DerefClsRDSHandle:
  case EagerSyncVMRegs:
  case ExtendsClass:
  case LdUnwinderValue:
  case GetCtxFwdCall:
  case LdCtx:
  case LdCctx:
  case LdClosure:
  case LdClsName:
  case LdAFWHActRec:
  case LdClsCtx:
  case LdContActRec:
  case LdContArKey:
  case LdContArValue:
  case LdContField:
  case LdContResumeAddr:
  case LdClsCachedSafe:
  case LdClsInitData:
  case UnwindCheckSideExit:
  case LdCns:
  case LdClsMethod:
  case LdClsMethodCacheCls:
  case LdClsMethodCacheFunc:
  case LdClsMethodFCacheFunc:
  case ProfilePackedArray:
  case ProfileStructArray:
  case ProfileSwitchDest:
  case LdFuncCachedSafe:
  case LdFuncNumParams:
  case LdGblAddr:
  case LdGblAddrDef:
  case LdObjClass:
  case LdObjInvoke:
  case LdStrLen:
  case StringIsset:
  case LdSwitchDblIndex:
  case LdSwitchStrIndex:
  case LdVectorBase:
  case LdWHResult:
  case LdWHState:
  case LookupClsRDSHandle:
  case GetCtxFwdCallDyn:
  case DbgTraceCall:
  case InitCtx:
  case PackMagicArgs:
    return may_load_store(AEmpty, AEmpty);

  // Some that touch memory we might care about later, but currently don't:
  case CheckStaticLocInit:
  case StaticLocInitCached:
  case ColIsEmpty:
  case ColIsNEmpty:
  case ConvCellToBool:
  case ConvObjToBool:
  case CountCollection:
  case LdVectorSize:
  case VectorHasImmCopy:
  case CheckPackedArrayBounds:
  case LdColArray:
  case EnterFrame:
    return may_load_store(AEmpty, AEmpty);

  //////////////////////////////////////////////////////////////////////
  // Instructions that can re-enter the VM and touch most heap things.  They
  // also may generally write to the eval stack below an offset (see
  // alias-class.h above AStack for more).

  case DecRef:
    {
      auto const src = inst.src(0);
      // It could decref the inner ref.
      auto const maybeRef = src->isA(TBoxedCell) ? ARef { src } :
                            src->type().maybe(TBoxedCell) ? ARefAny : AEmpty;
      // Need to add maybeRef to the `store' set. See comments about
      // `GeneralEffects' in memory-effects.h.
      auto const effect = may_load_store(maybeRef, maybeRef);
      if (inst.src(0)->type().maybe(TArr | TObj | TBoxedArr | TBoxedObj)) {
        // Could re-enter to run a destructor.
        return may_reenter(inst, effect);
      }
      return effect;
    }

  case LdArrFPushCuf:  // autoloads
  case LdArrFuncCtx:   // autoloads
  case LdObjMethod:    // can't autoload, but can decref $this right now
  case LdStrFPushCuf:  // autoload
    /*
     * Note that these instructions make stores to a pre-live actrec on the
     * eval stack.
     *
     * It is probably safe for these instructions to have may-load only from
     * the portion of the evaluation stack below the actrec they are
     * manipulating, but since there's always going to be either a Call or a
     * region exit following it it doesn't help us eliminate anything for now,
     * so we just pretend it can read/write anything on the stack.
     */
    return may_raise(inst, may_load_store(AStackAny, AStackAny));

  case LookupClsMethod:   // autoload, and it writes part of the new actrec
    {
      AliasClass effects = AStack {
        inst.src(2),
        inst.extra<LookupClsMethod>()->offset.offset,
        int32_t{kNumActRecCells}
      };
      return may_raise(inst, may_load_store(effects, effects));
    }

  case LdClsPropAddrOrNull:   // may run 86{s,p}init, which can autoload
  case LdClsPropAddrOrRaise:  // raises errors, and 86{s,p}init
  case BaseG:
  case Clone:
  case RaiseArrayIndexNotice:
  case RaiseArrayKeyNotice:
  case RaiseUninitLoc:
  case RaiseUndefProp:
  case RaiseMissingArg:
  case RaiseError:
  case RaiseNotice:
  case RaiseWarning:
  case ConvCellToStr:
  case ConvObjToStr:
  case Count:      // re-enters on CountableClass
  case CIterFree:  // decrefs context object in iter
  case MIterFree:
  case IterFree:
  case GtObj:
  case GteObj:
  case LtObj:
  case LteObj:
  case EqObj:
  case NeqObj:
  case CmpObj:
  case GtArr:
  case GteArr:
  case LtArr:
  case LteArr:
  case EqArr:
  case NeqArr:
  case CmpArr:
  case DecodeCufIter:
  case ConvCellToArr:  // decrefs src, may read obj props
  case ConvCellToObj:  // decrefs src
  case ConvObjToArr:   // decrefs src
  case GenericIdx:
  case InitProps:
  case InitSProps:
  case OODeclExists:
  case LdCls:          // autoload
  case LdClsCached:    // autoload
  case LdFunc:         // autoload
  case LdFuncCached:   // autoload
  case LdFuncCachedU:  // autoload
  case LdSwitchObjIndex:  // decrefs arg
  case LookupClsCns:      // autoload
  case LookupClsMethodCache:  // autoload
  case LookupClsMethodFCache: // autoload
  case LookupCns:
  case LookupCnsE:
  case LookupCnsU:
  case StringGet:      // raise_warning
  case ArrayAdd:       // decrefs source
  case AddElemIntKey:  // decrefs value
  case AddElemStrKey:  // decrefs value
  case AddNewElem:     // decrefs value
  case ArrayGet:       // kVPackedKind warnings
  case ArrayIsset:     // kVPackedKind warnings
  case ArraySet:       // kVPackedKind warnings
  case ArraySetRef:    // kVPackedKind warnings
  case ElemArray:
  case ElemArrayW:
  case GetMemoKey:     // re-enters to call getInstanceKey() in some cases
  case LdClsCtor:
  case ConcatStrStr:
  case PrintStr:
  case PrintBool:
  case PrintInt:
  case ConcatIntStr:
  case ConcatStrInt:
  case LdSSwitchDestSlow:
  case ConvObjToDbl:
  case ConvObjToInt:
  case MapAddElemC:
  case ColAddNewElemC:
  case CoerceStrToInt:
  case CoerceStrToDbl:
  case CoerceCellToDbl:
  case CoerceCellToInt:
  case CoerceCellToBool:
  case ConvCellToInt:
  case ConvResToStr:
  case ConcatStr3:
  case ConcatStr4:
  case ConvCellToDbl:
  case ThrowOutOfBounds:
  case ThrowInvalidOperation:
    return may_raise(inst, may_load_store(AHeapAny, AHeapAny));

  case ReleaseVVAndSkip:  // can decref ExtraArgs or VarEnv and Locals
    return may_reenter(inst,
                       may_load_store(AHeapAny|AFrameAny, AHeapAny|AFrameAny));

  // These two instructions don't touch memory we track, except that they may
  // re-enter to construct php Exception objects.  During this re-entry anything
  // can happen (e.g. a surprise flag check could cause a php signal handler to
  // run arbitrary code).
  case ABCUnblock:
  case AFWHPrepareChild:
    return may_reenter(inst, may_load_store(AEmpty, AEmpty));

  //////////////////////////////////////////////////////////////////////
  // The following instructions are used for debugging memory optimizations.
  // We can't ignore them, because they can prevent future optimizations;
  // eg t1 = LdStk<N>; DbgTrashStk<N>; StStk<N> t1
  // If we ignore the DbgTrashStk it looks like the StStk is redundant

  case DbgTrashStk:
    return GeneralEffects {
      AEmpty, AEmpty, AEmpty,
      AStack { inst.src(0), inst.extra<DbgTrashStk>()->offset.offset, 1 }
    };
  case DbgTrashFrame:
    return GeneralEffects {
      AEmpty, AEmpty, AEmpty,
      AStack {
        inst.src(0),
        // SpillFrame's spOffset is to the bottom of where it will store the
        // ActRec, but AliasClass needs an offset to the highest cell it will
        // store.
        inst.extra<DbgTrashFrame>()->offset.offset +
          int32_t{kNumActRecCells} - 1,
        int32_t{kNumActRecCells}
      }
    };
  case DbgTrashMem:
    return GeneralEffects {
      AEmpty, AEmpty, AEmpty,
      pointee(inst.src(0))
    };

  //////////////////////////////////////////////////////////////////////

  }

  not_reached();
}
Пример #15
0
	void decodeValue(const std::string& str, T& value)
	{
		std::istringstream is(str);
		is >> std::boolalpha;
		is >> value;
	}
int main(int, char**)
{
    {
        testbuf<char> sb("   abcdefghijk    ");
        std::istream is(&sb);
        signed char s[20];
        is >> s;
        assert(!is.eof());
        assert(!is.fail());
        assert(std::string((char*)s) == "abcdefghijk");
    }
    {
        testbuf<char> sb("   abcdefghijk    ");
        std::istream is(&sb);
        is.width(4);
        signed char s[20];
        is >> s;
        assert(!is.eof());
        assert(!is.fail());
        assert(std::string((char*)s) == "abc");
        assert(is.width() == 0);
    }
#if TEST_STD_VER > 17
    {
        testbuf<char> sb("   abcdefghijk    ");
        std::istream is(&sb);
        signed char s[4];
        is >> s;
        assert(!is.eof());
        assert(!is.fail());
        assert(std::string((char*)s) == "abc");
    }
#endif
    {
        testbuf<char> sb("   abcdefghijk");
        std::istream is(&sb);
        signed char s[20];
        is >> s;
        assert( is.eof());
        assert(!is.fail());
        assert(std::string((char*)s) == "abcdefghijk");
        assert(is.width() == 0);
    }
    {
        testbuf<char> sb("   abcdefghijk");
        std::istream is(&sb);
        signed char s[20];
        is.width(1);
        is >> s;
        assert(!is.eof());
        assert( is.fail());
        assert(std::string((char*)s) == "");
        assert(is.width() == 0);
    }
#if TEST_STD_VER > 17
    {
        testbuf<char> sb("   abcdefghijk");
        std::istream is(&sb);
        signed char s[1];
        is >> s;
        assert(!is.eof());
        assert( is.fail());
        assert(std::string((char*)s) == "");
    }
#endif
#ifndef TEST_HAS_NO_EXCEPTIONS
    {
        testbuf<char> sb;
        std::basic_istream<char> is(&sb);
        is.exceptions(std::ios_base::failbit);

        bool threw = false;
        try {
            signed char s[20];
            is.width(10);
            is >> s;
        } catch (std::ios_base::failure const&) {
            threw = true;
        }

        assert(!is.bad());
        assert(is.fail());
        assert(is.eof());
        assert(threw);
    }
    {
        testbuf<char> sb;
        std::basic_istream<char> is(&sb);
        is.exceptions(std::ios_base::eofbit);

        bool threw = false;
        try {
            signed char s[20];
            is.width(10);
            is >> s;
        } catch (std::ios_base::failure const&) {
            threw = true;
        }

        assert(!is.bad());
        assert(is.fail());
        assert(is.eof());
        assert(threw);
    }
#endif

    return 0;
}
Пример #17
0
/*
*Function: QueryResponse
*Inputs:none
*Outputs:none
*Returns:none
*/
void Iec103driver_Instance::QueryResponse(QObject *p, const QString &c, int id, QObject*caller) // handles database responses
{
	IT_IT("Iec103driver_Instance::QueryResponse");
	
	if(p != this) return;
	switch(id)
	{
		case tListUnits:
		{
			//
			// get the properties - need to be receipe aware 
			//
			unit_name = GetConfigureDb()->GetString("NAME");

			QString pc = 
			"select * from PROPS where SKEY='" + Name + 
			"' and (IKEY = '(default)' or IKEY='"+ GetReceipeName() + "') order by IKEY desc;"; 
			//
			// get the properties SKEY = unit name IKEY = receipe name
			// 
			GetConfigureDb()->DoExec(this,pc,tUnitProperties);

			
			if(GetReceipeName() == "(default)")
			{
				// get the properties for this receipe  - fall back to default
				QString cmd = "select * from SAMPLE where UNIT='" + GetConfigureDb()->GetString("NAME") + "' and ENABLED=1;"; 
				GetConfigureDb()->DoExec(this,cmd,tList);
			}
			else
			{
				QString cmd = 
				"select * from SAMPLE where UNIT='" + GetConfigureDb()->GetString("NAME") + 
				"' and NAME in (" + DriverInstance::FormSamplePointList() + ");"; 
				// only the enabled sample points
				GetConfigureDb()->DoExec(this,cmd,tList);
			};
		}
		break;
		case tList: // list of sample points controlled by the unit
		{
			//  
			// copy the list to local dictionary 
			// now get the properties for each of the sample points
			QString nl; // name list for getting properties
			// 
			for(int ii = 1; ii <= IecItems; ii++) // initialise
			{
				Values[ii].Name = "";
				Values[ii].clear();
			};
			//  
			// 
			int n = GetConfigureDb()->GetNumberResults();
			for(int i = 0; i < n; i++,GetConfigureDb()->FetchNext())
			{
				int idx = GetConfigureDb()->GetInt("IPINDEX");
				if (idx > 0 && idx <= IecItems)
				{
					Values[idx].Name = GetConfigureDb()->GetString("NAME"); // save the name
				};

				if(i)
				{
					nl += ",";
				};

				nl += "'" + GetConfigureDb()->GetString("NAME") + "'";
			};
			
			QString cmd = "select * from PROPS where SKEY='SAMPLEPROPS' and IKEY in ("+nl+");";
			GetConfigureDb()->DoExec(this,cmd,tSamplePointProperties);
		};
		break;
		case tSamplePointProperties://properties specific to a sample point
		{
			int n = GetConfigureDb()->GetNumberResults();
			for(int j = 0; j < n; j++,GetConfigureDb()->FetchNext()) // may get a boat load of properties back
			{  
				// look for the entry in the table
				for(int k = 1; k <= IecItems;k++)
				{
					if(Values[k].Name == GetConfigureDb()->GetString("IKEY"))
					{
//						QString s = UndoEscapeSQLText(GetConfigureDb()->GetString("DVAL"));
//						QTextIStream is(&s); // extract the values
//						QString a;  
//						is >> a; // interval
//						Values[k].SamplePeriod = QStringToInterval(a);
//						Values[k].clear(); // set up
//						is >> a; // now get the 
//						Values[k].Low  = a.toDouble(); // 4 - 20 low value 
//						is >> a;
//						Values[k].High = a.toDouble(); // 4 - 20 high value
//						is >> a;
//						Values[k].fSpotValue = a.toInt(); 
						break;                    
					};
				};
			};
		};
		break;
		case tUnitProperties:
		{
			if(GetConfigureDb()->GetNumberResults() > 0)
			{
				// 
				QString s = UndoEscapeSQLText(GetConfigureDb()->GetString("DVAL")); // the top one is either the receipe or (default)
				QTextIStream is(&s); // extract the values
				//
				is >> IecItems;	  // how many IEC items there are in the RTU or PLC
				is >> Cfg.SampleTime; // how long we sample for in milliseconds
				is >> Cfg.IEC103LinkAddress; // IEC 103 Link Address

				Countdown = 1;

				if(Values)
				{
					delete[] Values;
					Values = NULL;
				}

				Values = new Track[IecItems+1];
				//
				if(InTest())
				{
					Cfg.SampleTime = 1000; // override sampling period
				};
				//

				//Start IEC 103 master driver
				if(!Connect())
				{
					QSLogAlarm(Name,tr("Failed to start IEC 103 client driver"));
				}
			}
		}
		break;
		case tGetSamplePointNamefromIOA:
		{
			QSTransaction &t = GetConfigureDb()->CurrentTransaction();

			if(GetConfigureDb()->GetNumberResults() > 0)
			{
				// 
				#ifdef DEPRECATED_IEC103_CONFIG
				QString SamplePointName = UndoEscapeSQLText(GetConfigureDb()->GetString("IKEY"));
				#else
				QString SamplePointName = UndoEscapeSQLText(GetConfigureDb()->GetString("NAME"));
				#endif


				double v = 0.0;

				if(strlen((const char*)t.Data1) > 0)
				{
					v = atof((const char*)t.Data1);
                    PostValue(SamplePointName, "VALUE", v); //Post the value directly in memory database
				}

				printf("SamplePointName = %s, IOA = %s, value = %lf\n", (const char*)SamplePointName, (const char*)t.Data2, v);
			}
		}
		break;
		case tGetIOAfromSamplePointName:
		{
			QSTransaction &t = GetConfigureDb()->CurrentTransaction();

			if(GetConfigureDb()->GetNumberResults() > 0)
			{
				// 
				#ifdef DEPRECATED_IEC103_CONFIG
				QString IOACommand = UndoEscapeSQLText(GetConfigureDb()->GetString("DVAL"));
				#else
				int IOACommand = GetConfigureDb()->GetInt("IOA");
				#endif
				
				int command_value = 0;

				if(strlen((const char*)t.Data1) > 0)
				{
					command_value = atoi((const char*)t.Data1);
				}

				printf("IOA command = %d, value = %d\n", IOACommand, command_value);

				//Send C_SC_NA_1//////////////////////////////////////////////////////////////////////////
				struct iec_item item_to_send;
				memset(&item_to_send,0x00, sizeof(struct iec_item));
				item_to_send.iec_type = C_SC_NA_1;
				item_to_send.iec_obj.ioa = IOACommand;
				item_to_send.iec_obj.o.type45.scs = command_value;
				item_to_send.msg_id = msg_sent_in_control_direction++;
				item_to_send.checksum = clearCrc((unsigned char *)&item_to_send, sizeof(struct iec_item));
				fifo_put(fifo_control_direction, (char *)&item_to_send, sizeof(struct iec_item));
				///////////////////////////////////////////////////////////////////////////////////////////
			}
		}
		break;
		default:
		break;
	}
Пример #18
0
HOT_FUNC
int SharedVariant::getIndex(const StringData* key) {
  assert(is(KindOfArray));
  if (getIsVector()) return -1;
  return m_data.map->indexOf(key);
}
Пример #19
0
    std::string string_from_file( const wchar_t* file_name, int file_code_page, int string_code_page )
    {
        std::string s;
        std::ifstream is( file_name, std::ios::in | std::ios::binary );

        if ( !is )
        {
            return "";
        }

        unsigned char ch[3] = { 0 };

        is.unsetf( std::ios::skipws );
        is.read( (char*)ch, 3 );

        if ( ch[0] == 0xFF && ch[1] == 0xFE ) // unicode: FF FE
        {
            is.seekg( -2, std::ios::end );
            size_t wsize = is.tellg();
            wchar_t* buf = new wchar_t[wsize/2];
            is.seekg( 2, std::ios::beg );
            is.read( (char*)buf, wsize );
            size_t size = WideCharToMultiByte( CP_UTF8, 0, buf, wsize, 0, 0, 0, 0 );
            s.resize( size );
            WideCharToMultiByte( CP_UTF8, 0, buf, wsize, &s[0], size, 0, 0 );
            delete[] buf;
        }
        else if ( ch[0] == 0xEF && ch[1] == 0xBB && ch[2] == 0xBF ) // utf-8 + BOM: EF BB BF
        {
            is.seekg( -3, std::ios::end );
            size_t size = is.tellg();
            is.seekg( 3, std::ios::beg );

            if ( string_code_page == CP_UTF8 )
            {
                s.resize( size );
                is.read( &s[0], size );
            }
            else
            {
                char* buf = new char[size];
                is.read( buf, size );
                size_t wsize = MultiByteToWideChar( CP_UTF8, 0, buf, size, 0, 0 );
                wchar_t* wbuf = new wchar_t[wsize];
                MultiByteToWideChar( CP_UTF8, 0, buf, size, wbuf, wsize );
                size_t size = WideCharToMultiByte( string_code_page, 0, wbuf, wsize, 0, 0, 0, 0 );
                s.resize( size );
                WideCharToMultiByte( string_code_page, 0, wbuf, wsize, &s[0], size, 0, 0 );
                delete[] buf;
                delete[] wbuf;
            }
        }
        else // ANSI
        {
            is.seekg( 0, std::ios::end );
            size_t size = is.tellg();
            is.seekg( 0, std::ios::beg );

            if ( file_code_page == string_code_page )
            {
                s.resize( size );
                is.read( &s[0], size );
            }
            else
            {
                char* buf = new char[size];
                is.read( buf, size );
                size_t wsize = MultiByteToWideChar( file_code_page, 0, buf, size, 0, 0 );
                wchar_t* wbuf = new wchar_t[wsize];
                MultiByteToWideChar( file_code_page, 0, buf, size, wbuf, wsize );
                size_t size = WideCharToMultiByte( string_code_page, 0, wbuf, wsize, 0, 0, 0, 0 );
                s.resize( size );
                WideCharToMultiByte( string_code_page, 0, wbuf, wsize, &s[0], size, 0, 0 );
                delete[] buf;
                delete[] wbuf;
            }
        }

        return s;
    }
Пример #20
0
/**
 * Updates from a more generic ascii file
 * @param filename :: The input filename
 */
void UpdateInstrumentFromFile::updateFromAscii(const std::string &filename) {
  AsciiFileHeader header;
  const bool isSpectrum = parseAsciiHeader(header);

  // Throws for multiple detectors
  const spec2index_map specToIndex(
      m_workspace->getSpectrumToWorkspaceIndexMap());

  std::ifstream datfile(filename.c_str(), std::ios_base::in);
  const int skipNLines = getProperty("SkipFirstNLines");
  std::string line;
  int lineCount(0);
  while (lineCount < skipNLines) {
    std::getline(datfile, line);
    ++lineCount;
  }

  Geometry::ParameterMap &pmap = m_workspace->instrumentParameters();
  auto &detectorInfo = m_workspace->mutableDetectorInfo();
  const auto &spectrumInfo = m_workspace->spectrumInfo();

  std::vector<double> colValues(header.colCount - 1, 0.0);
  while (std::getline(datfile, line)) {
    boost::trim(line);
    std::istringstream is(line);
    // Column 0 should be ID/spectrum number
    int32_t detOrSpec(-1000);
    is >> detOrSpec;
    // If first thing read is not a number then skip the line
    if (is.fail()) {
      g_log.debug() << "Skipping \"" << line
                    << "\". Cannot interpret as list of numbers.\n";
      continue;
    }

    bool skip{false};
    size_t index = static_cast<size_t>(-1);
    const Geometry::IDetector *det{nullptr};
    if (isSpectrum) {
      auto it = specToIndex.find(detOrSpec);
      if (it != specToIndex.end()) {
        index = it->second;
        if (spectrumInfo.hasDetectors(index)) {
          det = &spectrumInfo.detector(index);
        } else {
          skip = true;
        }
      } else {
        g_log.debug() << "Skipping \"" << line
                      << "\". Spectrum is not in workspace.\n";
        continue;
      }
    } else {
      try {
        index = detectorInfo.indexOf(detOrSpec);
        det = &detectorInfo.detector(index);
      } catch (std::out_of_range &) {
        skip = true;
      }
    }
    if (skip || index == static_cast<size_t>(-1)) {
      g_log.debug()
          << "Skipping \"" << line
          << "\". Spectrum in workspace but cannot find associated detector.\n";
      continue;
    }

    std::vector<size_t> indices;
    if (isSpectrum) {
      if (auto group = dynamic_cast<const Geometry::DetectorGroup *>(det)) {
        for (const auto detID : group->getDetectorIDs())
          indices.push_back(detectorInfo.indexOf(detID));
      } else {
        indices.push_back(detectorInfo.indexOf(det->getID()));
      }
    } else {
      indices.push_back(index);
    }

    // Special cases for detector r,t,p. Everything else is
    // attached as an detector parameter
    double R(0.0), theta(0.0), phi(0.0);
    for (size_t i = 1; i < header.colCount; ++i) {
      double value(0.0);
      is >> value;
      if (i < header.colCount - 1 && is.eof()) {
        // If stringstream is at EOF & we are not at the last column then
        // there aren't enought columns in the file
        throw std::runtime_error("UpdateInstrumentFromFile::updateFromAscii - "
                                 "File contains fewer than expected number of "
                                 "columns, check AsciiHeader property.");
      }

      if (i == header.rColIdx)
        R = value;
      else if (i == header.thetaColIdx)
        theta = value;
      else if (i == header.phiColIdx)
        phi = value;
      else if (header.detParCols.count(i) == 1) {
        for (const auto index : indices) {
          auto id = detectorInfo.detector(index).getComponentID();
          pmap.addDouble(id, header.colToName[i], value);
        }
      }
    }
    // Check stream state. stringstream::EOF should have been reached, if not
    // then there is still more to
    // read and the file has more columns than the header indicated
    if (!is.eof()) {
      throw std::runtime_error("UpdateInstrumentFromFile::updateFromAscii - "
                               "File contains more than expected number of "
                               "columns, check AsciiHeader property.");
    }

    // If not supplied use current values
    double r, t, p;
    if (isSpectrum)
      spectrumInfo.position(index).getSpherical(r, t, p);
    else
      detectorInfo.position(index).getSpherical(r, t, p);
    if (header.rColIdx == 0)
      R = r;
    if (header.thetaColIdx == 0)
      theta = t;
    if (header.phiColIdx == 0 || m_ignorePhi)
      phi = p;

    for (const auto index : indices)
      setDetectorPosition(detectorInfo, index, static_cast<float>(R),
                          static_cast<float>(theta), static_cast<float>(phi));
  }
}
PixelsLabelsArray LoadBIF(const std::string& fileName)
{
    std::ifstream is(fileName, std::ios_base::in | std::ios_base::binary);
	return LoadBIF(is);
}
Пример #22
0
int main(int argc, char* argv[])
{
    int num_checkers, break_duration;
    if(argc != 5)
    {
        cerr << "Error: invalid number of command line arguments." << endl;
        return 1;
    }

    ifstream is(argv[3], ios::in);

    if(!is)
    {
        cerr << "Error: could not open input file <" << argv[3] << ">." << endl;
        return 1;
    }

    ofstream os(argv[4], ios::out);

    if(!os)
    {
        cerr << "Error: could not open output file <" << argv[4] << ">." << endl;
        return 1;
    }

    if(!leg_int(argv[1]))
    {
        cerr << "Error: invalid number of checkers specified." << endl;
        return 1;
    }

    num_checkers = atoi(argv[1]);
    if(num_checkers < 0)
    {
        cerr << "invalid number of checkers specified." << endl;
        return 1;
    }

    if(!leg_int(argv[2]))
    {
        cerr << "Error: invalid checker break duration specified." << endl;
        return 1;
    }
    break_duration = atoi(argv[2]);
    if(break_duration < 0)
    {
        cerr << "Error: invalid checker break duration specified." << endl;
        return 1;
    }

    Pqueue arrival_q;
    string name, shopper;
    int arrival, num_items;
    bool type;
    while(is >> name)
    {
        is >> shopper >> arrival >> num_items;
        if(shopper == "shopper")
            type = true;
        else
            type = false;


        arrival_q.enqueue(new Cust(name, arrival, num_items, type), arrival);
    }

    run_simulation(arrival_q, num_checkers, break_duration, os);

    return 0;
}
Пример #23
0
int
main(void)
{
    SXE_HTTPD    httpd;
    SXE        * client;
    SXE        * client2;
    SXE        * server;
    SXE        * server2;
    tap_ev       event;

    plan_tests(14);

    test_sxe_register_and_init(1000);

    sxe_httpd_construct(&httpd, 2, 10, 512, 0);
    SXE_HTTPD_SET_HANDLER(&httpd, connect, h_connect);
    SXE_HTTPD_SET_HANDLER(&httpd, request, h_request);
    SXE_HTTPD_SET_HANDLER(&httpd, close,   h_close);
    ok((listener = test_httpd_listen(&httpd, "0.0.0.0", 0)) != NULL,                              "HTTPD listening");

    /* Starts two connections, then make a new connection, the oldest will be reaped by the server */
    tap_test_case_name("reap connections");

    /* 1st connection */
    SXEA1((client = test_new_tcp(NULL, "0.0.0.0", 0, client_connect, client_read, client_close)) != NULL,
           "Failed to allocate client SXE");
    SXEA1(sxe_connect(client, "127.0.0.1", SXE_LOCAL_PORT(listener)) == SXE_RETURN_OK,          "Failed to connect to HTTPD");
    is_eq(test_tap_ev_queue_identifier_wait(q_client, TEST_WAIT, &event), "client_connect", "Got 1st client connected event");
    is_eq(test_tap_ev_queue_identifier_wait(q_httpd, TEST_WAIT, &event), "h_connect",     "Got 1st server connect event");
    server = SXE_CAST(SXE *, tap_ev_arg(event, "this"));

    /* 1st client: send a complete request line */
    TEST_SXE_SEND_LITERAL(client, "GET /good HTTP/1.1\r\n", client_sent, q_client, TEST_WAIT, &event);

    /* Waiting for 1st client request state "stable" on "STATE_HEADER" to make
     * sure there is no more state updates on this request object, then the following
     * usleep will guarantee the 1st connection is older than the 2nd one.
     */
    is_eq(test_tap_ev_queue_identifier_wait(q_httpd, TEST_WAIT, &event), "h_request",     "Got 1st server request event");
    is(tap_ev_arg(event, "this"), server,                                                        "It's the 1st server");
    usleep(300000);

    /* 2nd connection, reaping happens, the 1st one got reaped */
    SXEA1((client2 = test_new_tcp(NULL, "0.0.0.0", 0, client_connect, client_read, client_close)) != NULL,
           "Failed to allocate client SXE");
    SXEA1(sxe_connect(client2, "127.0.0.1", SXE_LOCAL_PORT(listener)) == SXE_RETURN_OK,         "Failed to connect to HTTPD");

    is_eq(test_tap_ev_queue_identifier_wait(q_httpd, TEST_WAIT, &event), "h_connect",     "Got 2nd server connect event");
    server2 = SXE_CAST(SXE *, tap_ev_arg(event, "this"));
    is_eq(test_tap_ev_queue_identifier_wait(q_httpd, TEST_WAIT, &event), "h_close",       "Got a server close event");
    is(tap_ev_arg(event, "this"), server,                                                        "It's the 1st server");

    /* Pull these two arguments off in any order */
    test_process_all_libev_events();
    ok((event = tap_ev_queue_shift_next(q_client, "client_connect")) != NULL, "Got 2nd client connected event");
    ok((event = tap_ev_queue_shift_next(q_client, "client_close")) != NULL, "Got a client close event");
    is(tap_ev_arg(event, "this"), client,                                                        "It's the 1st client");

    is(tap_ev_queue_length(q_httpd),                                         0,                "No server events lurking");
    is(tap_ev_queue_length(q_client),                                         0,                "No client events lurking");

    sxe_close(listener);
    return exit_status();
}
Пример #24
0
int main(int argc, char** argv)
{
  try {
    options(argc, argv);
    
    if (grammar_list) {
      std::cout << grammar_type::lists();
      return 0;
    }
    
    if (tree_grammar_list) {
      std::cout << tree_grammar_type::lists();
      return 0;
    }
    
    threads = utils::bithack::max(1, threads);

    // read grammars...
    grammar_type grammar(grammar_files.begin(), grammar_files.end());
    if (debug)
      std::cerr << "grammar: " << grammar.size() << std::endl;
    
    tree_grammar_type tree_grammar(tree_grammar_files.begin(), tree_grammar_files.end());
    if (debug)
      std::cerr << "tree grammar: " << tree_grammar.size() << std::endl;

    typedef Task task_type;
    typedef std::vector<task_type, std::allocator<task_type> > task_set_type;
    
    task_type::queue_type queue(threads);
    task_set_type tasks(threads, task_type(queue, tree_grammar, grammar));
    
    boost::thread_group workers;
    for (int i = 0; i != threads; ++ i)
      workers.add_thread(new boost::thread(boost::ref(tasks[i])));
    
    utils::compress_istream is(input_file, 1024 * 1024);
    
    std::string line;
    while (utils::getline(is, line))
      if (! line.empty())
	queue.push_swap(line);
    
    for (int i = 0; i != threads; ++ i)
      queue.push(std::string());
    
    workers.join_all();

    tree_rule_pair_unique_type tree_rules_unique;
    rule_pair_unique_type      rules_unique;
    
    for (int i = 0; i != threads; ++ i) {
      if (tree_rules_unique.empty())
	tree_rules_unique.swap(tasks[i].tree_rules_unique);
      else
	tree_rules_unique.insert(tasks[i].tree_rules_unique.begin(), tasks[i].tree_rules_unique.end());
      
      tasks[i].tree_rules_unique.clear();
      
      if (rules_unique.empty())
	rules_unique.swap(tasks[i].rules_unique);
      else
	rules_unique.insert(tasks[i].rules_unique.begin(), tasks[i].rules_unique.end());
      
      tasks[i].rules_unique.clear();
    }
    tasks.clear();

    typedef std::ostream_iterator<char> oiter_type;

    features_generator<oiter_type>   generate_features;
    attributes_generator<oiter_type> generate_attributes;
    
    if (! output_tree_file.empty()) {
      namespace karma = boost::spirit::karma;
      namespace standard = boost::spirit::standard;
      
      utils::compress_ostream os(output_tree_file, 1024 * 1024);
      
      tree_rule_pair_unique_type::const_iterator iter_end = tree_rules_unique.end();
      for (tree_rule_pair_unique_type::const_iterator iter = tree_rules_unique.begin(); iter != iter_end; ++ iter) {
	os << iter->source.decode() << " ||| " << iter->target.decode();
	
	if (! iter->features.empty()) {
	  feature_set_type features(iter->features.begin(), iter->features.end());
	  karma::generate(oiter_type(os), generate_features, features);
	}
	
	if (! iter->attributes.empty())
	  karma::generate(oiter_type(os), generate_attributes, iter->attributes);
	os << '\n';
      }
    }
    
    if (! output_rule_file.empty()) {
      namespace karma = boost::spirit::karma;
      namespace standard = boost::spirit::standard;
      
      utils::compress_ostream os(output_rule_file, 1024 * 1024);
      
      rule_pair_unique_type::const_iterator iter_end = rules_unique.end();
      for (rule_pair_unique_type::const_iterator iter = rules_unique.begin(); iter != iter_end; ++ iter) {
	karma::generate(oiter_type(os),
			standard::string << " ||| " << -(standard::string % ' ') << " ||| " << -(standard::string % ' '),
			iter->lhs,
			symbol_set_type(iter->source.begin(), iter->source.end()),
			symbol_set_type(iter->target.begin(), iter->target.end()));
	
	if (! iter->features.empty()) {
	  feature_set_type features(iter->features.begin(), iter->features.end());
	  karma::generate(oiter_type(os), generate_features, features);
	}
	
	if (! iter->attributes.empty())
	  karma::generate(oiter_type(os), generate_attributes, iter->attributes);
	os << '\n';
      }
    }
  }
  catch (const std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}
Пример #25
0
MapBlock* Database_Dummy::loadBlock(v3s16 blockpos)
{
	v2s16 p2d(blockpos.X, blockpos.Z);

        if(m_database.count(getBlockAsString(blockpos))) {
                /*
                        Load block
                */
                std::string datastr = m_database[getBlockAsString(blockpos)];
//                srvmap->loadBlock(&datastr, blockpos, sector, false);

		try {
                	std::istringstream is(datastr, std::ios_base::binary);
                   	u8 version = SER_FMT_VER_INVALID;
                     	is.read((char*)&version, 1);

                     	if(is.fail())
                             	throw SerializationError("ServerMap::loadBlock(): Failed"
                                	             " to read MapBlock version");

                     	MapBlock *block = NULL;
                     	bool created_new = false;
                     	block = srvmap->getBlockNoCreateNoEx(blockpos);
                     	if(block == NULL)
                     	{
                             	block = srvmap->createBlankBlockNoInsert(blockpos);
                             	created_new = true;
                     	}
                     	// Read basic data
                     	block->deSerialize(is, version, true);
                     	// If it's a new block, insert it to the map
                     	if(created_new)
                             	srvmap->insertBlock(block);
                     	/*
                             	Save blocks loaded in old format in new format
                     	*/

                     	//if(version < SER_FMT_VER_HIGHEST || save_after_load)
                     	// Only save if asked to; no need to update version
                     	//if(save_after_load)
                        //     	saveBlock(block);
                     	// We just loaded it from, so it's up-to-date.
                     	block->resetModified();

             	}
             	catch(SerializationError &e)
             	{
                     	errorstream<<"Invalid block data in database"
                                     <<" ("<<blockpos.X<<","<<blockpos.Y<<","<<blockpos.Z<<")"
                                     <<" (SerializationError): "<<e.what()<<std::endl;
                     // TODO: Block should be marked as invalid in memory so that it is
                     // not touched but the game can run

                     	if(g_settings->getBool("ignore_world_load_errors")){
                             errorstream<<"Ignoring block load error. Duck and cover! "
                                             <<"(ignore_world_load_errors)"<<std::endl;
                     	} else {
                             throw SerializationError("Invalid block data in database");
                             //assert(0);
                     	}
             	}

                return srvmap->getBlockNoCreateNoEx(blockpos);  // should not be using this here
        }
	return(NULL);
}
    bool callMvRecognizerUsingFiles()
    {
        std::vector<std::string> test_cloud;
        v4r::io::getFilesInDirectory(directory_, test_cloud, "", ".*.pcd", false);
        for(size_t i=0; i < test_cloud.size(); i++)
        {
            pcl::PointCloud<PointT> cloud;
            pcl::io::loadPCDFile(directory_ + "/" + test_cloud[i], cloud);
            sensor_msgs::PointCloud2 cloud_ros;
            pcl::toROSMsg(cloud, cloud_ros);
            cloud_ros.header.stamp = ros::Time::now();
            recognition_srv_definitions::recognize srv_rec;
            srv_rec.request.cloud = cloud_ros;
            std::stringstream view_name_ss;
            view_name_ss << "view_" << i << std::endl;
            std::cout << "####### " << view_name_ss.str() << std::endl;
            srv_rec.request.view_name.data = view_name_ss.str();

            std::string pose_file = test_cloud[i];
            boost::replace_all(pose_file, ".pcd", ".txt");

#ifdef USE_WILLOW_DATASET_FOR_EVAL
            boost::replace_all(pose_file, "cloud_", "pose_");
#else
            pose_file = "transformation_" + pose_file;
#endif
            std::cout << "Checking if path " << directory_ << "/" << pose_file << " for transform exists. " << std::endl;

            if ( boost::filesystem::exists( directory_ + "/" + pose_file ) )
            {
                std::cout << "File exists." << std::endl;
                std::ifstream is( (directory_ + "/" + pose_file).c_str() );

#ifdef USE_WILLOW_DATASET_FOR_EVAL
                std::string s;
                std::vector<std::string> file_parts;
                std::getline( is, s );
                std::istringstream ss( s );
                std::vector<double> numbers;
                while (ss)
                {
                  std::string s;
                  if (!std::getline( ss, s, ' ' )) break;
                  file_parts.push_back( s );
                  if(file_parts.size()>1)
                      numbers.push_back(atof(s.c_str()));
                }
#else
                std::istream_iterator<double> start(is), end;
                std::vector<float> numbers(start, end);
                std::cout << "Read " << numbers.size() << " numbers" << std::endl;
#endif
                // print the numbers to stdout
                std::cout << "Transform to world coordinate system: " << std::endl;
                for(size_t i=0; i<numbers.size(); i++)
                {
                    std::cout << numbers[i] << " ";
                    srv_rec.request.transform.push_back(numbers[i]);
                }
                std::cout << std::endl;
            }

            if (!sv_rec_client_.call(srv_rec))
            {
                ROS_ERROR("Error calling multiview recognition service. ");
                return false;
            }
        }
        return true;
    }
Пример #27
0
void MySqlImpl::upload(vector<ResultEntity>& rs, string user, string logDir)
{
	try
	{
		sql::PreparedStatement *prep_stmt;
		
		string sql = "INSERT INTO tbl_interactions(user_name, timestamp, window, parent_window, application, point_x, point_y, win_rect_left, win_rect_top, win_rect_right, win_rect_bottom, \
						ui_name, ui_type, ui_value, parent_ui_name, parent_ui_type, ui_bound_left, ui_bound_top, ui_bound_right, ui_bound_bottom, has_screen, screen) \
													   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		prep_stmt = conn->prepareStatement(sql.c_str());

		for(int i=0; i<rs.size(); i++)
		{
			int idx = 1;
			prep_stmt->setString(idx++, user.c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("timestamp").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("window_name").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("parent_window").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("process_name").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("p_x").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("p_y").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("win_rect_left").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("win_rect_top").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("win_rect_right").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("win_rect_bottom").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("action_name").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("action_type").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("action_value").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("action_parent_name").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("action_parent_type").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("bound_left").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("bound_top").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("bound_right").c_str());
			prep_stmt->setString(idx++, rs[i].getColumn("bound_bottom").c_str());

			string imgPath = logDir + "/screen/" + dbTime2ImgTime(rs[i].getColumn("timestamp")) + ".png";
			ifstream is(imgPath, std::ios_base::binary);
			if(is.is_open())
			{
				prep_stmt->setBoolean(idx++, true);
				prep_stmt->setBlob(idx++, &is);
			}
			else
			{
				prep_stmt->setBoolean(idx++, false);
				prep_stmt->setBlob(idx++, NULL);
			}

			prep_stmt->execute();

			is.close();

			//std::remove(imgPath.c_str());
		}

		delete prep_stmt;
	}
	catch(sql::SQLException &exception)
	{
		printException(exception);
	}
	
}
Пример #28
0
int
main(int argc, char *argv[])
{
  plan(TEST_COUNT);

  av_log_set_level(AV_LOG_ERROR);

  // Get path to this binary
  char *bin = _findbin(argv[0]);

  // Test scanning a single file
  {
    char *file = _abspath(bin, "../data/video/bars-vp6f-mp3.flv");
    ScanData s = mediascan_scan_file(file, 0);

    ok(s->error == 0, "scan_file s->error ok");
    is(s->path, file, "scan_file s->path ok");
    ok(s->flags == 0, "scan_file s->flags ok");
    ok(s->type == TYPE_VIDEO, "scan_file s->type is TYPE_VIDEO");
    is(s->type_name, "FLV format", "scan_file s->type_name ok");
    ok(s->bitrate == 507, "scan_file s->bitrate ok");
    ok(s->duration_ms == 6000, "scan_file s->duration_ms ok");

    ok(s->nstreams == 2, "scan_file s->nstreams ok");
    ok(s->streams[0].type == TYPE_VIDEO, "scan_file s->streams[0].type ok");
    is(s->streams[0].codec_name, "vp6f", "scan_file s->streams[0].codec_name ok");
    ok(s->streams[0].bitrate == 409, "scan_file s->streams[0].bitrate ok");
    ok(s->streams[0].width == 360, "scan_file s->streams[0].width ok");
    ok(s->streams[0].height == 288, "scan_file s->streams[0].height ok");
    ok(s->streams[0].fps == 0, "scan_file s->streams[0].fps ok");
    ok(s->streams[1].type == TYPE_AUDIO, "scan_file s->streams[1].type ok");
    is(s->streams[1].codec_name, "mp3", "scan_file s->streams[1].codec_name ok");
    ok(s->streams[1].bitrate == 98, "scan_file s->streams[1].bitrate ok");
    ok(s->streams[1].samplerate == 44100, "scan_file s->streams[1].samplerate ok");
    ok(s->streams[1].channels == 2, "scan_file s->streams[1].channels ok");

    // AVMetadata, XXX use our own Metadata stuff
    int i = 0;
    AVMetadataTag *tag = NULL;
    while ((tag = av_metadata_get(s->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
      switch (i) {
        case 0:
          is(tag->key, "duration", "scan_file s->metadata key %d ok", i);
          is(tag->value, "6", "scan_file s->metadata value %d ok", i);
          break;
        case 1:
          is(tag->key, "width", "scan_file s->metadata key %d ok", i);
          is(tag->value, "360", "scan_file s->metadata value %d ok", i);
          break;
        case 2:
          is(tag->key, "height", "scan_file s->metadata key %d ok", i);
          is(tag->value, "288", "scan_file s->metadata value %d ok", i);
          break;
        case 3:
          is(tag->key, "videodatarate", "scan_file s->metadata key %d ok", i);
          is(tag->value, "400", "scan_file s->metadata value %d ok", i);
          break;
        case 4:
          is(tag->key, "framerate", "scan_file s->metadata key %d ok", i);
          is(tag->value, "10", "scan_file s->metadata value %d ok", i);
          break;
        case 5:
          is(tag->key, "videocodecid", "scan_file s->metadata key %d ok", i);
          is(tag->value, "4", "scan_file s->metadata value %d ok", i);
          break;
        case 6:
          is(tag->key, "audiodatarate", "scan_file s->metadata key %d ok", i);
          is(tag->value, "96", "scan_file s->metadata value %d ok", i);
          break;
        case 7:
          is(tag->key, "audiodelay", "scan_file s->metadata key %d ok", i);
          is(tag->value, "0", "scan_file s->metadata value %d ok", i);
          break;
        case 8:
          is(tag->key, "audiocodecid", "scan_file s->metadata key %d ok", i);
          is(tag->value, "2", "scan_file s->metadata value %d ok", i);
          break;
        case 9:
          is(tag->key, "canSeekToEnd", "scan_file s->metadata key %d ok", i);
          is(tag->value, "true", "scan_file s->metadata value %d ok", i);
          break;
        default:
          fail("Invalid metadata");
          break;
      }
      i++;
    }

    mediascan_free_ScanData(s);
    free(file);
  }

  // Non-media file extension
  {
    ScanData s = mediascan_scan_file(bin, 0);
    ok(s == NULL, "scan_file on non-media file ok");
  }

  // Media extension but corrupt data
  {
    char *file = _abspath(bin, "../data/video/corrupt.mp4");
    ScanData s = mediascan_scan_file(file, 0);

    ok(s->error == SCAN_FILE_OPEN, "scan_file on corrupt mp4 file ok");

    mediascan_free_ScanData(s);
    free(file);
  }

  free(bin);

  return exit_status();
}
Пример #29
0
int
main(void) {
    struct object   self;
    struct object * this = &self;

    plan_tests(47);

    /* Test sxe_return_to_string()
     */
    is_eq(sxe_return_to_string(SXE_RETURN_OK),             "OK"            , "sxe_return_to_string(SXE_RETURN_OK) eq \"OK\"");
    is_eq(sxe_return_to_string(SXE_RETURN_ERROR_INTERNAL), "ERROR_INTERNAL", "sxe_return_to_string(SXE_RETURN_ERROR_INTERNAL) eq \"ERROR_INTERNAL\"");
    is(   sxe_return_to_string(~0U),                        NULL,            "sxe_return_to_string(~0U) == NULL");
    TEST_CASE_RETURN_TO_STRING(EXPIRED_VALUE);
    TEST_CASE_RETURN_TO_STRING(NO_UNUSED_ELEMENTS);
    TEST_CASE_RETURN_TO_STRING(IN_PROGRESS);
    TEST_CASE_RETURN_TO_STRING(UNCATEGORIZED);
    TEST_CASE_RETURN_TO_STRING(END_OF_FILE);
    TEST_CASE_RETURN_TO_STRING(WARN_ALREADY_INITIALIZED);
    TEST_CASE_RETURN_TO_STRING(WARN_WOULD_BLOCK);
    TEST_CASE_RETURN_TO_STRING(WARN_ALREADY_CLOSED);
    TEST_CASE_RETURN_TO_STRING(ERROR_NOT_INITIALIZED);
    TEST_CASE_RETURN_TO_STRING(ERROR_ALLOC);
    TEST_CASE_RETURN_TO_STRING(ERROR_NO_CONNECTION);
    TEST_CASE_RETURN_TO_STRING(ERROR_ALREADY_CONNECTED);
    TEST_CASE_RETURN_TO_STRING(ERROR_INVALID_URI);
    TEST_CASE_RETURN_TO_STRING(ERROR_BAD_MESSAGE);
    TEST_CASE_RETURN_TO_STRING(ERROR_ADDRESS_IN_USE);
    TEST_CASE_RETURN_TO_STRING(ERROR_INTERRUPTED);
    TEST_CASE_RETURN_TO_STRING(ERROR_COMMAND_NOT_RUN);
    TEST_CASE_RETURN_TO_STRING(ERROR_LOCK_NOT_TAKEN);
    TEST_CASE_RETURN_TO_STRING(ERROR_INCORRECT_STATE);
    TEST_CASE_RETURN_TO_STRING(ERROR_TIMED_OUT);
    TEST_CASE_RETURN_TO_STRING(ERROR_WRITE_FAILED);
    TEST_CASE_RETURN_TO_STRING(INVALID_VALUE);           /* Just for coverage */

    ok(signal(SIGABRT, test_abort_handler) != SIG_ERR, "Caught abort signal");
    sxe_log_hook_line_out(NULL); /* for coverage */
    sxe_log_hook_line_out(log_line);
    PUTENV("SXE_LOG_LEVEL=6");   /* Trigger processing of the level in the first call to the log */
    SXEE60(entering);
    PUTENV("SXE_LOG_LEVEL=1");   /* This should be ignored. If it is not, the tests will fail    */
    this->id = 99;
    SXEL60I(logging);
    SXEA60(1, "Asserting true");
    SXED60(dumpdata, 4);
    SXER60(exiting);
    SXEL60(verylong);
    SXEE61("really long entry message: %s", verylong);
    SXEL60(escape);
    SXEL60(hextrunc);
    SXED60(dumpdata, 0);    /* Edge case */
    SXEA80(1, "We should not get this, because level 8 is too low!");

    is(sxe_log_decrease_level(SXE_LOG_LEVEL_ERROR),       SXE_LOG_LEVEL_TRACE,       "Level decreased to ERROR (2) from TRACE (6)");
    is(sxe_log_set_level(     SXE_LOG_LEVEL_INFORMATION), SXE_LOG_LEVEL_ERROR,       "Level set to INFO, was ERROR");
    is(sxe_log_decrease_level(SXE_LOG_LEVEL_TRACE),       SXE_LOG_LEVEL_INFORMATION, "Level was INFO, TRACE is not a decrease");

#if defined(_WIN32) && defined(LOCAL_SXE_DEBUG)
    skip(3, "Can't test aborts in a Windows debug build, due to pop up Window stopping the build");
#else
    SXEA60(this != &self, "This is not self");  /* Abort - must be the last thing we do*/
    fail("Did not catch an abort signal");
#endif
    }    /* Oog! Close the brace opened in the SXEE61 macro above */
Пример #30
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av );
        if( options.exists( "--help" ) || options.exists( "-h" ) || ac == 1 ) { usage(); }
        options.assert_mutually_exclusive( "--by-lower,--by-upper,--nearest" );
        bool by_upper = options.exists( "--by-upper" );
        bool nearest = options.exists( "--nearest" );
        bool by_lower = ( options.exists( "--by-lower" ) || !by_upper ) && !nearest;
        //bool nearest_only = options.exists( "--nearest-only" );
        bool timestamp_only = options.exists( "--timestamp-only,--time-only" );
        bool discard = !options.exists( "--no-discard" );
        boost::optional< boost::posix_time::time_duration > bound;
        if( options.exists( "--bound" ) ) { bound = boost::posix_time::microseconds( options.value< double >( "--bound" ) * 1000000 ); }
        comma::csv::options stdin_csv( options, "t" );
        //bool has_block = stdin_csv.has_field( "block" );
        comma::csv::input_stream< Point > stdin_stream( std::cin, stdin_csv );
        std::string properties = options.unnamed( "--by-lower,--by-upper,--nearest,--timestamp-only,--time-only,--no-discard", "--binary,-b,--delimiter,-d,--fields,-f,--bound" )[0];
        comma::io::istream is( comma::split( properties, ';' )[0] );
        comma::name_value::parser parser( "filename" );
        comma::csv::options csv = parser.get< comma::csv::options >( properties );
        if( csv.fields.empty() ) { csv.fields = "t"; }
        comma::csv::input_stream< Point > istream( *is, csv );
        std::pair< std::string, std::string > last;
        std::pair< boost::posix_time::ptime, boost::posix_time::ptime > last_timestamp;
        comma::signal_flag is_shutdown;
        while( !is_shutdown && std::cin.good() && !std::cin.eof() && is->good() && !is->eof() )
        {
            const Point* p = stdin_stream.read();
            if( !p ) { break; }
            bool eof = false;
            while( last_timestamp.first.is_not_a_date_time() || p->timestamp >= last_timestamp.second )
            {
                last_timestamp.first = last_timestamp.second;
                last.first = last.second;
                const Point* q = istream.read();
                if( !q ) { eof = true; break; }
                last_timestamp.second = q->timestamp;
                if( !timestamp_only )
                {
                    if( csv.binary() ) { last.second = std::string( istream.binary().last(), csv.format().size() ); }
                    else { last.second = comma::join( istream.ascii().last(), stdin_csv.delimiter ); }
                }
            }
            if( eof ) { break; }
            if( discard && p->timestamp < last_timestamp.first ) { continue; }
            bool is_first = by_lower || ( nearest && ( p->timestamp - last_timestamp.first ) < ( last_timestamp.second - p->timestamp ) );
            const boost::posix_time::ptime& t = is_first ? last_timestamp.first : last_timestamp.second;
            if( bound && !( ( t - *bound ) <= p->timestamp && p->timestamp <= ( t + *bound ) ) ) { continue; }
            const std::string& s = is_first ? last.first : last.second;
            if( stdin_csv.binary() )
            {
                std::cout.write( stdin_stream.binary().last(), stdin_csv.format().size() );
                if( timestamp_only )
                {
                    static comma::csv::binary< Point > b;
                    std::vector< char > v( b.format().size() );
                    b.put( Point( t ), &v[0] );
                    std::cout.write( &v[0], b.format().size() );
                }
                else
                {
                    std::cout.write( &s[0], s.size() );
                }
                std::cout.flush();
            }
            else
            {
                std::cout << comma::join( stdin_stream.ascii().last(), stdin_csv.delimiter );
                std::cout << stdin_csv.delimiter;
                if( timestamp_only ) { std::cout << boost::posix_time::to_iso_string( t ) << std::endl; }
                else { std::cout << s << std::endl; }
            }
        }
        if( is_shutdown ) { std::cerr << "csv-time-join: interrupted by signal" << std::endl; }
        return 0;     
    }
    catch( std::exception& ex ) { std::cerr << "csv-time-join: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "csv-time-join: unknown exception" << std::endl; }
    usage();
}