<commit_before>#include "tests-base.hpp"

#include "utf8rewind.h"

#include "helpers-strings.hpp"

class QuickbrownCaseMapping
	: public ::testing::Test
{

protected:

	void SetUp()
	{
		errors = 0;

		fileRegular.open("testdata/quickbrown.txt", std::ios_base::in);
		ASSERT_TRUE(fileRegular.is_open());

		fileUppercase.open("testdata/quickbrown_uppercase.txt", std::ios_base::in);
		ASSERT_TRUE(fileUppercase.is_open());

		fileLowercase.open("testdata/quickbrown_lowercase.txt", std::ios_base::in);
		ASSERT_TRUE(fileLowercase.is_open());
	}

	void TearDown()
	{
		fileLowercase.close();
		fileUppercase.close();
		fileRegular.close();
	}

	std::string ReadRegular(size_t position, size_t length)
	{
		std::string result;

		fileRegular.seekg(position, std::ios::beg);
		if (fileRegular.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileRegular.read(&result[0], length);

		return result;
	}

	std::string ReadUppercase(size_t position, size_t length)
	{
		std::string result;

		fileUppercase.seekg(position, std::ios::beg);
		if (fileUppercase.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileUppercase.read(&result[0], length);

		return result;
	}

	std::string ReadLowercase(size_t position, size_t length)
	{
		std::string result;

		fileLowercase.seekg(position, std::ios::beg);
		if (fileLowercase.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileLowercase.read(&result[0], length);

		return result;
	}

	std::fstream fileRegular;
	std::fstream fileUppercase;
	std::fstream fileLowercase;
	int32_t errors;

};

TEST_F(QuickbrownCaseMapping, DanishUppercase)
{
	std::string i = ReadRegular(271, 95);
	EXPECT_STREQ("  Quizdeltagerne spiste jordb\xc3\xa6r med fl\xc3\xb8" "de, mens cirkusklovnen\x0a  Wolther spillede p\xc3\xa5 xylofon.", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(271, 95);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, DanishLowercase)
{
	std::string i = ReadRegular(271, 95);
	EXPECT_STREQ("  Quizdeltagerne spiste jordb\xc3\xa6r med fl\xc3\xb8" "de, mens cirkusklovnen\x0a  Wolther spillede p\xc3\xa5 xylofon.", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(271, 95);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanFirstUppercase)
{
	std::string i = ReadRegular(503, 64);
	EXPECT_STREQ("  Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(503, 64);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanFirstLowercase)
{
	std::string i = ReadRegular(503, 64);
	EXPECT_STREQ("  Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(503, 64);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanSecondUppercase)
{
	std::string i = ReadRegular(642, 59);
	EXPECT_STREQ("  Zw\xC3\xB6lf Boxk\xC3\xA4mpfer jagten Eva quer \xC3\xBC" "ber den Sylter Deich", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(642, 59);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanSecondLowercase)
{
	std::string i = ReadRegular(642, 59);
	EXPECT_STREQ("  Zw\xC3\xB6lf Boxk\xC3\xA4mpfer jagten Eva quer \xC3\xBC" "ber den Sylter Deich", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(642, 59);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanThirdUppercase)
{
	std::string i = ReadRegular(767, 30);
	EXPECT_STREQ("  Heiz\xC3\xB6lr\xC3\xBC" "cksto\xC3\x9F" "abd\xC3\xA4mpfung", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(767, 30);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanThirdLowercase)
{
	std::string i = ReadRegular(767, 30);
	EXPECT_STREQ("  Heiz\xC3\xB6lr\xC3\xBC" "cksto\xC3\x9F" "abd\xC3\xA4mpfung", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(767, 30);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GreekFirstUppercase)
{
	std::string i = ReadRegular(911, 105);
	EXPECT_STREQ("  \xCE\x93\xCE\xB1\xCE\xB6\xCE\xAD\xCE\xB5\xCF\x82 \xCE\xBA\xCE\xB1\xE1\xBD\xB6 \xCE\xBC\xCF\x85\xCF\x81\xCF\x84\xCE\xB9\xE1\xBD\xB2\xCF\x82 \xCE\xB4\xE1\xBD\xB2\xCE\xBD \xCE\xB8\xE1\xBD\xB0 \xCE\xB2\xCF\x81\xE1\xBF\xB6 \xCF\x80\xCE\xB9\xE1\xBD\xB0 \xCF\x83\xCF\x84\xE1\xBD\xB8 \xCF\x87\xCF\x81\xCF\x85\xCF\x83\xCE\xB1\xCF\x86\xE1\xBD\xB6 \xCE\xBE\xCE\xAD\xCF\x86\xCF\x89\xCF\x84\xCE\xBF", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(911, 106);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GreekFirstLowercase)
{
	std::string i = ReadRegular(911, 105);
	EXPECT_STREQ("  \xCE\x93\xCE\xB1\xCE\xB6\xCE\xAD\xCE\xB5\xCF\x82 \xCE\xBA\xCE\xB1\xE1\xBD\xB6 \xCE\xBC\xCF\x85\xCF\x81\xCF\x84\xCE\xB9\xE1\xBD\xB2\xCF\x82 \xCE\xB4\xE1\xBD\xB2\xCE\xBD \xCE\xB8\xE1\xBD\xB0 \xCE\xB2\xCF\x81\xE1\xBF\xB6 \xCF\x80\xCE\xB9\xE1\xBD\xB0 \xCF\x83\xCF\x84\xE1\xBD\xB8 \xCF\x87\xCF\x81\xCF\x85\xCF\x83\xCE\xB1\xCF\x86\xE1\xBD\xB6 \xCE\xBE\xCE\xAD\xCF\x86\xCF\x89\xCF\x84\xCE\xBF", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(911, 105);
	EXPECT_UTF8EQ(el, al);
}<commit_msg>integration-quickbrown-casemapping: Added test for uppercasing second Greek string.<commit_after>#include "tests-base.hpp"

#include "utf8rewind.h"

#include "helpers-strings.hpp"

class QuickbrownCaseMapping
	: public ::testing::Test
{

protected:

	void SetUp()
	{
		errors = 0;

		fileRegular.open("testdata/quickbrown.txt", std::ios_base::in);
		ASSERT_TRUE(fileRegular.is_open());

		fileUppercase.open("testdata/quickbrown_uppercase.txt", std::ios_base::in);
		ASSERT_TRUE(fileUppercase.is_open());

		fileLowercase.open("testdata/quickbrown_lowercase.txt", std::ios_base::in);
		ASSERT_TRUE(fileLowercase.is_open());
	}

	void TearDown()
	{
		fileLowercase.close();
		fileUppercase.close();
		fileRegular.close();
	}

	std::string ReadRegular(size_t position, size_t length)
	{
		std::string result;

		fileRegular.seekg(position, std::ios::beg);
		if (fileRegular.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileRegular.read(&result[0], length);

		return result;
	}

	std::string ReadUppercase(size_t position, size_t length)
	{
		std::string result;

		fileUppercase.seekg(position, std::ios::beg);
		if (fileUppercase.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileUppercase.read(&result[0], length);

		return result;
	}

	std::string ReadLowercase(size_t position, size_t length)
	{
		std::string result;

		fileLowercase.seekg(position, std::ios::beg);
		if (fileLowercase.eof())
		{
			return result;
		}

		result.resize(length + 1);
		fileLowercase.read(&result[0], length);

		return result;
	}

	std::fstream fileRegular;
	std::fstream fileUppercase;
	std::fstream fileLowercase;
	int32_t errors;

};

TEST_F(QuickbrownCaseMapping, DanishUppercase)
{
	std::string i = ReadRegular(271, 95);
	EXPECT_STREQ("  Quizdeltagerne spiste jordb\xc3\xa6r med fl\xc3\xb8" "de, mens cirkusklovnen\x0a  Wolther spillede p\xc3\xa5 xylofon.", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(271, 95);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, DanishLowercase)
{
	std::string i = ReadRegular(271, 95);
	EXPECT_STREQ("  Quizdeltagerne spiste jordb\xc3\xa6r med fl\xc3\xb8" "de, mens cirkusklovnen\x0a  Wolther spillede p\xc3\xa5 xylofon.", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(271, 95);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanFirstUppercase)
{
	std::string i = ReadRegular(503, 64);
	EXPECT_STREQ("  Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(503, 64);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanFirstLowercase)
{
	std::string i = ReadRegular(503, 64);
	EXPECT_STREQ("  Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(503, 64);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanSecondUppercase)
{
	std::string i = ReadRegular(642, 59);
	EXPECT_STREQ("  Zw\xC3\xB6lf Boxk\xC3\xA4mpfer jagten Eva quer \xC3\xBC" "ber den Sylter Deich", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(642, 59);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanSecondLowercase)
{
	std::string i = ReadRegular(642, 59);
	EXPECT_STREQ("  Zw\xC3\xB6lf Boxk\xC3\xA4mpfer jagten Eva quer \xC3\xBC" "ber den Sylter Deich", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(642, 59);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GermanThirdUppercase)
{
	std::string i = ReadRegular(767, 30);
	EXPECT_STREQ("  Heiz\xC3\xB6lr\xC3\xBC" "cksto\xC3\x9F" "abd\xC3\xA4mpfung", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(767, 30);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GermanThirdLowercase)
{
	std::string i = ReadRegular(767, 30);
	EXPECT_STREQ("  Heiz\xC3\xB6lr\xC3\xBC" "cksto\xC3\x9F" "abd\xC3\xA4mpfung", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(767, 30);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GreekFirstUppercase)
{
	std::string i = ReadRegular(911, 105);
	EXPECT_STREQ("  \xCE\x93\xCE\xB1\xCE\xB6\xCE\xAD\xCE\xB5\xCF\x82 \xCE\xBA\xCE\xB1\xE1\xBD\xB6 \xCE\xBC\xCF\x85\xCF\x81\xCF\x84\xCE\xB9\xE1\xBD\xB2\xCF\x82 \xCE\xB4\xE1\xBD\xB2\xCE\xBD \xCE\xB8\xE1\xBD\xB0 \xCE\xB2\xCF\x81\xE1\xBF\xB6 \xCF\x80\xCE\xB9\xE1\xBD\xB0 \xCF\x83\xCF\x84\xE1\xBD\xB8 \xCF\x87\xCF\x81\xCF\x85\xCF\x83\xCE\xB1\xCF\x86\xE1\xBD\xB6 \xCE\xBE\xCE\xAD\xCF\x86\xCF\x89\xCF\x84\xCE\xBF", i.c_str());

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(911, 106);
	EXPECT_UTF8EQ(eu, au);
}

TEST_F(QuickbrownCaseMapping, GreekFirstLowercase)
{
	std::string i = ReadRegular(911, 105);
	EXPECT_STREQ("  \xCE\x93\xCE\xB1\xCE\xB6\xCE\xAD\xCE\xB5\xCF\x82 \xCE\xBA\xCE\xB1\xE1\xBD\xB6 \xCE\xBC\xCF\x85\xCF\x81\xCF\x84\xCE\xB9\xE1\xBD\xB2\xCF\x82 \xCE\xB4\xE1\xBD\xB2\xCE\xBD \xCE\xB8\xE1\xBD\xB0 \xCE\xB2\xCF\x81\xE1\xBF\xB6 \xCF\x80\xCE\xB9\xE1\xBD\xB0 \xCF\x83\xCF\x84\xE1\xBD\xB8 \xCF\x87\xCF\x81\xCF\x85\xCF\x83\xCE\xB1\xCF\x86\xE1\xBD\xB6 \xCE\xBE\xCE\xAD\xCF\x86\xCF\x89\xCF\x84\xCE\xBF", i.c_str());

	std::string al = helpers::lowercase(i);
	ASSERT_EQ(0, errors);

	std::string el = ReadLowercase(911, 105);
	EXPECT_UTF8EQ(el, al);
}

TEST_F(QuickbrownCaseMapping, GreekSecondUppercase)
{
	std::string i = ReadRegular(1086, 66);
	EXPECT_UTF8EQ("  \xCE\x9E\xCE\xB5\xCF\x83\xCE\xBA\xCE\xB5\xCF\x80\xCE\xAC\xCE\xB6\xCF\x89 \xCF\x84\xE1\xBD\xB4\xCE\xBD \xCF\x88\xCF\x85\xCF\x87\xCE\xBF\xCF\x86\xCE\xB8\xCF\x8C\xCF\x81\xCE\xB1 \xCE\xB2\xCE\xB4\xCE\xB5\xCE\xBB\xCF\x85\xCE\xB3\xCE\xBC\xCE\xAF\xCE\xB1", i);

	std::string au = helpers::uppercase(i);
	ASSERT_EQ(0, errors);

	std::string eu = ReadUppercase(1087, 66);
	EXPECT_UTF8EQ(eu, au);
}<|endoftext|>


<commit_before>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.

#include <glog/logging.h>
#include <gflags/gflags.h>

#include <boost/algorithm/string.hpp>

#include "scheduler/simple-scheduler.h"

using namespace std;
using namespace boost;

DEFINE_string(backends, "", "comma-separated list of <host:port> pairs");

namespace impala {

SimpleScheduler::SimpleScheduler() {
  if (FLAGS_backends.empty()) return;
  vector<string> backends;
  split(backends, FLAGS_backends, is_any_of(","));
  for (int i = 0; i < backends.size(); ++i) {
    int pos = backends[i].find(':');
    if (pos == string::npos) {
      LOG(ERROR) << "ignoring backend " << backends[i] << ": missing ':'";
      continue;
    }
    string host = backends[i].substr(0, pos);
    int port = atoi(backends[i].substr(pos + 1).c_str());

    HostMap::iterator i = host_map_.find(host);
    if (i == host_map_.end()) {
      i = host_map_.insert(make_pair(host, list<int>())).first;
    }
    i->second.push_back(port);
  }
}

Status SimpleScheduler::GetHosts(
    const vector<string>& data_locations, vector<pair<string, int> >* hostports) {
  hostports->clear();
  for (int i = 0; i < data_locations.size(); ++i) {
    HostMap::iterator entry = host_map_.find(data_locations[i]);
    if (entry != host_map_.end()) {
      DCHECK(entry->second.begin() != entry->second.end());
      // TODO: return a randomly selected backend for this host?
      // Will we ever have multiple backends on the same host, other
      // than in a test setup?
      hostports->push_back(make_pair(entry->first, entry->second.front()));
    } else {
      // TODO: should we make an effort to pick a random host?
      entry = host_map_.begin();
    }
    hostports->push_back(make_pair(entry->first, entry->second.front()));
    VLOG(1) << "SimpleScheduler: selecting "
            << entry->first << ":" << entry->second.front();
  }
  return Status::OK;
}

}
<commit_msg>Fixes a scheduler bug that adds some hosts to the list of returned hosts twice.<commit_after>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.

#include <glog/logging.h>
#include <gflags/gflags.h>

#include <boost/algorithm/string.hpp>

#include "scheduler/simple-scheduler.h"

using namespace std;
using namespace boost;

DEFINE_string(backends, "", "comma-separated list of <host:port> pairs");

namespace impala {

SimpleScheduler::SimpleScheduler() {
  if (FLAGS_backends.empty()) return;
  vector<string> backends;
  split(backends, FLAGS_backends, is_any_of(","));
  for (int i = 0; i < backends.size(); ++i) {
    int pos = backends[i].find(':');
    if (pos == string::npos) {
      LOG(ERROR) << "ignoring backend " << backends[i] << ": missing ':'";
      continue;
    }
    string host = backends[i].substr(0, pos);
    int port = atoi(backends[i].substr(pos + 1).c_str());

    HostMap::iterator i = host_map_.find(host);
    if (i == host_map_.end()) {
      i = host_map_.insert(make_pair(host, list<int>())).first;
    }
    i->second.push_back(port);
  }
}

Status SimpleScheduler::GetHosts(
    const vector<string>& data_locations, vector<pair<string, int> >* hostports) {
  hostports->clear();
  for (int i = 0; i < data_locations.size(); ++i) {
    HostMap::iterator entry = host_map_.find(data_locations[i]);
    if (entry == host_map_.end()) {
      // TODO: should we make an effort to pick a random host?
      entry = host_map_.begin();
    }
    DCHECK(!entry->second.empty());
    // TODO: return a randomly selected backend for this host?
    // Will we ever have multiple backends on the same host, other
    // than in a test setup?
    hostports->push_back(make_pair(entry->first, entry->second.front()));
    VLOG(1) << "SimpleScheduler: selecting "
            << entry->first << ":" << entry->second.front();
  }
  DCHECK_EQ(data_locations.size(), hostports->size());
  return Status::OK;
}

}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2015, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/gl/ShaderPreprocessor.h"
#include "cinder/gl/gl.h"
#include "cinder/app/Platform.h"
#include "cinder/Utilities.h"
#include "cinder/Log.h"

#include <regex>

using namespace std;

namespace cinder { namespace gl {

	namespace {
		const regex sIncludeRegex = regex( "^[ \t]*#[ ]*include[ ]+[\"<](.*)[\">].*" );
		const regex sVersionRegex = regex( "^[ ]*#[ ]*version[ ]+([123456789][0123456789][0123456789]).*" );
} // anonymous namespace

ShaderPreprocessor::ShaderPreprocessor()
{
	mSearchDirectories.push_back( app::Platform::get()->getAssetPath( "" ) );

	// set the default version
#if defined( CINDER_GL_ES_3 )
	mVersion = 300;
#elif defined( CINDER_GL_ES_2 )
	mVersion = 110;
#else // desktop
	mVersion = 150;
#endif
}

string ShaderPreprocessor::parse( const fs::path &sourcePath )
{
	set<fs::path> includeTree;

	return parseDirectives( parseRecursive( sourcePath, fs::path(), includeTree ) );
}

string ShaderPreprocessor::parse( const std::string &source, const fs::path &sourcePath )
{
	CI_ASSERT( ! fs::is_directory( sourcePath ) );

	return parseDirectives( parseTopLevel( source, sourcePath.parent_path() ) );
}

std::string ShaderPreprocessor::parseDirectives( const std::string &source )
{
	stringstream output;
	istringstream input( source );

	string version;

	// go through each line and find the #version directive
	string line;
	while( getline( input, line ) ) {
		if( regex_search( line, sVersionRegex ) ) {
			version = line;
		}
		else
			output << line;
		output << endl;
	}

	// if we don't have a version yet, add the default one
	if( version.empty() ) {
#if defined( CINDER_GL_ES )
		version = "#version " + to_string( mVersion ) + "es\n";
#else
		version = "#version " + to_string( mVersion ) + "\n";
#endif
	}
	else
		version += "\n";

	// copy the preprocessor directives to a string starting with the version
	std::string directivesString = version;
	for( auto define : mDefineDirectives ) {
		directivesString += "#define " + define + "\n";
	}

	return directivesString + output.str();
}

string ShaderPreprocessor::parseTopLevel( const string &source, const fs::path &currentDirectory )
{
	set<fs::path> includeTree;

	stringstream output;
	istringstream input( source );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), currentDirectory, includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	return output.str();
}

string ShaderPreprocessor::parseRecursive( const fs::path &path, const fs::path &currentDirectory, set<fs::path> &includeTree )
{
	const fs::path fullPath = findFullPath( path, currentDirectory );

	if( includeTree.count( fullPath ) )
		throw ShaderPreprocessorExc( "circular include found, path: " + fullPath.string() );

	includeTree.insert( fullPath );

	stringstream output;
	ifstream input( fullPath.string().c_str() );
	if( ! input.is_open() )
		throw ShaderPreprocessorExc( "Failed to open file at path: " + fullPath.string() );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), fullPath.parent_path(), includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	input.close();
	return output.str();
}

void ShaderPreprocessor::addSearchDirectory( const fs::path &directory )
{
	if( ! fs::is_directory( directory ) ) {
		CI_LOG_E( "Not a directory: " << directory );
		return;
	}

	fs::path dirCanonical = fs::canonical( directory );
	auto it = find( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical );
	if( it == mSearchDirectories.end() )
		mSearchDirectories.push_back( dirCanonical );
}

void ShaderPreprocessor::removeSearchDirectory( const fs::path &directory )
{
	fs::path dirCanonical = fs::canonical( directory );
	mSearchDirectories.erase( remove( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical ), mSearchDirectories.end() );
}

void ShaderPreprocessor::addDefine( const std::string &define )
{
	mDefineDirectives.push_back( define );
}

void ShaderPreprocessor::addDefine( const std::string &define, const std::string &value )
{
	mDefineDirectives.push_back( define + " " + value );
}
void ShaderPreprocessor::setDefineDirectives( const std::vector<std::string> &defines )
{
	mDefineDirectives = defines;
}

fs::path ShaderPreprocessor::findFullPath( const fs::path &includePath, const fs::path &currentDirectory )
{
	auto fullPath = currentDirectory / includePath;
	if( fs::exists( fullPath ) )
		return fs::canonical( fullPath );

	for( auto dirIt = mSearchDirectories.rbegin(); dirIt != mSearchDirectories.rend(); ++dirIt ) {
		fullPath = *dirIt / includePath;
		if( fs::exists( fullPath ) )
			return fs::canonical( fullPath );
	}

	throw ShaderPreprocessorExc( "could not find shader with include path: " + includePath.string() );
}

} } // namespace cinder::gl
<commit_msg>Indenting<commit_after>/*
 Copyright (c) 2015, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/gl/ShaderPreprocessor.h"
#include "cinder/gl/gl.h"
#include "cinder/app/Platform.h"
#include "cinder/Utilities.h"
#include "cinder/Log.h"

#include <regex>

using namespace std;

namespace cinder { namespace gl {

namespace {
	const regex sIncludeRegex = regex( "^[ \t]*#[ ]*include[ ]+[\"<](.*)[\">].*" );
	const regex sVersionRegex = regex( "^[ ]*#[ ]*version[ ]+([123456789][0123456789][0123456789]).*" );
} // anonymous namespace

ShaderPreprocessor::ShaderPreprocessor()
{
	mSearchDirectories.push_back( app::Platform::get()->getAssetPath( "" ) );

	// set the default version
#if defined( CINDER_GL_ES_3 )
	mVersion = 300;
#elif defined( CINDER_GL_ES_2 )
	mVersion = 110;
#else // desktop
	mVersion = 150;
#endif
}

string ShaderPreprocessor::parse( const fs::path &sourcePath )
{
	set<fs::path> includeTree;

	return parseDirectives( parseRecursive( sourcePath, fs::path(), includeTree ) );
}

string ShaderPreprocessor::parse( const std::string &source, const fs::path &sourcePath )
{
	CI_ASSERT( ! fs::is_directory( sourcePath ) );

	return parseDirectives( parseTopLevel( source, sourcePath.parent_path() ) );
}

std::string ShaderPreprocessor::parseDirectives( const std::string &source )
{
	stringstream output;
	istringstream input( source );

	string version;

	// go through each line and find the #version directive
	string line;
	while( getline( input, line ) ) {
		if( regex_search( line, sVersionRegex ) ) {
			version = line;
		}
		else
			output << line;
		output << endl;
	}

	// if we don't have a version yet, add the default one
	if( version.empty() ) {
#if defined( CINDER_GL_ES )
		version = "#version " + to_string( mVersion ) + "es\n";
#else
		version = "#version " + to_string( mVersion ) + "\n";
#endif
	}
	else
		version += "\n";

	// copy the preprocessor directives to a string starting with the version
	std::string directivesString = version;
	for( auto define : mDefineDirectives ) {
		directivesString += "#define " + define + "\n";
	}

	return directivesString + output.str();
}

string ShaderPreprocessor::parseTopLevel( const string &source, const fs::path &currentDirectory )
{
	set<fs::path> includeTree;

	stringstream output;
	istringstream input( source );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), currentDirectory, includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	return output.str();
}

string ShaderPreprocessor::parseRecursive( const fs::path &path, const fs::path &currentDirectory, set<fs::path> &includeTree )
{
	const fs::path fullPath = findFullPath( path, currentDirectory );

	if( includeTree.count( fullPath ) )
		throw ShaderPreprocessorExc( "circular include found, path: " + fullPath.string() );

	includeTree.insert( fullPath );

	stringstream output;
	ifstream input( fullPath.string().c_str() );
	if( ! input.is_open() )
		throw ShaderPreprocessorExc( "Failed to open file at path: " + fullPath.string() );

	// go through each line and process includes
	string line;
	smatch matches;

	size_t lineNumber = 1;

	while( getline( input, line ) ) {
		if( regex_search( line, matches, sIncludeRegex ) ) {
			output << parseRecursive( matches[1].str(), fullPath.parent_path(), includeTree );
			output << "#line " << lineNumber << endl;
		}
		else
			output << line;

		output << endl;
		lineNumber++;
	}

	input.close();
	return output.str();
}

void ShaderPreprocessor::addSearchDirectory( const fs::path &directory )
{
	if( ! fs::is_directory( directory ) ) {
		CI_LOG_E( "Not a directory: " << directory );
		return;
	}

	fs::path dirCanonical = fs::canonical( directory );
	auto it = find( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical );
	if( it == mSearchDirectories.end() )
		mSearchDirectories.push_back( dirCanonical );
}

void ShaderPreprocessor::removeSearchDirectory( const fs::path &directory )
{
	fs::path dirCanonical = fs::canonical( directory );
	mSearchDirectories.erase( remove( mSearchDirectories.begin(), mSearchDirectories.end(), dirCanonical ), mSearchDirectories.end() );
}

void ShaderPreprocessor::addDefine( const std::string &define )
{
	mDefineDirectives.push_back( define );
}

void ShaderPreprocessor::addDefine( const std::string &define, const std::string &value )
{
	mDefineDirectives.push_back( define + " " + value );
}
void ShaderPreprocessor::setDefineDirectives( const std::vector<std::string> &defines )
{
	mDefineDirectives = defines;
}

fs::path ShaderPreprocessor::findFullPath( const fs::path &includePath, const fs::path &currentDirectory )
{
	auto fullPath = currentDirectory / includePath;
	if( fs::exists( fullPath ) )
		return fs::canonical( fullPath );

	for( auto dirIt = mSearchDirectories.rbegin(); dirIt != mSearchDirectories.rend(); ++dirIt ) {
		fullPath = *dirIt / includePath;
		if( fs::exists( fullPath ) )
			return fs::canonical( fullPath );
	}

	throw ShaderPreprocessorExc( "could not find shader with include path: " + includePath.string() );
}

} } // namespace cinder::gl
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2004 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cassert>
#include <ctime>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#include <iostream.h>
#include <strstream.h>
#else
#include <fstream>
#include <iostream>
#include <strstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <xalanc/XalanTransformer/XalanTransformer.hpp>

//This is here for the Windows threads.
#if defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI
    typedef   DWORD      theThreadIDType;
    typedef   HANDLE     theThreadType;

//This is here for Unix threads
#elif defined(XALAN_POSIX2_AVAILABLE)
#include <pthread.h>
#include <unistd.h>
    typedef   unsigned long     theThreadIDType;
    typedef   pthread_t         theThreadType;

#else
//error Unsupported Platform!
#endif

#define NUM_THREADS 10

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
XALAN_USING_STD(ostrstream)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)
XALAN_USING_XALAN(XSLTInputSource)
XALAN_USING_XALAN(XSLTResultTarget)

// Used to hold compiled stylesheet and XML source document.
const XalanCompiledStylesheet*	glbCompiledStylesheet = 0;
const XalanParsedSource*		glbParsedSource = 0;
int								glbError = 0;

// Print messages tracking the progress of each thread, and the
// beginning and end of the entire operation.
void
outputMessage(
              theThreadIDType  id,
			const char	msg[])
{
	ostrstream threadMsg;

	threadMsg << "\n" << msg << " Thread: " << id << '\0';

	cout << threadMsg.str();

    #if defined(HPUX)
	threadMsg.rdbuf() -> freeze(false);
    #else
	threadMsg.freeze(false);
    #endif
}

#if defined(_MSC_VER)
THREADFUNCTIONRETURN
theThread(LPVOID	param)
#elif defined(XALAN_POSIX2_AVAILABLE)
  void  *theThread(void   *param)
#endif
{
// This routine uses a compiled stylesheet (glbCompiledStylesheet),
// and a binary source tree (glbParsedSource) to perform the
// transformation.

	int	theResult = 0;

   #if defined(_MSC_VER)
	const int	number = reinterpret_cast<int>(param);
        const theThreadIDType         theThreadID = GetCurrentThreadId();

   #elif defined(XALAN_POSIX2_AVAILABLE)
        const int       number = *(int *)(param);
        const theThreadIDType         theThreadID = pthread_self();

   #endif

	outputMessage(theThreadID, "Starting ");

	// Create a XalanTransformer.
	XalanTransformer	theXalanTransformer;

	// Generate the output file name for this thread.
    ostrstream	theFormatterOut;
    theFormatterOut << "birds" << number << ".out" << '\0';

	// Generate the XML output object.
	const XSLTResultTarget	theResultTarget(XalanDOMString(theFormatterOut.str()));

	// Unfreeze the ostrstream, so memory is returned...
     #if defined(HPUX)
        theFormatterOut.rdbuf() -> freeze(false);
     #else
	theFormatterOut.freeze(false);
     #endif

	outputMessage(theThreadID, "Transforming");

 	// Do the transform.
	theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget);

	if(theResult != 0)
	{
		cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
			 << endl
			 << endl;

		glbError = theResult;
	}

	outputMessage(theThreadID, "Finishing");

  #if defined(_MSC_VER)
	return (theResult);
  #elif defined(XALAN_POSIX2_AVAILABLE)
        return 0;
  #endif
}

// Create and run the threads...
// Print messages tracking the progress of each thread and of the
// overall operation...
void
doThreads(int	nThreads)
{
      int   i=0;
      cout << endl << "Clock before starting threads: " << clock() << endl;

	XALAN_USING_STD(vector)

        vector<theThreadType>   hThreads;

	hThreads.reserve(nThreads);

#if defined(_MSC_VER)

	for (; i < nThreads; ++i)
	{
                theThreadIDType  threadID;

                const theThreadType  hThread = CreateThread(
				0,
				4096,							// Stack size for thread.
				theThread,						// pointer to thread function
				reinterpret_cast<LPVOID>(i),	// argument for new thread
				0,								// creation flags
				&threadID);

		assert(hThread != 0);

		hThreads.push_back(hThread);
	}

	WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE);

	for (i = 0; i < nThreads; ++i)
	{
		CloseHandle(hThreads[i]);
	}

#elif defined(XALAN_POSIX2_AVAILABLE)

  int result;
  void *thread_result;

  for(; i < nThreads; ++i)
  {
   result = pthread_create(
                          &hThreads[i],    //thread pointer
                          NULL,            //thread's attribute default
                          theThread,       //thread function
                          (void *) &i      //thread function argument
                         );
  if (result != 0)
    {
      perror ("Thread creation failed");
      exit(EXIT_FAILURE);
    }
  }

  cout << endl << "Waiting for threads to finish..." << endl << endl;
  for( i = nThreads - 1; i>=0; i-- )
  {
    result = pthread_join(
                           hThreads[i],
                           &thread_result
                         );
    if (result != 0)
     {
       perror ("Thread join failed");
       exit (EXIT_FAILURE);
     }
   //for UNIX debugging
   // cout << "Thread joined, return value: " << (char *)thread_result << endl;
  }

#endif

cout << endl << endl << "Clock after threads: " << clock() << endl;

}

int
main(
			int		argc,
			char*	/* argv */[])
{
	if (argc != 1)
	{
		cerr << "Usage: ThreadTest"
			 << endl
			 << endl;
	}
	else
	{
		try
		{
			XALAN_USING_XERCES(XMLPlatformUtils)

			// Call the static initializer for Xerces.
			XMLPlatformUtils::Initialize();

			// Initialize Xalan.
			XalanTransformer::initialize();

			{
				// Create a XalanTransformer.  We won't actually use this to transform --
				// it's just acting likely a factory for the compiled stylesheet and
				// pre-parsed source.
				XalanTransformer	theXalanTransformer;

				glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet);

				if (glbError != 0)
				{
					cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
						 << endl
						 << endl;
				}
				else
				{
					assert(glbCompiledStylesheet != 0);

					// Compile the XML source document as well. All threads will use
					// this binary representation of the source tree.
					glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource);

					if (glbError != 0)
					{
						cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
							 << endl
							 << endl;
					}
					else
					{
						assert(glbParsedSource != 0);

						// Create and run the threads...
						// Each thread uses the same document and
						// stylesheet to perform a transformation.
                                    doThreads(NUM_THREADS);

					}
				}
			}

			// Terminate Xalan...
			XalanTransformer::terminate();

			// Terminate Xerces...
			XMLPlatformUtils::Terminate();

			// Clean up the ICU, if it's integrated...
			XalanTransformer::ICUCleanUp();
		}
		catch(...)
		{
			cerr << "Initialization failed!" << endl;

			glbError = -1;
		}
	}

	return glbError;
}
<commit_msg>Modified sample so it builds on Tru64.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2004 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cassert>
#include <ctime>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#include <iostream.h>
#include <strstream.h>
#else
#include <fstream>
#include <iostream>
#include <strstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <xalanc/XalanTransformer/XalanTransformer.hpp>

//This is here for the Windows threads.
#if defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI
    typedef   DWORD      theThreadIDType;
    typedef   HANDLE     theThreadType;

//This is here for Unix threads
#elif defined(XALAN_POSIX2_AVAILABLE)

    // This is a workaround for a Tru64 compiler bug...
#if defined(TRU64)
#if  defined(XALAN_STRICT_ANSI_HEADERS)
#include <csetjmp>
typedef long sigjmp_buf[_JBLEN];
#endif
extern "C" void  *theThread(void   *param);
#endif

#include <pthread.h>
#include <unistd.h>
    typedef   pthread_t     theThreadIDType;
    typedef   pthread_t     theThreadType;

#else
//error Unsupported Platform!
#endif

#if  defined(XALAN_STRICT_ANSI_HEADERS)
    using std::perror;
#endif

#define NUM_THREADS 10

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
XALAN_USING_STD(ostrstream)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)
XALAN_USING_XALAN(XSLTInputSource)
XALAN_USING_XALAN(XSLTResultTarget)

// Used to hold compiled stylesheet and XML source document.
const XalanCompiledStylesheet*	glbCompiledStylesheet = 0;
const XalanParsedSource*		glbParsedSource = 0;
int								glbError = 0;

// Print messages tracking the progress of each thread, and the
// beginning and end of the entire operation.
void
outputMessage(
              theThreadIDType  id,
			const char	msg[])
{
	ostrstream threadMsg;

	threadMsg << "\n" << msg << " Thread: " << id << '\0';

	cout << threadMsg.str();

    #if defined(HPUX)
	threadMsg.rdbuf() -> freeze(false);
    #else
	threadMsg.freeze(false);
    #endif
}

#if defined(_MSC_VER)
THREADFUNCTIONRETURN
theThread(LPVOID	param)
#elif defined(XALAN_POSIX2_AVAILABLE)
  void  *theThread(void   *param)
#endif
{
// This routine uses a compiled stylesheet (glbCompiledStylesheet),
// and a binary source tree (glbParsedSource) to perform the
// transformation.

	int	theResult = 0;

   #if defined(_MSC_VER)
	const int	number = reinterpret_cast<int>(param);
        const theThreadIDType         theThreadID = GetCurrentThreadId();

   #elif defined(XALAN_POSIX2_AVAILABLE)
        const int       number = *(int *)(param);
        const theThreadIDType         theThreadID = pthread_self();

   #endif

	outputMessage(theThreadID, "Starting ");

	// Create a XalanTransformer.
	XalanTransformer	theXalanTransformer;

	// Generate the output file name for this thread.
    ostrstream	theFormatterOut;
    theFormatterOut << "birds" << number << ".out" << '\0';

	// Generate the XML output object.
	const XSLTResultTarget	theResultTarget(XalanDOMString(theFormatterOut.str()));

	// Unfreeze the ostrstream, so memory is returned...
     #if defined(HPUX)
        theFormatterOut.rdbuf() -> freeze(false);
     #else
	theFormatterOut.freeze(false);
     #endif

	outputMessage(theThreadID, "Transforming");

 	// Do the transform.
	theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget);

	if(theResult != 0)
	{
		cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
			 << endl
			 << endl;

		glbError = theResult;
	}

	outputMessage(theThreadID, "Finishing");

  #if defined(_MSC_VER)
	return (theResult);
  #elif defined(XALAN_POSIX2_AVAILABLE)
        return 0;
  #endif
}

// Create and run the threads...
// Print messages tracking the progress of each thread and of the
// overall operation...
void
doThreads(int	nThreads)
{
      int   i=0;
      cout << endl << "Clock before starting threads: " << clock() << endl;

	XALAN_USING_STD(vector)

        vector<theThreadType>   hThreads;

	hThreads.reserve(nThreads);

#if defined(_MSC_VER)

	for (; i < nThreads; ++i)
	{
                theThreadIDType  threadID;

                const theThreadType  hThread = CreateThread(
				0,
				4096,							// Stack size for thread.
				theThread,						// pointer to thread function
				reinterpret_cast<LPVOID>(i),	// argument for new thread
				0,								// creation flags
				&threadID);

		assert(hThread != 0);

		hThreads.push_back(hThread);
	}

	WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE);

	for (i = 0; i < nThreads; ++i)
	{
		CloseHandle(hThreads[i]);
	}

#elif defined(XALAN_POSIX2_AVAILABLE)

  int result;
  void *thread_result;

  for(; i < nThreads; ++i)
  {
   result = pthread_create(
                          &hThreads[i],    //thread pointer
                          NULL,            //thread's attribute default
                          theThread,       //thread function
                          (void *) &i      //thread function argument
                         );
  if (result != 0)
    {
      perror ("Thread creation failed");
      exit(EXIT_FAILURE);
    }
  }

  cout << endl << "Waiting for threads to finish..." << endl << endl;
  for( i = nThreads - 1; i>=0; i-- )
  {
    result = pthread_join(
                           hThreads[i],
                           &thread_result
                         );
    if (result != 0)
     {
       perror ("Thread join failed");
       exit (EXIT_FAILURE);
     }
   //for UNIX debugging
   // cout << "Thread joined, return value: " << (char *)thread_result << endl;
  }

#endif

cout << endl << endl << "Clock after threads: " << clock() << endl;

}

int
main(
			int		argc,
			char*	/* argv */[])
{
	if (argc != 1)
	{
		cerr << "Usage: ThreadTest"
			 << endl
			 << endl;
	}
	else
	{
		try
		{
			XALAN_USING_XERCES(XMLPlatformUtils)

			// Call the static initializer for Xerces.
			XMLPlatformUtils::Initialize();

			// Initialize Xalan.
			XalanTransformer::initialize();

			{
				// Create a XalanTransformer.  We won't actually use this to transform --
				// it's just acting likely a factory for the compiled stylesheet and
				// pre-parsed source.
				XalanTransformer	theXalanTransformer;

				glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet);

				if (glbError != 0)
				{
					cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
						 << endl
						 << endl;
				}
				else
				{
					assert(glbCompiledStylesheet != 0);

					// Compile the XML source document as well. All threads will use
					// this binary representation of the source tree.
					glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource);

					if (glbError != 0)
					{
						cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
							 << endl
							 << endl;
					}
					else
					{
						assert(glbParsedSource != 0);

						// Create and run the threads...
						// Each thread uses the same document and
						// stylesheet to perform a transformation.
                                    doThreads(NUM_THREADS);

					}
				}
			}

			// Terminate Xalan...
			XalanTransformer::terminate();

			// Terminate Xerces...
			XMLPlatformUtils::Terminate();

			// Clean up the ICU, if it's integrated...
			XalanTransformer::ICUCleanUp();
		}
		catch(...)
		{
			cerr << "Initialization failed!" << endl;

			glbError = -1;
		}
	}

	return glbError;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implspritecanvas.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 15:01:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif

#ifndef _COM_SUN_STAR_RENDERING_INTERPOLATIONMODE_HPP_
#include <com/sun/star/rendering/InterpolationMode.hpp>
#endif

#include <implspritecanvas.hxx>
#include <implcustomsprite.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        ImplSpriteCanvas::TransformationArbiter::TransformationArbiter() :
            maTransformation()
        {
        }

        void ImplSpriteCanvas::TransformationArbiter::setTransformation( const ::basegfx::B2DHomMatrix& rViewTransform )
        {
            maTransformation = rViewTransform;
        }

        ::basegfx::B2DHomMatrix ImplSpriteCanvas::TransformationArbiter::getTransformation() const
        {
            return maTransformation;
        }

        ImplSpriteCanvas::ImplSpriteCanvas( const uno::Reference< rendering::XSpriteCanvas >& rCanvas ) :
            ImplCanvas( uno::Reference< rendering::XCanvas >(rCanvas,
                                                             uno::UNO_QUERY) ),
            ImplBitmapCanvas( uno::Reference< rendering::XBitmapCanvas >(rCanvas,
                                                                         uno::UNO_QUERY) ),
            mxSpriteCanvas( rCanvas ),
            mpTransformArbiter( new TransformationArbiter() )
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::ImplSpriteCanvas(): Invalid canvas" );
        }

        ImplSpriteCanvas::ImplSpriteCanvas(const ImplSpriteCanvas& rOrig) :
            Canvas(),
            BitmapCanvas(),
            SpriteCanvas(),
            ImplCanvas( rOrig ),
            ImplBitmapCanvas( rOrig ),
            mxSpriteCanvas( rOrig.getUNOSpriteCanvas() ),
            mpTransformArbiter( new TransformationArbiter() )
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::ImplSpriteCanvas( const ImplSpriteCanvas& ): Invalid canvas" );

            mpTransformArbiter->setTransformation( getTransformation() );
        }

        ImplSpriteCanvas::~ImplSpriteCanvas()
        {
        }

        void ImplSpriteCanvas::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix )
        {
            mpTransformArbiter->setTransformation( rMatrix );

            ImplCanvas::setTransformation( rMatrix );
        }

        bool ImplSpriteCanvas::updateScreen( bool bUpdateAll ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::updateScreen(): Invalid canvas" );

            if( !mxSpriteCanvas.is() )
                return false;

            return mxSpriteCanvas->updateScreen( bUpdateAll );
        }

        CustomSpriteSharedPtr ImplSpriteCanvas::createCustomSprite( const ::basegfx::B2DSize& rSize ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::createCustomSprite(): Invalid canvas" );

            if( !mxSpriteCanvas.is() )
                return CustomSpriteSharedPtr();

            return CustomSpriteSharedPtr(
                new ImplCustomSprite( mxSpriteCanvas,
                                      mxSpriteCanvas->createCustomSprite( ::basegfx::unotools::size2DFromB2DSize(rSize) ),
                                      mpTransformArbiter ) );
        }

        SpriteSharedPtr ImplSpriteCanvas::createClonedSprite( const SpriteSharedPtr& rSprite ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::createCustomSprite(): Invalid canvas" );
            OSL_ENSURE( rSprite.get() != NULL && rSprite->getUNOSprite().is(),
                        "ImplSpriteCanvas::createCustomSprite(): Invalid sprite" );

            if( !mxSpriteCanvas.is() ||
                rSprite.get() == NULL ||
                !rSprite->getUNOSprite().is() )
            {
                return SpriteSharedPtr();
            }

            return SpriteSharedPtr(
                new ImplSprite( mxSpriteCanvas,
                                mxSpriteCanvas->createClonedSprite( rSprite->getUNOSprite() ),
                                mpTransformArbiter ) );
        }

        SpriteSharedPtr ImplSpriteCanvas::createSpriteFromBitmaps( const uno::Sequence< uno::Reference< rendering::XBitmap > >& rAnimationBitmaps,
                                                                   sal_Int8                                                     nInterpolationMode )
        {
            return SpriteSharedPtr( new internal::ImplSprite( mxSpriteCanvas,
                                                              mxSpriteCanvas->createSpriteFromBitmaps( rAnimationBitmaps,
                                                                                nInterpolationMode ),
                                                              mpTransformArbiter ) );
        }

        CanvasSharedPtr ImplSpriteCanvas::clone() const
        {
            return SpriteCanvasSharedPtr( new ImplSpriteCanvas( *this ) );
        }

        uno::Reference< rendering::XSpriteCanvas > ImplSpriteCanvas::getUNOSpriteCanvas() const
        {
            return mxSpriteCanvas;
        }

    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.46); FILE MERGED 2008/04/01 15:10:07 thb 1.9.46.3: #i85898# Stripping all external header guards 2008/04/01 12:27:52 thb 1.9.46.2: #i85898# Stripping all external header guards 2008/03/31 13:07:09 rt 1.9.46.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: implspritecanvas.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <com/sun/star/rendering/InterpolationMode.hpp>

#include <implspritecanvas.hxx>
#include <implcustomsprite.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        ImplSpriteCanvas::TransformationArbiter::TransformationArbiter() :
            maTransformation()
        {
        }

        void ImplSpriteCanvas::TransformationArbiter::setTransformation( const ::basegfx::B2DHomMatrix& rViewTransform )
        {
            maTransformation = rViewTransform;
        }

        ::basegfx::B2DHomMatrix ImplSpriteCanvas::TransformationArbiter::getTransformation() const
        {
            return maTransformation;
        }

        ImplSpriteCanvas::ImplSpriteCanvas( const uno::Reference< rendering::XSpriteCanvas >& rCanvas ) :
            ImplCanvas( uno::Reference< rendering::XCanvas >(rCanvas,
                                                             uno::UNO_QUERY) ),
            ImplBitmapCanvas( uno::Reference< rendering::XBitmapCanvas >(rCanvas,
                                                                         uno::UNO_QUERY) ),
            mxSpriteCanvas( rCanvas ),
            mpTransformArbiter( new TransformationArbiter() )
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::ImplSpriteCanvas(): Invalid canvas" );
        }

        ImplSpriteCanvas::ImplSpriteCanvas(const ImplSpriteCanvas& rOrig) :
            Canvas(),
            BitmapCanvas(),
            SpriteCanvas(),
            ImplCanvas( rOrig ),
            ImplBitmapCanvas( rOrig ),
            mxSpriteCanvas( rOrig.getUNOSpriteCanvas() ),
            mpTransformArbiter( new TransformationArbiter() )
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::ImplSpriteCanvas( const ImplSpriteCanvas& ): Invalid canvas" );

            mpTransformArbiter->setTransformation( getTransformation() );
        }

        ImplSpriteCanvas::~ImplSpriteCanvas()
        {
        }

        void ImplSpriteCanvas::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix )
        {
            mpTransformArbiter->setTransformation( rMatrix );

            ImplCanvas::setTransformation( rMatrix );
        }

        bool ImplSpriteCanvas::updateScreen( bool bUpdateAll ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::updateScreen(): Invalid canvas" );

            if( !mxSpriteCanvas.is() )
                return false;

            return mxSpriteCanvas->updateScreen( bUpdateAll );
        }

        CustomSpriteSharedPtr ImplSpriteCanvas::createCustomSprite( const ::basegfx::B2DSize& rSize ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::createCustomSprite(): Invalid canvas" );

            if( !mxSpriteCanvas.is() )
                return CustomSpriteSharedPtr();

            return CustomSpriteSharedPtr(
                new ImplCustomSprite( mxSpriteCanvas,
                                      mxSpriteCanvas->createCustomSprite( ::basegfx::unotools::size2DFromB2DSize(rSize) ),
                                      mpTransformArbiter ) );
        }

        SpriteSharedPtr ImplSpriteCanvas::createClonedSprite( const SpriteSharedPtr& rSprite ) const
        {
            OSL_ENSURE( mxSpriteCanvas.is(), "ImplSpriteCanvas::createCustomSprite(): Invalid canvas" );
            OSL_ENSURE( rSprite.get() != NULL && rSprite->getUNOSprite().is(),
                        "ImplSpriteCanvas::createCustomSprite(): Invalid sprite" );

            if( !mxSpriteCanvas.is() ||
                rSprite.get() == NULL ||
                !rSprite->getUNOSprite().is() )
            {
                return SpriteSharedPtr();
            }

            return SpriteSharedPtr(
                new ImplSprite( mxSpriteCanvas,
                                mxSpriteCanvas->createClonedSprite( rSprite->getUNOSprite() ),
                                mpTransformArbiter ) );
        }

        SpriteSharedPtr ImplSpriteCanvas::createSpriteFromBitmaps( const uno::Sequence< uno::Reference< rendering::XBitmap > >& rAnimationBitmaps,
                                                                   sal_Int8                                                     nInterpolationMode )
        {
            return SpriteSharedPtr( new internal::ImplSprite( mxSpriteCanvas,
                                                              mxSpriteCanvas->createSpriteFromBitmaps( rAnimationBitmaps,
                                                                                nInterpolationMode ),
                                                              mpTransformArbiter ) );
        }

        CanvasSharedPtr ImplSpriteCanvas::clone() const
        {
            return SpriteCanvasSharedPtr( new ImplSpriteCanvas( *this ) );
        }

        uno::Reference< rendering::XSpriteCanvas > ImplSpriteCanvas::getUNOSpriteCanvas() const
        {
            return mxSpriteCanvas;
        }

    }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageAdaptor.h"
#include "itkAffineRegistrationTransform.h"
#include "itkAffineTransform.h"
#include "itkArray.h"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkBloxBoundaryPointImage.h"
#include "itkBloxBoundaryPointItem.h"
#include "itkBloxCoreAtomAnalyzer.h"
#include "itkBloxCoreAtomImage.h"
#include "itkBloxCoreAtomItem.h"
#include "itkBloxImage.h"
#include "itkBloxItem.h"
#include "itkBloxPixel.h"
#include "itkBluePixelAccessor.h"
#include "itkBoundingBox.h"
#include "itkByteSwapper.h"
#include "itkCellBoundary.h"
#include "itkCellInterface.h"
#include "itkCellInterfaceVisitor.h"
#include "itkCentralDifferenceImageFunction.h"
#include "itkColorTable.h"
#include "itkCommand.h"
#include "itkConditionalIterator.h"
#include "itkConeSpatialFunction.h"
#include "itkConicShellInteriorExteriorSpatialFunction.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkConstRandomAccessNeighborhoodIterator.h"
#include "itkConstSliceIterator.h"
#include "itkConstSmartNeighborhoodIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousImageFunction.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.h"
#include "itkCreateObjectFunction.h"
#include "itkDataObject.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultPixelAccessor.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDenseFiniteDifferenceImageFilter.h"
#include "itkDerivativeOperator.h"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodySplineKernelTransform.h"
#include "itkEntropyPreservingGradientMagnitudeImageFunction.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkFiniteDifferenceEquation.h"
#include "itkFiniteDifferenceImageFilter.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianOperator.h"
#include "itkGreenPixelAccessor.h"
#include "itkHexahedronCell.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageBase.h"
#include "itkImageBoundaryCondition.h"
#include "itkImageConstIterator.h"
#include "itkImageConstIteratorWithIndex.h"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.h"
#include "itkImageIO.h"
#include "itkImageIOBase.h"
#include "itkImageIOCommon.h"
#include "itkImageIterator.h"
#include "itkImageIteratorWithIndex.h"
#include "itkImageLinearConstIteratorWithIndex.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageRegion.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionReverseIterator.h"
#include "itkImageReverseIterator.h"
#include "itkImageSliceConstIteratorWithIndex.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "itkImageSource.h"
#include "itkImageToImageFilter.h"
#include "itkImportImageContainer.h"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkInteriorExteriorSpatialFunction.h"
#include "itkKernelTransform.h"
#include "itkLevelSetCurvatureFunction.h"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.h"
#include "itkMatrix.h"
#include "itkMesh.h"
#include "itkMeshRegion.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkNeighborhood.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodInnerProduct.h"
#include "itkNeighborhoodIterator.h"
#include "itkNeighborhoodOperator.h"
#include "itkNthElementImageAdaptor.h"
#include "itkNthElementPixelAccessor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkOffset.h"
#include "itkOutputWindow.h"
#include "itkPhysicalImage.h"
#include "itkPhysicalImageAdaptor.h"
#include "itkPixelAccessor.h"
#include "itkPoint.h"
#include "itkPointLocator.h"
#include "itkPointSet.h"
#include "itkPolygonCell.h"
#include "itkProcessObject.h"
#include "itkQuadrilateralCell.h"
#include "itkQuaternionRigidRegistrationTransform.h"
#include "itkRGBPixel.h"
#include "itkRandomAccessNeighborhoodIterator.h"
#include "itkRedPixelAccessor.h"
#include "itkRegion.h"
#include "itkRigid3DPerspectiveRegistrationTransform.h"
#include "itkRigid3DPerspectiveTransform.h"
#include "itkRigid3DRegistrationTransform.h"
#include "itkRigid3DTransform.h"
#include "itkScalarImageRegionIterator.h"
#include "itkScalarVector.h"
#include "itkSimpleImageRegionConstIterator.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartNeighborhoodIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.h"
#include "itkSpatialFunction.h"
#include "itkSphereSpatialFunction.h"
#include "itkSqrtImageAdaptor.h"
#include "itkStatDenseHistogram.h"
#include "itkStatHistogram.h"
#include "itkStatSparseHistogram.h"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.h"
#include "itkThinPlateSplineKernelTransform.h"
#include "itkTimeStamp.h"
#include "itkTransform.h"
#include "itkTranslationRegistrationTransform.h"
#include "itkTranslationTransform.h"
#include "itkTriangleCell.h"
#include "itkUpwindDerivativeImageFunction.h"
#include "itkValarrayImageContainer.h"
#include "itkVector.h"
#include "itkVectorContainer.h"
#include "itkVectorNeighborhoodInnerProduct.h"
#include "itkVersion.h"
#include "itkVertexCell.h"
#include "itkWeakPointer.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>FIX: remove ScalarImageRegionIterator<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageAdaptor.h"
#include "itkAffineRegistrationTransform.h"
#include "itkAffineTransform.h"
#include "itkArray.h"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkBloxBoundaryPointImage.h"
#include "itkBloxBoundaryPointItem.h"
#include "itkBloxCoreAtomAnalyzer.h"
#include "itkBloxCoreAtomImage.h"
#include "itkBloxCoreAtomItem.h"
#include "itkBloxImage.h"
#include "itkBloxItem.h"
#include "itkBloxPixel.h"
#include "itkBluePixelAccessor.h"
#include "itkBoundingBox.h"
#include "itkByteSwapper.h"
#include "itkCellBoundary.h"
#include "itkCellInterface.h"
#include "itkCellInterfaceVisitor.h"
#include "itkCentralDifferenceImageFunction.h"
#include "itkColorTable.h"
#include "itkCommand.h"
#include "itkConditionalIterator.h"
#include "itkConeSpatialFunction.h"
#include "itkConicShellInteriorExteriorSpatialFunction.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkConstRandomAccessNeighborhoodIterator.h"
#include "itkConstSliceIterator.h"
#include "itkConstSmartNeighborhoodIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousImageFunction.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.h"
#include "itkCreateObjectFunction.h"
#include "itkDataObject.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultPixelAccessor.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDenseFiniteDifferenceImageFilter.h"
#include "itkDerivativeOperator.h"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodySplineKernelTransform.h"
#include "itkEntropyPreservingGradientMagnitudeImageFunction.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkFiniteDifferenceEquation.h"
#include "itkFiniteDifferenceImageFilter.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianOperator.h"
#include "itkGreenPixelAccessor.h"
#include "itkHexahedronCell.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageBase.h"
#include "itkImageBoundaryCondition.h"
#include "itkImageConstIterator.h"
#include "itkImageConstIteratorWithIndex.h"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.h"
#include "itkImageIO.h"
#include "itkImageIOBase.h"
#include "itkImageIOCommon.h"
#include "itkImageIterator.h"
#include "itkImageIteratorWithIndex.h"
#include "itkImageLinearConstIteratorWithIndex.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageRegion.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionReverseIterator.h"
#include "itkImageReverseIterator.h"
#include "itkImageSliceConstIteratorWithIndex.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "itkImageSource.h"
#include "itkImageToImageFilter.h"
#include "itkImportImageContainer.h"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkInteriorExteriorSpatialFunction.h"
#include "itkKernelTransform.h"
#include "itkLevelSetCurvatureFunction.h"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.h"
#include "itkMatrix.h"
#include "itkMesh.h"
#include "itkMeshRegion.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkNeighborhood.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodInnerProduct.h"
#include "itkNeighborhoodIterator.h"
#include "itkNeighborhoodOperator.h"
#include "itkNthElementImageAdaptor.h"
#include "itkNthElementPixelAccessor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkOffset.h"
#include "itkOutputWindow.h"
#include "itkPhysicalImage.h"
#include "itkPhysicalImageAdaptor.h"
#include "itkPixelAccessor.h"
#include "itkPoint.h"
#include "itkPointLocator.h"
#include "itkPointSet.h"
#include "itkPolygonCell.h"
#include "itkProcessObject.h"
#include "itkQuadrilateralCell.h"
#include "itkQuaternionRigidRegistrationTransform.h"
#include "itkRGBPixel.h"
#include "itkRandomAccessNeighborhoodIterator.h"
#include "itkRedPixelAccessor.h"
#include "itkRegion.h"
#include "itkRigid3DPerspectiveRegistrationTransform.h"
#include "itkRigid3DPerspectiveTransform.h"
#include "itkRigid3DRegistrationTransform.h"
#include "itkRigid3DTransform.h"
#include "itkScalarVector.h"
#include "itkSimpleImageRegionConstIterator.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartNeighborhoodIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.h"
#include "itkSpatialFunction.h"
#include "itkSphereSpatialFunction.h"
#include "itkSqrtImageAdaptor.h"
#include "itkStatDenseHistogram.h"
#include "itkStatHistogram.h"
#include "itkStatSparseHistogram.h"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.h"
#include "itkThinPlateSplineKernelTransform.h"
#include "itkTimeStamp.h"
#include "itkTransform.h"
#include "itkTranslationRegistrationTransform.h"
#include "itkTranslationTransform.h"
#include "itkTriangleCell.h"
#include "itkUpwindDerivativeImageFunction.h"
#include "itkValarrayImageContainer.h"
#include "itkVector.h"
#include "itkVectorContainer.h"
#include "itkVectorNeighborhoodInnerProduct.h"
#include "itkVersion.h"
#include "itkVertexCell.h"
#include "itkWeakPointer.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2016 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SysMembarrier.h"

#include <mutex>

#include <folly/Portability.h>
#include <folly/portability/Unistd.h>

#if !defined(__NR_membarrier) && defined(FOLLY_X64)
#define __NR_membarrier 324
#define MEMBARRIER_CMD_QUERY 0
#define MEMBARRIER_CMD_SHARED 1
#endif

namespace folly {
namespace detail {

bool sysMembarrierAvailable() {
  if (!kIsLinux) {
    return false;
  }

#ifdef __NR_membarrier
  auto r = syscall(__NR_membarrier, MEMBARRIER_CMD_QUERY, /* flags = */ 0);
  if (r == -1) {
    return false;
  }

  return r & MEMBARRIER_CMD_SHARED;
#else
  return false;
#endif
}

int sysMembarrier() {
#ifdef __NR_membarrier
  return syscall(__NR_membarrier, MEMBARRIER_CMD_SHARED, /* flags = */ 0);
#else
  return -1;
#endif
}
}
}
<commit_msg>Fix macro check in SysMembarrier<commit_after>/*
 * Copyright 2016 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "SysMembarrier.h"

#include <mutex>

#include <folly/Portability.h>
#include <folly/portability/Unistd.h>

#if !defined(__NR_membarrier) && FOLLY_X64 && !FOLLY_MOBILE
#define __NR_membarrier 324
#define MEMBARRIER_CMD_QUERY 0
#define MEMBARRIER_CMD_SHARED 1
#endif

namespace folly {
namespace detail {

bool sysMembarrierAvailable() {
  if (!kIsLinux) {
    return false;
  }

#ifdef __NR_membarrier
  auto r = syscall(__NR_membarrier, MEMBARRIER_CMD_QUERY, /* flags = */ 0);
  if (r == -1) {
    return false;
  }

  return r & MEMBARRIER_CMD_SHARED;
#else
  return false;
#endif
}

int sysMembarrier() {
#ifdef __NR_membarrier
  return syscall(__NR_membarrier, MEMBARRIER_CMD_SHARED, /* flags = */ 0);
#else
  return -1;
#endif
}
}
}
<|endoftext|>


<commit_before>#ifndef CTHREADRINGBUF
#define CTHREADRINGBUF
#include<atomic>
#include<condition_variable>
#include<memory>	//allocator
#include<mutex>
#include<type_traits>	//make_unsigned
#include<utility>	//forward, move
#include"../algorithm/algorithm.hpp"	//for_each_val

namespace nThread
{
	//a fixed-sized and cannot overwrite when buffer is full
	template<class T>
	class CThreadRingBuf
	{
	public:
		typedef std::allocator<T> allocator_type;
		typedef typename std::allocator<T>::size_type size_type;
		typedef T value_type;
	private:
		typedef typename std::allocator<T>::pointer pointer;
		static allocator_type alloc_;
		const pointer begin_;
		std::unique_ptr<std::atomic<bool> []> complete_;
		std::condition_variable cv_;
		const pointer end_;
		std::mutex read_mut_;
		size_type read_subscript_;
		std::atomic<size_type> write_subscript_;
		//can only be used when your write will not overwrite the data
		template<class TFwdRef>
		void write_(TFwdRef &&val)
		{
			const auto write{write_subscript_++};
			{
				std::lock_guard<std::mutex> lock{read_mut_};
				cv_.notify_all();
			}
			if(write<size())
				alloc_.construct(begin_+write,std::forward<TFwdRef>(val));
			else
				begin_[write%size()]=std::forward<TFwdRef>(val);
			complete_[write%size()]=true;
		}
	public:
		explicit CThreadRingBuf(const size_type size)
			:begin_{alloc_.allocate(size)},complete_{std::make_unique<std::atomic<bool>[]>(size)},end_{begin_+size},read_subscript_{0},write_subscript_{0}{}
		value_type read()
		{
			size_type read;
			{
				std::unique_lock<std::mutex> lock{read_mut_};
				cv_.wait(lock,[&]{
					if(read_subscript_<write_subscript_)
					{
						read=((read_subscript_++)%size());
						return true;
					}
					return false;
				});
			}
			while(!complete_[read])
				;
			complete_[read]=false;
			return std::move(begin_[read]);
		}
		inline size_type size() const noexcept
		{
			return end_-begin_;
		}
		inline void write(const T &val)
		{
			write_(val);
		}
		inline void write(T &&xval)
		{
			write_(std::move(xval));
		}
		~CThreadRingBuf()
		{
			nAlgorithm::for_each_val(begin_,end_,[&](const auto p){alloc_.destroy(p);});
			alloc_.deallocate(begin_,size());
		}
	};

	template<class T>
	typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_;
}

#endif<commit_msg>use CSemaphore and memory_order<commit_after>#ifndef CTHREADRINGBUF
#define CTHREADRINGBUF
#include<atomic>
#include<memory>	//allocator, make_unique, unique_ptr
#include<utility>	//forward, move
#include"CSemaphore.hpp"
#include"../algorithm/algorithm.hpp"	//for_each_val

namespace nThread
{
	//a fixed-sized and cannot overwrite when buffer is full
	//T must meet the requirements of move constructor and move assignment operator
	template<class T>
	class CThreadRingBuf
	{
	public:
		typedef std::allocator<T> allocator_type;
		typedef typename std::allocator<T>::size_type size_type;
		typedef T value_type;
	private:
		typedef typename std::allocator<T>::pointer pointer;
		static allocator_type alloc_;
		const pointer begin_;
		std::unique_ptr<std::atomic<bool> []> complete_;
		std::atomic<size_type> read_subscript_;
		CSemaphore sema_;
		size_type size_;
		std::atomic<size_type> use_construct_;
		std::atomic<size_type> write_subscript_;
		//can only be used when your write will not overwrite the data
		template<class TFwdRef>
		void write_(TFwdRef &&val)
		{
			sema_.signal();
			const auto write{write_subscript_++};
			if(write<size()&&use_construct_++<size())
				alloc_.construct(begin_+write,std::forward<TFwdRef>(val));
			else
				begin_[write%size()]=std::forward<TFwdRef>(val);
			complete_[write%size()].store(true,std::memory_order_release);
		}
	public:
		explicit CThreadRingBuf(const size_type size)
			:begin_{alloc_.allocate(size)},complete_{std::make_unique<std::atomic<bool>[]>(size)},sema_{0},size_{size},read_subscript_{0},use_construct_{0},write_subscript_{0}{}
		value_type read()
		{
			sema_.wait();
			const auto read{(read_subscript_++)%size()};
			while(!complete_[read].load(memory_order_acquire))
				;
			complete_[read]=false;
			return std::move(begin_[read]);
		}
		inline size_type size() const noexcept
		{
			return size_;
		}
		inline void write(const T &val)
		{
			write_(val);
		}
		inline void write(T &&xval)
		{
			write_(std::move(xval));
		}
		~CThreadRingBuf()
		{
			nAlgorithm::for_each_val(begin_,begin_+size(),[&](const auto p){alloc_.destroy(p);});
			alloc_.deallocate(begin_,size());
		}
	};

	template<class T>
	typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_;
}

#endif<|endoftext|>


<commit_before>#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_network.h"
#include "collector_engine.h"
#include "condor_io.h"
#include "sched.h"

// about self
static char *_FileName_ = __FILE__;

// prototypes
#ifndef WIN32
extern void reportToDevelopers (void);
extern "C" int schedule_event( int , int , int , int , int , void (*)(void));
#endif

// variables from the config file
extern char *CondorAdministrator;
extern char *CondorDevelopers;
extern int   ClientTimeout;
extern int   QueryTimeout;

extern CollectorEngine collector;

void
initializeParams()
{
    char *tmp;
	int		MachineUpdateInterval;
	int		MasterCheckInterval;

	if (CondorAdministrator) free (CondorAdministrator);
    if ((CondorAdministrator = param ("CONDOR_ADMIN")) == NULL)
	{
		EXCEPT ("Variable 'CONDOR_ADMIN' not found in condfig file.");
	}

	tmp = param ("CLIENT_TIMEOUT");
	if( tmp ) {
		ClientTimeout = atoi( tmp );
		free( tmp );
	} else {
		ClientTimeout = 30;
	}

	tmp = param ("QUERY_TIMEOUT");
	if( tmp ) {
		QueryTimeout = atoi( tmp );
		free( tmp );
	} else {
		QueryTimeout = 60;
	}

	tmp = param ("MACHINE_UPDATE_INTERVAL");
	if( tmp ) {
		MachineUpdateInterval = atoi( tmp );
		free( tmp );
	} else {
		MachineUpdateInterval = 300;
	}

	tmp = param ("MASTER_CHECK_INTERVAL");
	if( tmp ) {
		MasterCheckInterval = atoi( tmp );
		free( tmp );
	} else {
		MasterCheckInterval = 10800; 	// three hours
	}

	if (CondorDevelopers) free (CondorDevelopers);
	tmp = param ("CONDOR_DEVELOPERS");
	if (tmp == NULL) {
		tmp = strdup("condor-admin@cs.wisc.edu");
	} else
	if (strcmp (tmp, "NONE") == 0) {
		free (tmp);
		tmp = NULL;
	}
	CondorDevelopers = tmp;

	// set the appropriate parameters in the collector engine
	collector.setClientTimeout (ClientTimeout);
	collector.scheduleHousekeeper (MachineUpdateInterval);
	collector.scheduleDownMasterCheck(MasterCheckInterval);
}

#ifndef WIN32
void
initializeReporter (void)
{
	const int STAR = -1;

	// schedule reports to developers
	schedule_event( STAR, 1,  0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 8,  0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 15, 0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 23, 0, 0, 0, reportToDevelopers );
}
#endif
<commit_msg>Param for "CLASSAD_LIFETIME" to determine how old you're willing to let classads get before they timeout.  Defaults to 15 minutes.<commit_after>#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "condor_network.h"
#include "collector_engine.h"
#include "condor_io.h"
#include "sched.h"

// about self
static char *_FileName_ = __FILE__;

// prototypes
#ifndef WIN32
extern void reportToDevelopers (void);
extern "C" int schedule_event( int , int , int , int , int , void (*)(void));
#endif

// variables from the config file
extern char *CondorAdministrator;
extern char *CondorDevelopers;
extern int   ClientTimeout;
extern int   QueryTimeout;

extern CollectorEngine collector;

void
initializeParams()
{
    char *tmp;
	int		ClassadLifetime;
	int		MasterCheckInterval;

	if (CondorAdministrator) free (CondorAdministrator);
    if ((CondorAdministrator = param ("CONDOR_ADMIN")) == NULL)
	{
		EXCEPT ("Variable 'CONDOR_ADMIN' not found in condfig file.");
	}

	tmp = param ("CLIENT_TIMEOUT");
	if( tmp ) {
		ClientTimeout = atoi( tmp );
		free( tmp );
	} else {
		ClientTimeout = 30;
	}

	tmp = param ("QUERY_TIMEOUT");
	if( tmp ) {
		QueryTimeout = atoi( tmp );
		free( tmp );
	} else {
		QueryTimeout = 60;
	}

	tmp = param ("CLASSAD_LIFETIME");
	if( tmp ) {
		ClassadLifetime = atoi( tmp );
		free( tmp );
	} else {
		ClassadLifetime = 900;
	}

	tmp = param ("MASTER_CHECK_INTERVAL");
	if( tmp ) {
		MasterCheckInterval = atoi( tmp );
		free( tmp );
	} else {
		MasterCheckInterval = 10800; 	// three hours
	}

	if (CondorDevelopers) free (CondorDevelopers);
	tmp = param ("CONDOR_DEVELOPERS");
	if (tmp == NULL) {
		tmp = strdup("condor-admin@cs.wisc.edu");
	} else
	if (strcmp (tmp, "NONE") == 0) {
		free (tmp);
		tmp = NULL;
	}
	CondorDevelopers = tmp;

	// set the appropriate parameters in the collector engine
	collector.setClientTimeout( ClientTimeout );
	collector.scheduleHousekeeper( ClassadLifetime );
	collector.scheduleDownMasterCheck( MasterCheckInterval );
}

#ifndef WIN32
void
initializeReporter (void)
{
	const int STAR = -1;

	// schedule reports to developers
	schedule_event( STAR, 1,  0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 8,  0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 15, 0, 0, 0, reportToDevelopers );
	schedule_event( STAR, 23, 0, 0, 0, reportToDevelopers );
}
#endif
<|endoftext|>