<commit_before>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <iostream>
#include <string>
#include "module/global.hpp"
#include "module/World.hpp"
#include "module/Module.hpp"
#include "client/PatchModel.hpp"
#include "App.hpp"
#include "ThreadedLoader.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

ThreadedLoader::ThreadedLoader(SharedPtr<EngineInterface> engine)
	: _engine(engine)
	, _deprecated_loader(engine)
{
	set_name("Loader");

	if (parser())
		start();
	else
		cerr << "WARNING: Failed to load ingen_serialisation module, load disabled." << endl;
}

SharedPtr<Parser>
ThreadedLoader::parser()
{
	if (_parser)
		return _parser;

	World* world = App::instance().world();
	if (!world->serialisation_module)
		world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");

	if (world->serialisation_module) {
		Parser* (*new_parser)() = NULL;

		bool found = App::instance().world()->serialisation_module->get_symbol(
				"new_parser", (void*&)new_parser);

		if (found)
			_parser = SharedPtr<Parser>(new_parser());
	}

	return _parser;
}

void
ThreadedLoader::_whipped()
{
	_mutex.lock();

	while ( ! _events.empty() ) {
		_events.front()();
		_events.pop_front();
	}

	_mutex.unlock();
}

void
ThreadedLoader::load_patch(bool                    merge,
                           const Glib::ustring&    data_base_uri,
                           const Path&             data_path,
                           GraphObject::Variables  engine_data,
                           optional<Path>          engine_parent,
                           optional<Symbol>        engine_symbol)
{
	_mutex.lock();

	// FIXME: Filthy hack to load deprecated patches based on file extension
	if (data_base_uri.substr(data_base_uri.length()-3) == ".om") {
		_events.push_back(sigc::hide_return(sigc::bind(
				sigc::mem_fun(_deprecated_loader, &DeprecatedLoader::load_patch),
				data_base_uri,
				engine_parent,
				(engine_symbol) ? engine_symbol.get() : "",
				engine_data,
				false)));
	} else {
		Glib::ustring engine_base = "";
		if (engine_parent) {
			if (merge)
				engine_base = engine_parent.get();
			else
				engine_base = engine_parent.get().base();
		}

		if (merge && (!engine_parent || engine_parent.get() == "/"))
			engine_base = engine_base.substr(0, engine_base.find_last_of("/"));

		_events.push_back(sigc::hide_return(sigc::bind(
				sigc::mem_fun(_parser.get(), &Ingen::Serialisation::Parser::parse_document),
				App::instance().world(),
				App::instance().world()->engine.get(),
				data_base_uri, // document
				data_base_uri + data_path.substr(1), // object URI document
				engine_base,
				engine_symbol,
				engine_data)));
	}

	whip();

	_mutex.unlock();
}

void
ThreadedLoader::save_patch(SharedPtr<PatchModel> model, const string& filename)
{
	_mutex.lock();

	_events.push_back(sigc::hide_return(sigc::bind(
		sigc::mem_fun(this, &ThreadedLoader::save_patch_event),
		model, filename)));

	_mutex.unlock();

	whip();
}

void
ThreadedLoader::save_patch_event(SharedPtr<PatchModel> model, const string& filename)
{
	if (App::instance().serialiser())
		App::instance().serialiser()->to_file(model, filename);
}

} // namespace GUI
} // namespace Ingen
<commit_msg>Fix crash when importing .om patches.<commit_after>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <iostream>
#include <string>
#include "module/global.hpp"
#include "module/World.hpp"
#include "module/Module.hpp"
#include "client/PatchModel.hpp"
#include "App.hpp"
#include "ThreadedLoader.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

ThreadedLoader::ThreadedLoader(SharedPtr<EngineInterface> engine)
	: _engine(engine)
	, _deprecated_loader(engine)
{
	set_name("Loader");

	if (parser())
		start();
	else
		cerr << "WARNING: Failed to load ingen_serialisation module, load disabled." << endl;
}

SharedPtr<Parser>
ThreadedLoader::parser()
{
	if (_parser)
		return _parser;

	World* world = App::instance().world();
	if (!world->serialisation_module)
		world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");

	if (world->serialisation_module) {
		Parser* (*new_parser)() = NULL;

		bool found = App::instance().world()->serialisation_module->get_symbol(
				"new_parser", (void*&)new_parser);

		if (found)
			_parser = SharedPtr<Parser>(new_parser());
	}

	return _parser;
}

void
ThreadedLoader::_whipped()
{
	_mutex.lock();

	while ( ! _events.empty() ) {
		_events.front()();
		_events.pop_front();
	}

	_mutex.unlock();
}

void
ThreadedLoader::load_patch(bool                    merge,
                           const Glib::ustring&    data_base_uri,
                           const Path&             data_path,
                           GraphObject::Variables  engine_data,
                           optional<Path>          engine_parent,
                           optional<Symbol>        engine_symbol)
{
	_mutex.lock();

	// FIXME: Filthy hack to load deprecated patches based on file extension
	if (data_base_uri.substr(data_base_uri.length()-3) == ".om") {
		_events.push_back(sigc::hide_return(sigc::bind(
				sigc::mem_fun(_deprecated_loader, &DeprecatedLoader::load_patch),
				data_base_uri,
				engine_parent,
				engine_symbol ? (string)engine_symbol.get() : string(""),
				engine_data,
				false)));
	} else {
		Glib::ustring engine_base = "";
		if (engine_parent) {
			if (merge)
				engine_base = engine_parent.get();
			else
				engine_base = engine_parent.get().base();
		}

		if (merge && (!engine_parent || engine_parent.get() == "/"))
			engine_base = engine_base.substr(0, engine_base.find_last_of("/"));

		_events.push_back(sigc::hide_return(sigc::bind(
				sigc::mem_fun(_parser.get(), &Ingen::Serialisation::Parser::parse_document),
				App::instance().world(),
				App::instance().world()->engine.get(),
				data_base_uri, // document
				data_base_uri + data_path.substr(1), // object URI document
				engine_base,
				engine_symbol,
				engine_data)));
	}

	whip();

	_mutex.unlock();
}

void
ThreadedLoader::save_patch(SharedPtr<PatchModel> model, const string& filename)
{
	_mutex.lock();

	_events.push_back(sigc::hide_return(sigc::bind(
		sigc::mem_fun(this, &ThreadedLoader::save_patch_event),
		model, filename)));

	_mutex.unlock();

	whip();
}

void
ThreadedLoader::save_patch_event(SharedPtr<PatchModel> model, const string& filename)
{
	if (App::instance().serialiser())
		App::instance().serialiser()->to_file(model, filename);
}

} // namespace GUI
} // namespace Ingen
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, 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 "caffe2/operators/recurrent_network_executor.h"

#include "caffe2/core/timer.h"

namespace caffe2 {

template <>
std::unique_ptr<RecurrentNetworkExecutorBase> createRNNExecutor<CPUContext>(
    const NetDef& step_net_def,
    std::map<string, string>& recurrent_input_map,
    std::string timestep_blob,
    ArgumentHelper rnn_args) {
  auto* exec = new ThreadedRecurrentNetworkExecutor(
      step_net_def, recurrent_input_map, timestep_blob);
  int num_threads = rnn_args.GetSingleArgument<int>("rnn_executor.num_threads", 0);
  if (num_threads > 0) {
    exec->setNumThreads(num_threads);
    LOG(INFO) << "Set num threads: " << num_threads;
  }
  return std::unique_ptr<RecurrentNetworkExecutorBase>(exec);
}

bool ThreadedRecurrentNetworkExecutor::Run(int T) {
  CAFFE_ENFORCE(timestep_ops_.size() >= T);
  countdown_ = T * timestep_ops_[0].size();
  finished_timesteps_ = 0;

  // Frontier
  CHECK(job_queue_.size() == 0);

  for (auto& rnn_op : timestep_ops_[0]) {
    if (rnn_op.frontier) {
      job_queue_.Push(OpJob(0, rnn_op.order, T, 1));
    }
  }

  _Exec();
  return true;
}

bool ThreadedRecurrentNetworkExecutor::RunBackwards(int T) {
  CAFFE_ENFORCE(timestep_ops_.size() >= T);
  countdown_ = T * timestep_ops_[0].size();
  finished_timesteps_ = 0;

  // Frontier
  CHECK(job_queue_.size() == 0);

  for (auto& rnn_op : timestep_ops_[T - 1]) {
    if (rnn_op.frontier) {
      job_queue_.Push(OpJob(T - 1, rnn_op.order, T, -1));
    }
  }

  _Exec();
  return true;
}

void ThreadedRecurrentNetworkExecutor::RunOp(OpJob job, int thread_id) {
  bool first_timestep =
      ((job.forward() && job.timestep == 0) ||
       (job.backward() && job.timestep == job.T - 1));
  bool last_timestep =
      ((job.backward() && job.timestep == 0) ||
       (job.forward() && job.timestep == job.T - 1));
  auto& rnn_op = timestep_ops_[job.timestep][job.op_idx];
  if (rnn_op.num_dynamic_inputs > 0 && !rnn_op.frontier) {
    CAFFE_ENFORCE_EQ(
        rnn_op.proc_inputs,
        rnn_op.num_dynamic_inputs -
            first_timestep * rnn_op.num_recurrent_inputs,
        "Error at operator ",
        job.op_idx,
        " on timestep ",
        job.timestep,
        " T=",
        job.T,
        " first =",
        first_timestep);
  }

  // Reset input dependency counter
  rnn_op.proc_inputs = 0;

  // Run the operator
  rnn_op.op->Run();

  // Knock down dependencies and start next ops, if this
  // was last dependency fulfilled.
  for (int depidx : rnn_op.dependencies) {
    int t = job.timestep;
    bool for_next_timestep = depidx <= rnn_op.order;
    if (!last_timestep && for_next_timestep) {
      t += job.direction;
    } else if (for_next_timestep) {
      continue;
    }

    auto& dep_op = timestep_ops_[t][depidx];
    int proc_inputs = dep_op.proc_inputs.fetch_add(1) + 1;

    // Schedule next op, if this was the last dependency. Note that on
    // first timestep we don't have recurrent inputs.
    int num_req_inputs = dep_op.num_dynamic_inputs;
    if (first_timestep && !for_next_timestep) {
      num_req_inputs -= dep_op.num_recurrent_inputs;
    }

    if (proc_inputs == num_req_inputs || num_req_inputs == 0) {
      job_queue_.Push(OpJob(t, depidx, job.T, job.direction));
    }
  }

  if (countdown_.fetch_sub(1) == 1) {
    CAFFE_ENFORCE_EQ(0, job_queue_.size());
    std::unique_lock<std::mutex> lk(countdown_mtx_);
    cv_.notify_one();
  }
}

void ThreadedRecurrentNetworkExecutor::WorkerFunction() {
  size_t num_jobs = 0;
  static std::atomic<int> seq(0);
  int id = seq.fetch_add(1);

  while (!failed_) {
    OpJob job;
    if (!job_queue_.Pop(&job)) {
      break;
    }

    // Check for limited timestep parallelism
    if (max_parallel_timesteps_ > 0) {
      int t = (job.direction == 1 ? job.timestep : job.T - job.timestep + 1);
      if (t - finished_timesteps_ >= max_parallel_timesteps_) {
        // Return to queue
        job_queue_.Push(job);
        continue;
      }
    }

    try {
      RunOp(job, id);
      if (job.op_idx == timestep_ops_template_.size() - 1) {
        finished_timesteps_.fetch_add(1);
      }
      num_jobs++;
    } catch (::caffe2::EnforceNotMet& enf) {
      std::unique_lock<std::mutex> lk(countdown_mtx_);
      LOG(ERROR) << "Crash at thread " << id << " timestep " << job.timestep
                 << " op:"
                 << ProtoDebugString(step_net_def_.op(job.op_idx))
                 << enf.what();
      job_queue_.NoMoreJobs();
      failed_ = true;
      cv_.notify_one();
      return;
    }
  }
  VLOG(1) << "Worker exiting, did run: " << num_jobs << " jobs";
}

void ThreadedRecurrentNetworkExecutor::_Exec() {
  CAFFE_ENFORCE_EQ(false, failed_);

  // Start threads if not started
  std::unique_lock<std::mutex> lk(countdown_mtx_);
  while (workers_.size() < num_threads_) {
    VLOG(1) << "Start RNN worker " << workers_.size() << " / "
              << num_threads_;
    workers_.push_back(
        std::thread(&ThreadedRecurrentNetworkExecutor::WorkerFunction, this));
  }

  // Wait until threads finish.
  Timer t;
  cv_.wait_for(lk, std::chrono::seconds(30), [&] {
    // Log if we are still running, so that we catch deadlocks.. there
    // should not be any deadlocks, but...
    if (t.Seconds() > 10) {
      LOG(INFO) << "RNN Executor still running, remaining ops: " << countdown_;
    }
    return failed_ || countdown_ == 0;
  });

  CAFFE_ENFORCE_EQ(false, failed_, "Recurrent network execution failed");
  CAFFE_ENFORCE_EQ(
      0, countdown_, "Recurrent network execution did not finish in time");
  CAFFE_ENFORCE_EQ(job_queue_.size(), 0);
}

} // namespace caffe2
<commit_msg>remove timeout from RNN executor<commit_after>/**
 * Copyright (c) 2016-present, 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 "caffe2/operators/recurrent_network_executor.h"

#include "caffe2/core/timer.h"

namespace caffe2 {

template <>
std::unique_ptr<RecurrentNetworkExecutorBase> createRNNExecutor<CPUContext>(
    const NetDef& step_net_def,
    std::map<string, string>& recurrent_input_map,
    std::string timestep_blob,
    ArgumentHelper rnn_args) {
  auto* exec = new ThreadedRecurrentNetworkExecutor(
      step_net_def, recurrent_input_map, timestep_blob);
  int num_threads = rnn_args.GetSingleArgument<int>("rnn_executor.num_threads", 0);
  if (num_threads > 0) {
    exec->setNumThreads(num_threads);
    LOG(INFO) << "Set num threads: " << num_threads;
  }
  return std::unique_ptr<RecurrentNetworkExecutorBase>(exec);
}

bool ThreadedRecurrentNetworkExecutor::Run(int T) {
  CAFFE_ENFORCE(timestep_ops_.size() >= T);
  countdown_ = T * timestep_ops_[0].size();
  finished_timesteps_ = 0;

  // Frontier
  CHECK(job_queue_.size() == 0);

  for (auto& rnn_op : timestep_ops_[0]) {
    if (rnn_op.frontier) {
      job_queue_.Push(OpJob(0, rnn_op.order, T, 1));
    }
  }

  _Exec();
  return true;
}

bool ThreadedRecurrentNetworkExecutor::RunBackwards(int T) {
  CAFFE_ENFORCE(timestep_ops_.size() >= T);
  countdown_ = T * timestep_ops_[0].size();
  finished_timesteps_ = 0;

  // Frontier
  CHECK(job_queue_.size() == 0);

  for (auto& rnn_op : timestep_ops_[T - 1]) {
    if (rnn_op.frontier) {
      job_queue_.Push(OpJob(T - 1, rnn_op.order, T, -1));
    }
  }

  _Exec();
  return true;
}

void ThreadedRecurrentNetworkExecutor::RunOp(OpJob job, int thread_id) {
  bool first_timestep =
      ((job.forward() && job.timestep == 0) ||
       (job.backward() && job.timestep == job.T - 1));
  bool last_timestep =
      ((job.backward() && job.timestep == 0) ||
       (job.forward() && job.timestep == job.T - 1));
  auto& rnn_op = timestep_ops_[job.timestep][job.op_idx];
  if (rnn_op.num_dynamic_inputs > 0 && !rnn_op.frontier) {
    CAFFE_ENFORCE_EQ(
        rnn_op.proc_inputs,
        rnn_op.num_dynamic_inputs -
            first_timestep * rnn_op.num_recurrent_inputs,
        "Error at operator ",
        job.op_idx,
        " on timestep ",
        job.timestep,
        " T=",
        job.T,
        " first =",
        first_timestep);
  }

  // Reset input dependency counter
  rnn_op.proc_inputs = 0;

  // Run the operator
  rnn_op.op->Run();

  // Knock down dependencies and start next ops, if this
  // was last dependency fulfilled.
  for (int depidx : rnn_op.dependencies) {
    int t = job.timestep;
    bool for_next_timestep = depidx <= rnn_op.order;
    if (!last_timestep && for_next_timestep) {
      t += job.direction;
    } else if (for_next_timestep) {
      continue;
    }

    auto& dep_op = timestep_ops_[t][depidx];
    int proc_inputs = dep_op.proc_inputs.fetch_add(1) + 1;

    // Schedule next op, if this was the last dependency. Note that on
    // first timestep we don't have recurrent inputs.
    int num_req_inputs = dep_op.num_dynamic_inputs;
    if (first_timestep && !for_next_timestep) {
      num_req_inputs -= dep_op.num_recurrent_inputs;
    }

    if (proc_inputs == num_req_inputs || num_req_inputs == 0) {
      job_queue_.Push(OpJob(t, depidx, job.T, job.direction));
    }
  }

  if (countdown_.fetch_sub(1) == 1) {
    CAFFE_ENFORCE_EQ(0, job_queue_.size());
    std::unique_lock<std::mutex> lk(countdown_mtx_);
    cv_.notify_one();
  }
}

void ThreadedRecurrentNetworkExecutor::WorkerFunction() {
  size_t num_jobs = 0;
  static std::atomic<int> seq(0);
  int id = seq.fetch_add(1);

  while (!failed_) {
    OpJob job;
    if (!job_queue_.Pop(&job)) {
      break;
    }

    // Check for limited timestep parallelism
    if (max_parallel_timesteps_ > 0) {
      int t = (job.direction == 1 ? job.timestep : job.T - job.timestep + 1);
      if (t - finished_timesteps_ >= max_parallel_timesteps_) {
        // Return to queue
        job_queue_.Push(job);
        continue;
      }
    }

    try {
      RunOp(job, id);
      if (job.op_idx == timestep_ops_template_.size() - 1) {
        finished_timesteps_.fetch_add(1);
      }
      num_jobs++;
    } catch (::caffe2::EnforceNotMet& enf) {
      std::unique_lock<std::mutex> lk(countdown_mtx_);
      LOG(ERROR) << "Crash at thread " << id << " timestep " << job.timestep
                 << " op:"
                 << ProtoDebugString(step_net_def_.op(job.op_idx))
                 << enf.what();
      job_queue_.NoMoreJobs();
      failed_ = true;
      cv_.notify_one();
      return;
    }
  }
  VLOG(1) << "Worker exiting, did run: " << num_jobs << " jobs";
}

void ThreadedRecurrentNetworkExecutor::_Exec() {
  CAFFE_ENFORCE_EQ(false, failed_);

  // Start threads if not started
  std::unique_lock<std::mutex> lk(countdown_mtx_);
  while (workers_.size() < num_threads_) {
    VLOG(1) << "Start RNN worker " << workers_.size() << " / " << num_threads_;
    workers_.push_back(
        std::thread(&ThreadedRecurrentNetworkExecutor::WorkerFunction, this));
  }

  // Wait until threads finish.
  Timer t;
  while (!failed_ && countdown_ > 0) {
    cv_.wait_for(lk, std::chrono::seconds(30), [&] {
      // Log if we are still running, so that we catch deadlocks.. there
      // should not be any deadlocks, but...
      if (t.Seconds() > 10) {
        LOG(INFO) << "RNN Executor still running, remaining ops: "
                  << countdown_;
      }
      return failed_ || countdown_ == 0;
    });
  }
}

} // namespace caffe2
<|endoftext|>


<commit_before><commit_msg>coverity#707915 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>/*************************************************
*	main.cpp
*
*	Release: Sep 2016
*	Update: Sep 2016
*
*	University of North Carolina at Chapel Hill
*	Department of Computer Science
*
*	Ilwoo Lyu, ilwoolyu@cs.unc.edu
*************************************************/

#include <cstdlib>
#include <vector>
#include <string>
#include <dirent.h>
#include "GroupwiseRegistrationCLP.h"
#include "GroupwiseRegistration.h"

void getListFile(string path, vector<string> &list, const string &suffix)
{
	DIR *dir = opendir(path.c_str());
	if (dir != NULL)
	{
		while (dirent *entry = readdir(dir))
		{
			string filename = entry->d_name;
		    if (filename.size() >= suffix.size() && equal(suffix.rbegin(), suffix.rend(), filename.rbegin()))
				list.push_back(path + "/" + filename);
		}
	}
	closedir(dir);
	sort(list.begin(), list.begin() + list.size());
}

void getTrimmedList(vector<string> &list, const vector<string> &name)
{
	int i = 0;
	while (i < list.size())
	{
		size_t found;
		for (int j = 0; j < name.size(); j++)
		{
			found = list[i].find(name[j].substr(name[j].rfind('/') + 1));
			if (string::npos != found) break;
		}
		if (string::npos == found) list.erase(list.begin() + i);
		else i++;
	}
	sort(list.begin(), list.begin() + list.size());
}

int main(int argc , char *argv[])
{
	PARSE_ARGS;

	if (argc == 1)
	{
		cout << "Usage: " << argv[0] << " --help" << endl;
		return EXIT_SUCCESS;
	}

	// update list files from the directory information
	if (!dirSphere.empty() && listSphere.empty()) getListFile(dirSphere, listSphere, "vtk");
	if (!dirProperty.empty() && listProperty.empty()) getListFile(dirProperty, listProperty, "txt");
	if (!dirSurf.empty() && listSurf.empty()) getListFile(dirSurf, listSurf, "vtk");
	if (!dirLandmark.empty() && listLandmark.empty()) getListFile(dirLandmark, listLandmark, "txt");
	if (!dirCoeff.empty() && listCoeff.empty()) getListFile(dirCoeff, listCoeff, "coeff");

	// subject names
	int nSubj = listSphere.size();
	vector<string> subjName;
	if (nSubj > 0)
	{
		for (int i = 0; i < nSubj; i++)
		{
			int pivot = listSphere[i].rfind('/') + 1;
			string name = listSphere[i].substr(pivot, listSphere[i].length() - 4 - pivot);
			subjName.push_back(name.substr(0, name.rfind('.')));
		}
	}
	//for (int i = 0; i < nSubj; i++) cout << subjName[i] << endl;
	if (listOutput.empty())
		for (int i = 0; i < nSubj; i++) listOutput.push_back(dirOutput + "/" + subjName[i] + ".coeff");

	// trim all irrelevant files to the sphere files
	if (!listProperty.empty()) getTrimmedList(listProperty, subjName);
	if (!listLandmark.empty()) getTrimmedList(listLandmark, subjName);
	if (!listCoeff.empty()) getTrimmedList(listCoeff, subjName);
	if (!listProperty.empty()) getTrimmedList(listProperty, listFilter);
	if (listWeight.empty())
		for (int i = 0; i < listProperty.size() / listSurf.size(); i++)
			listWeight.push_back(1);

	int nProperties = listProperty.size();
	int nOutput = listOutput.size();
	int nWeight = listWeight.size();
	int nLandmark = listLandmark.size();
	int nCoeff = listCoeff.size();
	int nSurf = listSurf.size();

	const char **property = NULL;
	const char **sphere = NULL;
	const char **output = NULL;
	const char **landmark = NULL;
	const char **coeff = NULL;
	const char **surf = NULL;

	if (nProperties > 0) property = new const char*[nProperties];
	if (nSubj > 0) sphere = new const char*[nSubj];
	if (nOutput > 0) output = new const char*[nOutput];
	if (nLandmark > 0) landmark = new const char*[nLandmark];
	if (nCoeff > 0) coeff = new const char*[nCoeff];
	if (nSurf > 0) surf = new const char*[nSurf];
	if (surf == NULL) weightLoc = 0;
	float *weight = new float[nWeight];

	// exception handling
	if (nSubj != nOutput)
	{
		cout << "Fatal error: # of subjects is incosistent with # of outputs!" << endl;
		return EXIT_FAILURE;
	}
	else if (nLandmark == 0 && nProperties == 0)
	{
		cout << "Fatal error: neither landmarks nor properties are provided!" << endl;
		return EXIT_FAILURE;
	}
	else if (nProperties / nSubj != nWeight)
	{
		cout << "Fatal error: # of properties is incosistent with # of weighting factors!" << endl;
		return EXIT_FAILURE;
	}

	for (int i = 0; i < nSubj; i++) sphere[i] = listSphere[i].c_str();
	for (int i = 0; i < nProperties; i++) property[i] = listProperty[i].c_str();
	for (int i = 0; i < nOutput; i++) output[i] = listOutput[i].c_str();
	for (int i = 0; i < nLandmark; i++) landmark[i] = listLandmark[i].c_str();
	for (int i = 0; i < nCoeff; i++) coeff[i] = listCoeff[i].c_str();
	for (int i = 0; i < nSurf; i++) surf[i] = listSurf[i].c_str();
	for (int i = 0; i < nWeight; i++) weight[i] = listWeight[i];
	if (nWeight == 0) for (int i = 0; i < nProperties / nSubj; i++) weight[i] = 1;

	// display for lists of files
	cout << "Property: " << nProperties / nSubj << endl;	for (int i = 0; i < nProperties; i++) cout << property[i] << endl;
	cout << "Sphere: " << nSubj << endl;					for (int i = 0; i < nSubj; i++) cout << sphere[i] << endl;
	cout << "Output: " << nOutput << endl;					for (int i = 0; i < nOutput; i++) cout << output[i] << endl;
	cout << "Landmark: " << nLandmark << endl;				for (int i = 0; i < nLandmark; i++) cout << landmark[i] << endl;
	cout << "Coefficient: " << nCoeff << endl;				for (int i = 0; i < nCoeff; i++) cout << coeff[i] << endl;
	cout << "Surface: " << nSurf << endl;					for (int i = 0; i < nSurf; i++) cout << surf[i] << endl;

	GroupwiseRegistration groups(sphere, nSubj, property, nProperties / nSubj, output, weight, degree, landmark, weightLoc, coeff, surf, maxIter);
	groups.run();

	// delete memory allocation
	delete [] property;
	delete [] sphere;
	delete [] output;
	delete [] landmark;
	delete [] coeff;
	delete [] surf;
	delete [] weight;

	return EXIT_SUCCESS;
}
<commit_msg>Bug fixed: filename handling<commit_after>/*************************************************
*	main.cpp
*
*	Release: Sep 2016
*	Update: Sep 2016
*
*	University of North Carolina at Chapel Hill
*	Department of Computer Science
*
*	Ilwoo Lyu, ilwoolyu@cs.unc.edu
*************************************************/

#include <cstdlib>
#include <vector>
#include <string>
#include <dirent.h>
#include "GroupwiseRegistrationCLP.h"
#include "GroupwiseRegistration.h"

void getListFile(string path, vector<string> &list, const string &suffix)
{
	DIR *dir = opendir(path.c_str());
	if (dir != NULL)
	{
		while (dirent *entry = readdir(dir))
		{
			string filename = entry->d_name;
		    if (filename.size() >= suffix.size() && equal(suffix.rbegin(), suffix.rend(), filename.rbegin()))
				list.push_back(path + "/" + filename);
		}
	}
	closedir(dir);
	sort(list.begin(), list.begin() + list.size());
}

void getTrimmedList(vector<string> &list, const vector<string> &name)
{
	int i = 0;
	while (i < list.size())
	{
		size_t found;
		for (int j = 0; j < name.size(); j++)
		{
			found = list[i].find(name[j].substr(name[j].rfind('/') + 1));
			if (string::npos != found) break;
		}
		if (string::npos == found) list.erase(list.begin() + i);
		else i++;
	}
	sort(list.begin(), list.begin() + list.size());
}

int main(int argc , char *argv[])
{
	PARSE_ARGS;

	if (argc == 1)
	{
		cout << "Usage: " << argv[0] << " --help" << endl;
		return EXIT_SUCCESS;
	}

	// update list files from the directory information
	if (!dirSphere.empty() && listSphere.empty()) getListFile(dirSphere, listSphere, "vtk");
	if (!dirProperty.empty() && listProperty.empty()) getListFile(dirProperty, listProperty, "txt");
	if (!dirSurf.empty() && listSurf.empty()) getListFile(dirSurf, listSurf, "vtk");
	if (!dirLandmark.empty() && listLandmark.empty()) getListFile(dirLandmark, listLandmark, "txt");
	if (!dirCoeff.empty() && listCoeff.empty()) getListFile(dirCoeff, listCoeff, "coeff");

	// subject names
	int nSubj = listSphere.size();
	vector<string> subjName;
	if (nSubj > 0)
	{
		for (int i = 0; i < nSubj; i++)
		{
			int pivot = listSphere[i].rfind('/') + 1;
			string name = listSphere[i].substr(pivot, listSphere[i].length() - 4 - pivot);
			pivot = name.rfind('.');
			if (pivot == string::npos) pivot = name.length();
			subjName.push_back(name.substr(0, pivot));
		}
	}
	//for (int i = 0; i < nSubj; i++) cout << subjName[i] << endl;
	if (listOutput.empty())
		for (int i = 0; i < nSubj; i++) listOutput.push_back(dirOutput + "/" + subjName[i] + ".coeff");

	// trim all irrelevant files to the sphere files
	if (!listProperty.empty()) getTrimmedList(listProperty, subjName);
	if (!listLandmark.empty()) getTrimmedList(listLandmark, subjName);
	if (!listCoeff.empty()) getTrimmedList(listCoeff, subjName);
	if (!listProperty.empty()) getTrimmedList(listProperty, listFilter);
	if (listWeight.empty())
		for (int i = 0; i < listProperty.size() / listSurf.size(); i++)
			listWeight.push_back(1);

	int nProperties = listProperty.size();
	int nOutput = listOutput.size();
	int nWeight = listWeight.size();
	int nLandmark = listLandmark.size();
	int nCoeff = listCoeff.size();
	int nSurf = listSurf.size();

	const char **property = NULL;
	const char **sphere = NULL;
	const char **output = NULL;
	const char **landmark = NULL;
	const char **coeff = NULL;
	const char **surf = NULL;

	if (nProperties > 0) property = new const char*[nProperties];
	if (nSubj > 0) sphere = new const char*[nSubj];
	if (nOutput > 0) output = new const char*[nOutput];
	if (nLandmark > 0) landmark = new const char*[nLandmark];
	if (nCoeff > 0) coeff = new const char*[nCoeff];
	if (nSurf > 0) surf = new const char*[nSurf];
	if (surf == NULL) weightLoc = 0;
	float *weight = new float[nWeight];

	// exception handling
	if (nSubj != nOutput)
	{
		cout << "Fatal error: # of subjects is incosistent with # of outputs!" << endl;
		return EXIT_FAILURE;
	}
	else if (nLandmark == 0 && nProperties == 0)
	{
		cout << "Fatal error: neither landmarks nor properties are provided!" << endl;
		return EXIT_FAILURE;
	}
	else if (nProperties / nSubj != nWeight)
	{
		cout << "Fatal error: # of properties is incosistent with # of weighting factors!" << endl;
		return EXIT_FAILURE;
	}

	for (int i = 0; i < nSubj; i++) sphere[i] = listSphere[i].c_str();
	for (int i = 0; i < nProperties; i++) property[i] = listProperty[i].c_str();
	for (int i = 0; i < nOutput; i++) output[i] = listOutput[i].c_str();
	for (int i = 0; i < nLandmark; i++) landmark[i] = listLandmark[i].c_str();
	for (int i = 0; i < nCoeff; i++) coeff[i] = listCoeff[i].c_str();
	for (int i = 0; i < nSurf; i++) surf[i] = listSurf[i].c_str();
	for (int i = 0; i < nWeight; i++) weight[i] = listWeight[i];
	if (nWeight == 0) for (int i = 0; i < nProperties / nSubj; i++) weight[i] = 1;

	// display for lists of files
	cout << "Property: " << nProperties / nSubj << endl;	for (int i = 0; i < nProperties; i++) cout << property[i] << endl;
	cout << "Sphere: " << nSubj << endl;					for (int i = 0; i < nSubj; i++) cout << sphere[i] << endl;
	cout << "Output: " << nOutput << endl;					for (int i = 0; i < nOutput; i++) cout << output[i] << endl;
	cout << "Landmark: " << nLandmark << endl;				for (int i = 0; i < nLandmark; i++) cout << landmark[i] << endl;
	cout << "Coefficient: " << nCoeff << endl;				for (int i = 0; i < nCoeff; i++) cout << coeff[i] << endl;
	cout << "Surface: " << nSurf << endl;					for (int i = 0; i < nSurf; i++) cout << surf[i] << endl;

	GroupwiseRegistration groups(sphere, nSubj, property, nProperties / nSubj, output, weight, degree, landmark, weightLoc, coeff, surf, maxIter);
	groups.run();

	// delete memory allocation
	delete [] property;
	delete [] sphere;
	delete [] output;
	delete [] landmark;
	delete [] coeff;
	delete [] surf;
	delete [] weight;

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// UNCLASSIFIED
#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "dosc/decoder.hpp"
#include <stdexcept>
#include <algorithm>
#include <boost/range/algorithm/find.hpp>

namespace dosc {
const std::string decoder::all = "";

struct osc_time {
        uint32_t seconds; // since midnight 1 Jan 1900
        uint32_t frac;    // fractional seconds
};

void
chomp_string(const_buffer_range& range, const size_t max_nul)
{
        const_buffer_iterator end = range.first;
        advance(end, max_nul);
        end = min(end, range.second);
        for (; range.first != end && *range.first == '\0'; advance(range.first, 1)) ;
}

// calculate the size of the arguments and return the iterator that indicates the end.
static const_buffer_iterator calculate_size(const std::string& type_string, const_buffer_range range)
{
        const const_buffer_iterator start = range.first;
        for (std::string::const_iterator i = type_string.begin(); i != type_string.end(); ++i) {
                if (range.first >= range.second) {
                        return range.second;
                }
                switch (*i) {
                case osc_int32_tag:
                case osc_float_tag:
                case osc_char_tag:
                case osc_rgba_tag:
                case osc_midi_tag:
                        advance(range.first, 4);
                        break;
                case osc_int64_tag:
                case osc_time_tag:
                case osc_double_tag:
                        advance(range.first, 8);
                        break;
                case osc_string_tag:
                case osc_alt_string_tag: {
                        const const_buffer_iterator start = range.first;
                        while (range.first < range.second && *range.first != '\0') {
                                advance(range.first, 1);
                        }
                        chomp_string(range, 4 - distance(start, range.first) % 4);
                }
                        break;
                case osc_blob_tag:
                {
                        int32_t size = 0;
                        std::copy(range.first, range.first + 4, reinterpret_cast<char*>(&size));
                        advance(range.first, 4 + size);
                        if (int extra = size % 4) {
                                advance(range.first, 4 - extra);
                        }
                }
                        break;
                case osc_array_beg_tag:
                case osc_array_end_tag:
                        assert(false); // not implemented yet
                        break;
                case osc_true_tag:
                case osc_false_tag:
                case osc_nil_tag:
                case osc_infinitum_tag:
                default:
                        break;
                }
        }
        return range.first;
}

int32_t
decode_int32_tag(const_buffer_range& range)
{
        if (boost::size(range) < 4) {
                throw std::runtime_error("range is too small");
        }
        int32_t tag;
        std::reverse_copy(range.first, range.first + 4, reinterpret_cast<char*>(&tag));
        advance(range.first, 4);
        return tag;
}

int64_t
decode_int64_tag(const_buffer_range& range)
{
        if (boost::size(range) < 8) {
                throw std::runtime_error("range is too small");
        }
        int64_t tag;
        std::reverse_copy(range.first, range.first + 8, reinterpret_cast<char*>(&tag));
        advance(range.first, 8);
        return tag;
}

float
decode_float_tag(const_buffer_range& range)
{
        if (boost::size(range) < 4) {
                throw std::runtime_error("range is too small");
        }
        float tag;
        std::reverse_copy(range.first, range.first + 4, reinterpret_cast<char*>(&tag));
        advance(range.first, 4);
        return tag;
}

double
decode_double_tag(const_buffer_range& range)
{
        if (boost::size(range) < 8) {
                throw std::runtime_error("range is too small");
        }
        double tag;
        std::reverse_copy(range.first, range.first + 8, reinterpret_cast<char*>(&tag));
        advance(range.first, 8);
        return tag;
}

const char*
decode_string_tag(const_buffer_range& range)
{
        const_buffer_iterator null_pos = boost::find(range, '\0');
        if (null_pos == range.second) {
                throw std::runtime_error("Invalid string!");
        }
        const size_t length = distance(range.first, null_pos);
        const char* tag = reinterpret_cast<const char*>(&*range.first);
        range.first = null_pos;
        chomp_string(range, 4 - (length % 4));
        return tag;
}

void
decoder::operator()(const bytes_ptr packet)
{
        parse(make_pair(packet->begin(), packet->end()));
}

const_buffer_iterator
decoder::parse(const_buffer_range range)
{
        while (range.first < range.second) {
                switch (*range.first) {
                case '#': // bundle
                        //std::cout << "bundle" << std::endl;
                        range.first = parse_bundle(range);
                        //std::cout << "bundle done" << std::endl;
                        break;
                case '/': // message
                        //std::cout << "message" << std::endl;
                        range.first = parse_message(range);
                        //std::cout << "message done" << std::endl;
                        break;
                default:
                        //std::cout << "Warning: unrecognized character @ start of element: 0x" << static_cast<unsigned int>(*range.first) << std::endl;
                        advance(range.first, 1);
                }
        }
        //std::cout << "packet done" << std::endl;
        return range.first;
}

const_buffer_iterator
decoder::parse_message(const_buffer_range range)
{
        for (; range.first != range.second && *range.first; advance(range.first, 1)) {
                address_.push_back(*range.first);
        }
        chomp_string(range, 4 - address_.size() % 4);

        // type string is optional
        if (range.first != range.second && *range.first == ',') {
                for (; range.first != range.second && *range.first != '\0'; advance(range.first, 1)) {
                        type_.push_back(*range.first);
                }
                chomp_string(range, 4 - type_.size() % 4);
        }
        const_buffer_iterator arg_end = calculate_size(type_, range);
        const_buffer_range arguments(range.first, arg_end);
        methods_[all](address_, type_, arguments);
        address_.clear();
        type_.clear();

        return arg_end;
}

static const_buffer_iterator parse_time(const_buffer_range range, osc_time& time)
{
        advance(range.first, 8);
        return range.first;
}

const_buffer_iterator
decoder::parse_bundle(const_buffer_range range)
{
        if (std::string(range.first, range.first + 7) != "#bundle") {
                std::cout << "Warning: bad bundle identifier" << std::endl;
                advance(range.first, 1);
                return range.first;
        }
        advance(range.first, 8); // length of "#bundle" + '\0' terminator

        osc_time time;
        range.first = parse_time(range, time);

        // parse the bundle elements
        while (range.first < range.second) {
                int32_t element_size = 0;
                const const_buffer_iterator size_start = range.first;
                advance(range.first, 4);
                std::reverse_copy(size_start, range.first, reinterpret_cast<char*>(&element_size));
                parse(range);
                assert(element_size % 4 == 0);
                while (element_size % 4) {
                        element_size += 1;
                }
                advance(range.first, element_size);
        }
        return range.first;
}

} // namespace dosc
<commit_msg>Fix a bug in the DOSC decoder.<commit_after>// UNCLASSIFIED
#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "dosc/decoder.hpp"
#include <stdexcept>
#include <algorithm>
#include <boost/range/algorithm/find.hpp>

namespace dosc {
const std::string decoder::all = "";

struct osc_time {
        uint32_t seconds; // since midnight 1 Jan 1900
        uint32_t frac;    // fractional seconds
};

void
chomp_string(const_buffer_range& range, const size_t max_nul)
{
        const_buffer_iterator end = range.first;
        advance(end, max_nul);
        end = min(end, range.second);
        for (; range.first != end && *range.first == '\0'; advance(range.first, 1)) ;
}

// calculate the size of the arguments and return the iterator that indicates the end.
static const_buffer_iterator calculate_size(const std::string& type_string, const_buffer_range range)
{
        const const_buffer_iterator start = range.first;
        for (std::string::const_iterator i = type_string.begin(); i != type_string.end(); ++i) {
                if (range.first >= range.second) {
                        return range.second;
                }
                switch (*i) {
                case osc_int32_tag:
                case osc_float_tag:
                case osc_char_tag:
                case osc_rgba_tag:
                case osc_midi_tag:
                        advance(range.first, 4);
                        break;
                case osc_int64_tag:
                case osc_time_tag:
                case osc_double_tag:
                        advance(range.first, 8);
                        break;
                case osc_string_tag:
                case osc_alt_string_tag: {
                        const const_buffer_iterator start = range.first;
                        while (range.first < range.second && *range.first != '\0') {
                                advance(range.first, 1);
                        }
                        chomp_string(range, 4 - distance(start, range.first) % 4);
                }
                        break;
                case osc_blob_tag:
                {
                        int32_t size = 0;
                        std::copy(range.first, range.first + 4, reinterpret_cast<char*>(&size));
                        advance(range.first, 4 + size);
                        if (int extra = size % 4) {
                                advance(range.first, 4 - extra);
                        }
                }
                        break;
                case osc_array_beg_tag:
                case osc_array_end_tag:
                        assert(false); // not implemented yet
                        break;
                case osc_true_tag:
                case osc_false_tag:
                case osc_nil_tag:
                case osc_infinitum_tag:
                default:
                        break;
                }
        }
        return range.first;
}

int32_t
decode_int32_tag(const_buffer_range& range)
{
        if (boost::size(range) < 4) {
                throw std::runtime_error("range is too small");
        }
        int32_t tag;
        std::reverse_copy(range.first, range.first + 4, reinterpret_cast<char*>(&tag));
        advance(range.first, 4);
        return tag;
}

int64_t
decode_int64_tag(const_buffer_range& range)
{
        if (boost::size(range) < 8) {
                throw std::runtime_error("range is too small");
        }
        int64_t tag;
        std::reverse_copy(range.first, range.first + 8, reinterpret_cast<char*>(&tag));
        advance(range.first, 8);
        return tag;
}

float
decode_float_tag(const_buffer_range& range)
{
        if (boost::size(range) < 4) {
                throw std::runtime_error("range is too small");
        }
        float tag;
        std::reverse_copy(range.first, range.first + 4, reinterpret_cast<char*>(&tag));
        advance(range.first, 4);
        return tag;
}

double
decode_double_tag(const_buffer_range& range)
{
        if (boost::size(range) < 8) {
                throw std::runtime_error("range is too small");
        }
        double tag;
        std::reverse_copy(range.first, range.first + 8, reinterpret_cast<char*>(&tag));
        advance(range.first, 8);
        return tag;
}

const char*
decode_string_tag(const_buffer_range& range)
{
        const_buffer_iterator null_pos = boost::find(range, '\0');
        if (null_pos == range.second) {
                throw std::runtime_error("Invalid string!");
        }
        const size_t length = distance(range.first, null_pos);
        const char* tag = reinterpret_cast<const char*>(&*range.first);
        range.first = null_pos;
        chomp_string(range, 4 - (length % 4));
        return tag;
}

void
decoder::operator()(const bytes_ptr packet)
{
        parse(make_pair(packet->begin(), packet->end()));
}

const_buffer_iterator
decoder::parse(const_buffer_range range)
{
        while (range.first < range.second) {
                switch (*range.first) {
                case '#': // bundle
                        //std::cout << "bundle" << std::endl;
                        range.first = parse_bundle(range);
                        //std::cout << "bundle done" << std::endl;
                        break;
                case '/': // message
                        //std::cout << "message" << std::endl;
                        range.first = parse_message(range);
                        //std::cout << "message done" << std::endl;
                        break;
                default:
                        //std::cout << "Warning: unrecognized character @ start of element: 0x" << static_cast<unsigned int>(*range.first) << std::endl;
                        advance(range.first, 1);
                }
        }
        //std::cout << "packet done" << std::endl;
        return range.first;
}

const_buffer_iterator
decoder::parse_message(const_buffer_range range)
{
        for (; range.first != range.second && *range.first; advance(range.first, 1)) {
                address_.push_back(*range.first);
        }
        chomp_string(range, 4 - address_.size() % 4);

        // type string is optional
        if (range.first != range.second && *range.first == ',') {
                for (; range.first != range.second && *range.first != '\0'; advance(range.first, 1)) {
                        type_.push_back(*range.first);
                }
                chomp_string(range, 4 - type_.size() % 4);
        }
        const_buffer_iterator arg_end = calculate_size(type_, range);
        const_buffer_range arguments(range.first, arg_end);
        methods_[all](address_, type_, arguments);
        address_.clear();
        type_.clear();

        return arg_end;
}

static const_buffer_iterator parse_time(const_buffer_range range, osc_time& time)
{
        advance(range.first, 8);
        return range.first;
}

const_buffer_iterator
decoder::parse_bundle(const_buffer_range range)
{
        if (std::string(range.first, range.first + 7) != "#bundle") {
                std::cout << "Warning: bad bundle identifier" << std::endl;
                advance(range.first, 1);
                return range.first;
        }
        advance(range.first, 8); // length of "#bundle" + '\0' terminator

        osc_time time;
        range.first = parse_time(range, time);

        // parse the bundle elements
        while (range.first < range.second) {
                int32_t element_size = 0;
                const const_buffer_iterator size_start = range.first;
                advance(range.first, 4);
                std::reverse_copy(size_start, range.first, reinterpret_cast<char*>(&element_size));
                // make a new range so that the parse function only parses a single bundle element.
                parse(make_pair(range.first, range.first + element_size));
                assert(element_size % 4 == 0);
                while (element_size % 4) {
                        element_size += 1;
                }
                advance(range.first, element_size);
        }
        return range.first;
}

} // namespace dosc
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnordmetric/environment.h>
#include <fnordmetric/metricdb/adminui.h>
#include <fnordmetric/util/assets.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>

namespace fnordmetric {
namespace metricdb {

xzero::HttpService::Handler* AdminUI::get() {
  static AdminUI self;
  return &self;
}

bool AdminUI::handleRequest(xzero::HttpRequest* request,
                            xzero::HttpResponse* response) {

  if (env()->verbose()) {
    fnord::util::LogEntry log_entry;
    log_entry.append("__severity__", "DEBUG");
    log_entry.printf(
        "__message__",
        "HTTP request: %s %s",
        request->unparsedMethod().c_str(),
        request->path().c_str());

    env()->logger()->log(log_entry);
  }

  auto url = request->path();

  if (url == "/") {
    response->setStatus(xzero::HttpStatus::Found);
    response->addHeader("Content-Type", "text/html; charset=utf-8");
    response->addHeader("Location", "/admin");
    response->completed();
    return true;
  }

  if (url == "/admin") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.html",
        "text/html; charset=utf-8");
    return true;
  }

  if (url == "/favicon.ico") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-favicon.ico",
        "image/x-icon");
    return true;
  }

  if (url == "/s/fnordmetric.js") {
    sendAsset(
        response,
        "fnordmetric-js/fnordmetric.js",
        "text/javascript");
    return true;
  }

  if (url == "/s/fnordmetric-webui.css") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.css",
        "text/css");
    return true;
  }

  if (url == "/s/fnordmetric-webui.js") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.js",
        "text/javascript");
    return true;
  }

  return false;
}

void AdminUI::sendAsset(
    xzero::HttpResponse* response,
    const std::string& asset_path,
    const std::string& content_type) const {
  auto asset_data = util::Assets::getAsset(asset_path);
  response->setStatus(xzero::HttpStatus::Ok);
  response->addHeader("Content-Type", content_type);
  response->setContentLength(asset_data.size());

  response->output()->write(
      asset_data,
      std::bind(&xzero::HttpResponse::completed, response));
}

}
}
<commit_msg>fontawesome :)<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnordmetric/environment.h>
#include <fnordmetric/metricdb/adminui.h>
#include <fnordmetric/util/assets.h>
#include <xzero/http/HttpRequest.h>
#include <xzero/http/HttpResponse.h>

namespace fnordmetric {
namespace metricdb {

xzero::HttpService::Handler* AdminUI::get() {
  static AdminUI self;
  return &self;
}

bool AdminUI::handleRequest(xzero::HttpRequest* request,
                            xzero::HttpResponse* response) {

  if (env()->verbose()) {
    fnord::util::LogEntry log_entry;
    log_entry.append("__severity__", "DEBUG");
    log_entry.printf(
        "__message__",
        "HTTP request: %s %s",
        request->unparsedMethod().c_str(),
        request->path().c_str());

    env()->logger()->log(log_entry);
  }

  auto url = request->path();

  if (url == "/") {
    response->setStatus(xzero::HttpStatus::Found);
    response->addHeader("Content-Type", "text/html; charset=utf-8");
    response->addHeader("Location", "/admin");
    response->completed();
    return true;
  }

  if (url == "/admin") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.html",
        "text/html; charset=utf-8");
    return true;
  }

  if (url == "/favicon.ico") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-favicon.ico",
        "image/x-icon");
    return true;
  }

  if (url == "/s/fnordmetric.js") {
    sendAsset(
        response,
        "fnordmetric-js/fnordmetric.js",
        "text/javascript");
    return true;
  }

  if (url == "/s/fnordmetric-webui.css") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.css",
        "text/css");
    return true;
  }

  if (url == "/s/fnordmetric-webui.js") {
    sendAsset(
        response,
        "fnordmetric-webui/fnordmetric-webui.js",
        "text/javascript");
    return true;
  }

  if (url == "/s/fontawesome.woff") {
    sendAsset(
        response,
        "fnordmetric-webui/fontawesome.woff",
        "application/x-font-woff");
    return true;
  }

  return false;
}

void AdminUI::sendAsset(
    xzero::HttpResponse* response,
    const std::string& asset_path,
    const std::string& content_type) const {
  auto asset_data = util::Assets::getAsset(asset_path);
  response->setStatus(xzero::HttpStatus::Ok);
  response->addHeader("Content-Type", content_type);
  response->setContentLength(asset_data.size());

  response->output()->write(
      asset_data,
      std::bind(&xzero::HttpResponse::completed, response));
}

}
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -emit-llvm-only -verify %s
// PR6641

extern "C" int printf(const char *, ...);

struct Foo {
 Foo() : iFoo (2) {
  printf("%p\n", this);
 }
 int iFoo;
};

typedef Foo (*T)[3][4];

T bar() {
 return new Foo[2][3][4];
}

T bug(int i) {
  return new Foo[i][3][4];
}

void pr(T a) {
  for (int i = 0; i < 3; i++)
   for (int j = 0; j < 4; j++)
     printf("%p\n", a[i][j]);
}

Foo *test() {
  return new Foo[5];
}

int main() {
 T f =  bar();
 pr(f);
 f = bug(3);
 pr(f);

 Foo * g = test();
 for (int i = 0; i < 5; i++)
 printf("%d\n", g[i].iFoo);
 return 0;
}
<commit_msg>Check for some code gen. for PR6641 test.<commit_after>// RUN: %clang_cc1 %s -triple x86_64-unknown-unknown -emit-llvm -o - | FileCheck %s
// PR6641

extern "C" int printf(const char *, ...);

struct Foo {
 Foo() : iFoo (2) {
  printf("%p\n", this);
 }
 int iFoo;
};

typedef Foo (*T)[3][4];

T bar() {
 return new Foo[2][3][4];
}

T bug(int i) {
  return new Foo[i][3][4];
}

void pr(T a) {
  for (int i = 0; i < 3; i++)
   for (int j = 0; j < 4; j++)
     printf("%p\n", a[i][j]);
}

Foo *test() {
  return new Foo[5];
}

int main() {
 T f =  bar();
 pr(f);
 f = bug(3);
 pr(f);

 Foo * g = test();
 for (int i = 0; i < 5; i++)
 printf("%d\n", g[i].iFoo);
 return 0;
}

// CHECK: call noalias i8* @_Znam
// CHECK: call noalias i8* @_Znam
// CHECK: call noalias i8* @_Znam

<|endoftext|>


<commit_before>// @(#)root/meta:$Name:  $:$Id: TGenericClassInfo.cxx,v 1.18 2007/02/01 21:59:28 pcanal Exp $
// Author: Philippe Canal 08/05/2002

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TROOT.h"
#include "TClass.h"
#include "TVirtualStreamerInfo.h"
#include "TStreamer.h"
#include "TVirtualIsAProxy.h"
#include "TVirtualCollectionProxy.h"
#include "TCollectionProxyInfo.h"

namespace ROOT {

   const TInitBehavior *DefineBehavior(void * /*parent_type*/,
                                       void * /*actual_type*/)
   {

      // This function loads the default behavior for the
      // loading of classes.

      static TDefaultInitBehavior theDefault;
      return &theDefault;
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        void *showmembers, VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(showmembers),
        fVersion(1),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof)
   {
      // Constructor.

      Init(pragmabits);
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        void* showmembers,  VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(showmembers),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
   {
      // Constructor with version number.

      Init(pragmabits);
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(0),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)

   {
      // Constructor with version number and no showmembers.

      Init(pragmabits);
   }

   class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc)

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const TInitBehavior  *action,
                                        VoidFuncPtr_t dictionary, Int_t pragmabits)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(typeid(TForNamespace)),
        fImplFileName(0), fImplFileLine(0),
        fIsA(0), fShowMembers(0),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(0),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)

   {
      // Constructor for namespace

      Init(pragmabits);
   }

  /*  TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) :
    fAction(gci.fAction),
    fClass(gci.fClass),
    fClassName(gci.fClassName),
    fDeclFileName(gci.fDeclFileName),
    fDeclFileLine(gci.fDeclFileLine),
    fDictionary(gci.fDictionary),
    fInfo(gci.fInfo),
    fImplFileName(gci.fImplFileName),
    fImplFileLine(gci.fImplFileLine),
    fIsA(gci.fIsA),
    fShowMembers(gci.fShowMembers),
    fVersion(gci.fVersion),
    fNew(gci.fNew),
    fNewArray(gci.fNewArray),
    fDelete(gci.fDelete),
    fDeleteArray(gci.fDeleteArray),
    fDestructor(gci.fDestructor),
    fStreamer(gci.fStreamer),
    fCollectionProxy(gci.fCollectionProxy),
    fSizeof(gci.fSizeof)
   { }

  TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci)
   {
     if(this!=&gci) {
       fAction=gci.fAction;
       fClass=gci.fClass;
       fClassName=gci.fClassName;
       fDeclFileName=gci.fDeclFileName;
       fDeclFileLine=gci.fDeclFileLine;
       fDictionary=gci.fDictionary;
       fInfo=gci.fInfo;
       fImplFileName=gci.fImplFileName;
       fImplFileLine=gci.fImplFileLine;
       fIsA=gci.fIsA;
       fShowMembers=gci.fShowMembers;
       fVersion=gci.fVersion;
       fNew=gci.fNew;
       fNewArray=gci.fNewArray;
       fDelete=gci.fDelete;
       fDeleteArray=gci.fDeleteArray;
       fDestructor=gci.fDestructor;
       fStreamer=gci.fStreamer;
       fCollectionProxy=gci.fCollectionProxy;
       fSizeof=gci.fSizeof;
     } return *this;
   }
  */

   void TGenericClassInfo::Init(Int_t pragmabits)
   {
      // Initilization routine.

      //TVirtualStreamerInfo::Class_Version MUST be the same as TStreamerInfo::Class_Version
      if (fVersion==-2) fVersion = TVirtualStreamerInfo::Class_Version();
      if (!fAction) return;
      GetAction().Register(fClassName,
                           fVersion,
                           fInfo, // typeid(RootClass),
                           fDictionary,
                           pragmabits);
   }

   TGenericClassInfo::~TGenericClassInfo()
   {
      // Destructor.

      delete fCollectionProxyInfo;
      delete fCollectionStreamerInfo;
      if (!fClass) delete fIsA; // fIsA is adopted by the class if any.
      fIsA = 0;
      if (!gROOT) return;
      if (fAction) GetAction().Unregister(GetClassName());
   }

   const TInitBehavior &TGenericClassInfo::GetAction() const
   {
      // Return the creator action.

      return *fAction;
   }

   TClass *TGenericClassInfo::GetClass()
   {
      // Generate and return the TClass object.

      if (!fClass && fAction) {
         fClass = GetAction().CreateClass(GetClassName(),
                                          GetVersion(),
                                          GetInfo(),
                                          GetIsA(),
                                          (ShowMembersFunc_t)GetShowMembers(),
                                          GetDeclFileName(),
                                          GetImplFileName(),
                                          GetDeclFileLine(),
                                          GetImplFileLine());
         fClass->SetNew(fNew);
         fClass->SetNewArray(fNewArray);
         fClass->SetDelete(fDelete);
         fClass->SetDeleteArray(fDeleteArray);
         fClass->SetDestructor(fDestructor);
         fClass->AdoptStreamer(fStreamer); fStreamer = 0;
         // If IsZombie is true, something went wront and we will not be
         // able to properly copy the collection proxy
         if (!fClass->IsZombie()) {
            if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy);
            else if (fCollectionProxyInfo) {
               fClass->SetCollectionProxy(*fCollectionProxyInfo);
            }
         }
         fClass->SetClassSize(fSizeof);
      }
      return fClass;
   }

   const char *TGenericClassInfo::GetClassName() const
   {
      // Return the class name

      return fClassName;
   }

   TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const
   {
      // Return the set of info we have for the CollectionProxy, if any

      return fCollectionProxyInfo;
   }

   TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const
   {
      // Return the set of info we have for the Collection Streamer, if any

      return fCollectionProxyInfo;
   }

   const type_info &TGenericClassInfo::GetInfo() const
   {
      // Return the typeifno value

      return fInfo;
   }

   void *TGenericClassInfo::GetShowMembers() const
   {
      // Return the point of the ShowMembers function
      return fShowMembers;
   }

   void TGenericClassInfo::SetFromTemplate()
   {
      // Import the information from the class template.

      TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
      if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
   }

   Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line)
   {
      // Set the name of the implementation file.

      fImplFileName = file;
      fImplFileLine = line;
      if (fClass) fClass->AddImplFile(file,line);
      return 0;
   }

   Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line)
   {
      // Set the name of the declaration file.

      fDeclFileName = file;
      fDeclFileLine = line;
      if (fClass) fClass->SetDeclFile(file,line);
      return 0;
   }

   Short_t TGenericClassInfo::SetVersion(Short_t version)
   {
      // Set a class version number.

      ROOT::ResetClassVersion(fClass, GetClassName(),version);
      fVersion = version;
      return version;
   }

   void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info)
   {
      // Set the info for the CollectionProxy

      fCollectionProxyInfo = info;
   }

   void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info)
   {
      // Set the info for the Collection Streamer

      fCollectionProxyInfo = info;
   }

   Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer)
   {
      // Set a Streamer object.  The streamer object is now 'owned'
      // by the TGenericClassInfo.

      delete fStreamer; fStreamer = 0;
      if (fClass) {
         fClass->AdoptStreamer(streamer);
      } else {
         fStreamer = streamer;
      }
      return 0;
   }

   Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy)
   {
      // Set the CollectProxy object.  The CollectionProxy object is now 'owned'
      // by the TGenericClassInfo.

      delete fCollectionProxy; fCollectionProxy = 0;
      fCollectionProxy = collProxy;
      if (fClass && fCollectionProxy && !fClass->IsZombie()) {
         fClass->CopyCollectionProxy(*fCollectionProxy);
      }
      return 0;
   }

   Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer)
   {
      // Set a Streamer function.

      delete fStreamer; fStreamer = 0;
      if (fClass) {
         fClass->AdoptStreamer(new TClassStreamer(streamer));
      } else {
         fStreamer = new TClassStreamer(streamer);
      }
      return 0;
   }

   const char *TGenericClassInfo::GetDeclFileName() const
   {
      // Get the name of the declaring header file.

      return fDeclFileName;
   }

   Int_t TGenericClassInfo::GetDeclFileLine() const
   {
      // Get the declaring line number.

      return fDeclFileLine;
   }

   const char *TGenericClassInfo::GetImplFileName()
   {
      // Get the implementation filename.

      if (!fImplFileName) SetFromTemplate();
      return fImplFileName;
   }

   Int_t TGenericClassInfo::GetImplFileLine()
   {
      // Get the ClassImp line number.

      if (!fImplFileLine) SetFromTemplate();
      return fImplFileLine;
   }

   Int_t TGenericClassInfo::GetVersion() const
   {
      // Return the class version number.

      return fVersion;
   }

   TClass *TGenericClassInfo::IsA(const void *obj)
   {
      // Return the actual type of the object.

      return (*GetIsA())(obj);
   }

   TVirtualIsAProxy* TGenericClassInfo::GetIsA() const
   {
      // Return the IsA proxy.

      return fIsA;
   }

   void TGenericClassInfo::SetNew(NewFunc_t newFunc)
   {
      // Install a new wrapper around 'new'.

      fNew = newFunc;
      if (fClass) fClass->SetNew(fNew);
   }

   void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc)
   {
      // Install a new wrapper around 'new []'.

      fNewArray = newArrayFunc;
      if (fClass) fClass->SetNewArray(fNewArray);
   }

   void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc)
   {
      // Install a new wrapper around 'delete'.

      fDelete = deleteFunc;
      if (fClass) fClass->SetDelete(fDelete);
   }

   void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc)
   {
      // Install a new wrapper around 'delete []'.

      fDeleteArray = deleteArrayFunc;
      if (fClass) fClass->SetDeleteArray(fDeleteArray);
   }

   void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc)
   {
      // Install a new wrapper around the destructor.

      fDestructor = destructorFunc;
      if (fClass) fClass->SetDestructor(fDestructor);
   }

   NewFunc_t TGenericClassInfo::GetNew() const
   {
      // Get the wrapper around 'new'.

      return fNew;
   }

   NewArrFunc_t TGenericClassInfo::GetNewArray() const
   {
      // Get the wrapper around 'new []'.

      return fNewArray;
   }

   DelFunc_t TGenericClassInfo::GetDelete() const
   {
      // Get the wrapper around 'delete'.

      return fDelete;
   }

   DelArrFunc_t TGenericClassInfo::GetDeleteArray() const
   {
      // Get the wrapper around 'delete []'.

      return fDeleteArray;
   }

   DesFunc_t TGenericClassInfo::GetDestructor() const
   {
      // Get the wrapper around the destructor.

      return fDestructor;
   }

}
<commit_msg>From Philippe: Fix a problem affecting SEAL, cintex/ROOTClassEnhancer.cxx reported by Pere.<commit_after>// @(#)root/meta:$Name:  $:$Id: TGenericClassInfo.cxx,v 1.19 2007/02/05 18:11:00 brun Exp $
// Author: Philippe Canal 08/05/2002

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TROOT.h"
#include "TClass.h"
#include "TVirtualStreamerInfo.h"
#include "TStreamer.h"
#include "TVirtualIsAProxy.h"
#include "TVirtualCollectionProxy.h"
#include "TCollectionProxyInfo.h"

namespace ROOT {

   const TInitBehavior *DefineBehavior(void * /*parent_type*/,
                                       void * /*actual_type*/)
   {

      // This function loads the default behavior for the
      // loading of classes.

      static TDefaultInitBehavior theDefault;
      return &theDefault;
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        void *showmembers, VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(showmembers),
        fVersion(1),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
   {
      // Constructor.

      Init(pragmabits);
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        void* showmembers,  VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(showmembers),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
   {
      // Constructor with version number.

      Init(pragmabits);
   }

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const type_info &info, const TInitBehavior  *action,
                                        VoidFuncPtr_t dictionary,
                                        TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(info),
        fImplFileName(0), fImplFileLine(0),
        fIsA(isa), fShowMembers(0),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(sizof),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)

   {
      // Constructor with version number and no showmembers.

      Init(pragmabits);
   }

   class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc)

   TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
                                        const char *declFileName, Int_t declFileLine,
                                        const TInitBehavior  *action,
                                        VoidFuncPtr_t dictionary, Int_t pragmabits)
      : fAction(action), fClass(0), fClassName(fullClassname),
        fDeclFileName(declFileName), fDeclFileLine(declFileLine),
        fDictionary(dictionary), fInfo(typeid(TForNamespace)),
        fImplFileName(0), fImplFileLine(0),
        fIsA(0), fShowMembers(0),
        fVersion(version),
        fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
        fCollectionProxy(0), fSizeof(0),
        fCollectionProxyInfo(0), fCollectionStreamerInfo(0)

   {
      // Constructor for namespace

      Init(pragmabits);
   }

  /*  TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) :
    fAction(gci.fAction),
    fClass(gci.fClass),
    fClassName(gci.fClassName),
    fDeclFileName(gci.fDeclFileName),
    fDeclFileLine(gci.fDeclFileLine),
    fDictionary(gci.fDictionary),
    fInfo(gci.fInfo),
    fImplFileName(gci.fImplFileName),
    fImplFileLine(gci.fImplFileLine),
    fIsA(gci.fIsA),
    fShowMembers(gci.fShowMembers),
    fVersion(gci.fVersion),
    fNew(gci.fNew),
    fNewArray(gci.fNewArray),
    fDelete(gci.fDelete),
    fDeleteArray(gci.fDeleteArray),
    fDestructor(gci.fDestructor),
    fStreamer(gci.fStreamer),
    fCollectionProxy(gci.fCollectionProxy),
    fSizeof(gci.fSizeof)
   { }

  TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci)
   {
     if(this!=&gci) {
       fAction=gci.fAction;
       fClass=gci.fClass;
       fClassName=gci.fClassName;
       fDeclFileName=gci.fDeclFileName;
       fDeclFileLine=gci.fDeclFileLine;
       fDictionary=gci.fDictionary;
       fInfo=gci.fInfo;
       fImplFileName=gci.fImplFileName;
       fImplFileLine=gci.fImplFileLine;
       fIsA=gci.fIsA;
       fShowMembers=gci.fShowMembers;
       fVersion=gci.fVersion;
       fNew=gci.fNew;
       fNewArray=gci.fNewArray;
       fDelete=gci.fDelete;
       fDeleteArray=gci.fDeleteArray;
       fDestructor=gci.fDestructor;
       fStreamer=gci.fStreamer;
       fCollectionProxy=gci.fCollectionProxy;
       fSizeof=gci.fSizeof;
     } return *this;
   }
  */

   void TGenericClassInfo::Init(Int_t pragmabits)
   {
      // Initilization routine.

      //TVirtualStreamerInfo::Class_Version MUST be the same as TStreamerInfo::Class_Version
      if (fVersion==-2) fVersion = TVirtualStreamerInfo::Class_Version();
      if (!fAction) return;
      GetAction().Register(fClassName,
                           fVersion,
                           fInfo, // typeid(RootClass),
                           fDictionary,
                           pragmabits);
   }

   TGenericClassInfo::~TGenericClassInfo()
   {
      // Destructor.

      delete fCollectionProxyInfo;
      delete fCollectionStreamerInfo;
      if (!fClass) delete fIsA; // fIsA is adopted by the class if any.
      fIsA = 0;
      if (!gROOT) return;
      if (fAction) GetAction().Unregister(GetClassName());
   }

   const TInitBehavior &TGenericClassInfo::GetAction() const
   {
      // Return the creator action.

      return *fAction;
   }

   TClass *TGenericClassInfo::GetClass()
   {
      // Generate and return the TClass object.

      if (!fClass && fAction) {
         fClass = GetAction().CreateClass(GetClassName(),
                                          GetVersion(),
                                          GetInfo(),
                                          GetIsA(),
                                          (ShowMembersFunc_t)GetShowMembers(),
                                          GetDeclFileName(),
                                          GetImplFileName(),
                                          GetDeclFileLine(),
                                          GetImplFileLine());
         fClass->SetNew(fNew);
         fClass->SetNewArray(fNewArray);
         fClass->SetDelete(fDelete);
         fClass->SetDeleteArray(fDeleteArray);
         fClass->SetDestructor(fDestructor);
         fClass->AdoptStreamer(fStreamer); fStreamer = 0;
         // If IsZombie is true, something went wront and we will not be
         // able to properly copy the collection proxy
         if (!fClass->IsZombie()) {
            if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy);
            else if (fCollectionProxyInfo) {
               fClass->SetCollectionProxy(*fCollectionProxyInfo);
            }
         }
         fClass->SetClassSize(fSizeof);
      }
      return fClass;
   }

   const char *TGenericClassInfo::GetClassName() const
   {
      // Return the class name

      return fClassName;
   }

   TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const
   {
      // Return the set of info we have for the CollectionProxy, if any

      return fCollectionProxyInfo;
   }

   TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const
   {
      // Return the set of info we have for the Collection Streamer, if any

      return fCollectionProxyInfo;
   }

   const type_info &TGenericClassInfo::GetInfo() const
   {
      // Return the typeifno value

      return fInfo;
   }

   void *TGenericClassInfo::GetShowMembers() const
   {
      // Return the point of the ShowMembers function
      return fShowMembers;
   }

   void TGenericClassInfo::SetFromTemplate()
   {
      // Import the information from the class template.

      TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
      if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
   }

   Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line)
   {
      // Set the name of the implementation file.

      fImplFileName = file;
      fImplFileLine = line;
      if (fClass) fClass->AddImplFile(file,line);
      return 0;
   }

   Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line)
   {
      // Set the name of the declaration file.

      fDeclFileName = file;
      fDeclFileLine = line;
      if (fClass) fClass->SetDeclFile(file,line);
      return 0;
   }

   Short_t TGenericClassInfo::SetVersion(Short_t version)
   {
      // Set a class version number.

      ROOT::ResetClassVersion(fClass, GetClassName(),version);
      fVersion = version;
      return version;
   }

   void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info)
   {
      // Set the info for the CollectionProxy

      fCollectionProxyInfo = info;
   }

   void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info)
   {
      // Set the info for the Collection Streamer

      fCollectionProxyInfo = info;
   }

   Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer)
   {
      // Set a Streamer object.  The streamer object is now 'owned'
      // by the TGenericClassInfo.

      delete fStreamer; fStreamer = 0;
      if (fClass) {
         fClass->AdoptStreamer(streamer);
      } else {
         fStreamer = streamer;
      }
      return 0;
   }

   Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy)
   {
      // Set the CollectProxy object.  The CollectionProxy object is now 'owned'
      // by the TGenericClassInfo.

      delete fCollectionProxy; fCollectionProxy = 0;
      fCollectionProxy = collProxy;
      if (fClass && fCollectionProxy && !fClass->IsZombie()) {
         fClass->CopyCollectionProxy(*fCollectionProxy);
      }
      return 0;
   }

   Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer)
   {
      // Set a Streamer function.

      delete fStreamer; fStreamer = 0;
      if (fClass) {
         fClass->AdoptStreamer(new TClassStreamer(streamer));
      } else {
         fStreamer = new TClassStreamer(streamer);
      }
      return 0;
   }

   const char *TGenericClassInfo::GetDeclFileName() const
   {
      // Get the name of the declaring header file.

      return fDeclFileName;
   }

   Int_t TGenericClassInfo::GetDeclFileLine() const
   {
      // Get the declaring line number.

      return fDeclFileLine;
   }

   const char *TGenericClassInfo::GetImplFileName()
   {
      // Get the implementation filename.

      if (!fImplFileName) SetFromTemplate();
      return fImplFileName;
   }

   Int_t TGenericClassInfo::GetImplFileLine()
   {
      // Get the ClassImp line number.

      if (!fImplFileLine) SetFromTemplate();
      return fImplFileLine;
   }

   Int_t TGenericClassInfo::GetVersion() const
   {
      // Return the class version number.

      return fVersion;
   }

   TClass *TGenericClassInfo::IsA(const void *obj)
   {
      // Return the actual type of the object.

      return (*GetIsA())(obj);
   }

   TVirtualIsAProxy* TGenericClassInfo::GetIsA() const
   {
      // Return the IsA proxy.

      return fIsA;
   }

   void TGenericClassInfo::SetNew(NewFunc_t newFunc)
   {
      // Install a new wrapper around 'new'.

      fNew = newFunc;
      if (fClass) fClass->SetNew(fNew);
   }

   void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc)
   {
      // Install a new wrapper around 'new []'.

      fNewArray = newArrayFunc;
      if (fClass) fClass->SetNewArray(fNewArray);
   }

   void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc)
   {
      // Install a new wrapper around 'delete'.

      fDelete = deleteFunc;
      if (fClass) fClass->SetDelete(fDelete);
   }

   void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc)
   {
      // Install a new wrapper around 'delete []'.

      fDeleteArray = deleteArrayFunc;
      if (fClass) fClass->SetDeleteArray(fDeleteArray);
   }

   void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc)
   {
      // Install a new wrapper around the destructor.

      fDestructor = destructorFunc;
      if (fClass) fClass->SetDestructor(fDestructor);
   }

   NewFunc_t TGenericClassInfo::GetNew() const
   {
      // Get the wrapper around 'new'.

      return fNew;
   }

   NewArrFunc_t TGenericClassInfo::GetNewArray() const
   {
      // Get the wrapper around 'new []'.

      return fNewArray;
   }

   DelFunc_t TGenericClassInfo::GetDelete() const
   {
      // Get the wrapper around 'delete'.

      return fDelete;
   }

   DelArrFunc_t TGenericClassInfo::GetDeleteArray() const
   {
      // Get the wrapper around 'delete []'.

      return fDeleteArray;
   }

   DesFunc_t TGenericClassInfo::GetDestructor() const
   {
      // Get the wrapper around the destructor.

      return fDestructor;
   }

}
<|endoftext|>


<commit_before>#include "vector"
#include <iostream>
#include <algorithm>

using namespace stxxl;

struct counter
{
    int value;
    counter(int v) : value(v) { };
    int operator()  ()
    {
        int old_val = value;
        value++;
        return old_val;
    };
};

void my_assert(int value)
{
    assert(value);
};

int main()
{
    stxxl::vector<int64> v(int64(1024) * int64(1024 * 1024));
    stxxl::vector<int64>::iterator it = v.begin();
    stxxl::vector<int64>::const_iterator c_it = v.begin();
    STXXL_MSG(v.end().bid() - c_it.bid() )
    STXXL_MSG( c_it.block_offset() )
    STXXL_MSG( v.end().block_offset() )

    stxxl::random_number rnd;
    int offset = rnd(1024);

    STXXL_MSG("write " << v.size())

    stxxl::ran32State = 0xdeadbeef;

    std::generate(v.begin(), v.end(), stxxl::random_number32());
    int64 i;
    //for(i=0; i < v.size();i++)
    //{
    //	v[i] = stxxl::random_number32()();//i + offset;
    //	assert(v[i] == i + offset);
    //}

    v.flush();

    STXXL_MSG("seq read" << v.size())

    stxxl::ran32State = 0xdeadbeef;

    for (i = 0; i < v.size(); i++)
    {
        assert(v[i] == rand32() );
    }

    /*
       STXXL_MSG("rnd read")
       i = v.size();
       for(; i > 0 ;i--)
       {
            int64 pos = rnd(v.size());
            assert(v[pos] == pos + offset);
       }*/

    return 0;
};
<commit_msg>deleted rnd_test.cpp since the test is already in test_vector.cpp<commit_after><|endoftext|>


<commit_before>#include "fx/SoundList.h"
#include "devices/DeviceManager.h"
#include "devices/IDevice.h"
#include "devices/IDeviceFactory.h"
#include "devices/IHandle.h"
#include "plugin/PluginManager.h"
#include "file/File.h"
#include "Exception.h"
#include "IReader.h"
#include "fx/MutableSound.h"

#include <iostream>
#include <condition_variable>
#include <mutex>

using namespace aud;

int main(int argc, char* argv[])
{
	if (argc == 1){
		std::cerr << "Usage: " << argv[0] << " <filename>" << " <filename>" << " ..." << std::endl;
		return 1;
	}

	PluginManager::loadPlugins("");

	auto factory = DeviceManager::getDefaultDeviceFactory();
	auto device = factory->openDevice();

	std::shared_ptr<SoundList> list(std::make_shared<SoundList>());
	std::shared_ptr<File> file;
	for (int i = 1; i < argc; i++)
	{
		file.reset(new File(argv[i]));
		list->addSound(file);
	}
	list->setRandomMode(true);
	std::shared_ptr<MutableSound> mtSound = std::make_shared<MutableSound>(list);

	std::condition_variable condition;
	std::mutex mutex;
	std::unique_lock<std::mutex> lock(mutex);

	auto release = [](void* condition){reinterpret_cast<std::condition_variable*>(condition)->notify_all(); };

	device->lock();
	auto handle = device->play(mtSound);
	handle->setStopCallback(release, &condition);
	handle->setLoopCount(2);
	device->unlock();

	condition.wait(lock);

	return 0;
}
<commit_msg>Minor change to randsounds demo<commit_after>#include "fx/SoundList.h"
#include "devices/DeviceManager.h"
#include "devices/IDevice.h"
#include "devices/IDeviceFactory.h"
#include "devices/IHandle.h"
#include "plugin/PluginManager.h"
#include "file/File.h"
#include "Exception.h"
#include "IReader.h"
#include "fx/MutableSound.h"

#include <iostream>
#include <condition_variable>
#include <mutex>

using namespace aud;

int main(int argc, char* argv[])
{
	if (argc == 1){
		std::cerr << "Usage: " << argv[0] << " <filename>" << " <filename>" << " ..." << std::endl;
		return 1;
	}

	PluginManager::loadPlugins("");

	auto factory = DeviceManager::getDefaultDeviceFactory();
	auto device = factory->openDevice();

	std::shared_ptr<SoundList> list(std::make_shared<SoundList>());
	std::shared_ptr<File> file;
	for (int i = 1; i < argc; i++)
	{
		file=(std::make_shared<File>(argv[i]));
		list->addSound(file);
	}
	list->setRandomMode(true);
	std::shared_ptr<MutableSound> mtSound = std::make_shared<MutableSound>(list);

	std::condition_variable condition;
	std::mutex mutex;
	std::unique_lock<std::mutex> lock(mutex);

	auto release = [](void* condition){reinterpret_cast<std::condition_variable*>(condition)->notify_all(); };

	device->lock();
	auto handle = device->play(mtSound);
	handle->setStopCallback(release, &condition);
	handle->setLoopCount(2);
	device->unlock();

	condition.wait(lock);

	return 0;
}
<|endoftext|>