<commit_before>/*
 * Clustering.cpp
 *
 *  Created on: 31.10.2012
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "Clustering.h"
#include <algorithm>

namespace NetworKit {

Clustering::Clustering() : NodeMap<cluster>(0, none), name("noname")  {
	this->nextCluster = 0; // first cluster index is 0
	this->upperIdBound = 0; // upper id bound = n is okay only for agglomeratively created clusters
}

Clustering::Clustering(count n) :
		NodeMap<cluster>(n, none), name("noname") {
	// all entries are initialized to none, which means that the nodes are unclustered
	this->nextCluster = 0; // first cluster index is 0
	this->upperIdBound = n; // upper id bound = n is okay only for agglomeratively created clusters
}

Clustering::~Clustering() {
	// TODO Auto-generated destructor stub
}

void Clustering::addToCluster(cluster c, node u) {
	assert((*this)[u] == this->defaultValue);
	(*this)[u] = c;
}

void Clustering::toSingleton(node u) {
	(*this)[u] = this->getNextCluster();
}

void Clustering::moveToCluster(cluster c, node u) {
	assert((*this)[u] != this->defaultValue);
	(*this)[u] = c;
}

void Clustering::mergeClusters(cluster c, cluster d) {
	cluster e = this->getNextCluster();
	for (node u = 0; u < this->n; ++u) {
		if (((*this)[u] == c) || (*this)[u] == d) {
			this->moveToCluster(e, u);
		}
	}
}

bool Clustering::isProper(Graph& G) {
	// test whether each node has been assigned to a cluster
	bool success = true;
	G.forNodes([&](node v) {
		bool contained = this->contains(v);
		if (!contained) {
			ERROR("Clustering does not contain node " << v);
			success = false;
		}
	});
	return success;
}

count Clustering::numberOfClusters() const {

	count nc = this->upperBound();
	std::vector<int> exists(nc, 0); // a boolean vector would not be thread-safe

	this->parallelForEntries([&](node u, cluster C) {
		if (C != none) {
			exists[C] = 1;
		}
	});

	count k = 0; // number of actually existing clusters
	#pragma omp parallel for reduction(+:k)
	for (index i = 0; i < nc; ++i) {
		if (exists[i]) {
			k++;
		}
	}

	return k;
}

cluster Clustering::upperBound() const {
	return this->upperIdBound;
}

cluster Clustering::lowerBound() const {
	return 0;
}

void Clustering::allToSingletons() {
	DEBUG("this->n is " << this->n);
	for (node u = 0; u < this->n; ++u) {
		this->data[u] = u;
	}
	this->nextCluster = this->n;
}

cluster Clustering::addCluster() {
	cluster c = this->nextCluster;
	this->nextCluster += 1;
	return c;
}

bool Clustering::isInRange(node v) {
	return ((0 <= v) && (v < this->numberOfNodes()));
}

bool Clustering::contains(node v) {
	// assert (this->isInRange(v));	// assume that node is in range
	return (this->data[v] != this->defaultValue); // check if node is assigned to cluster, i.e. entry is not null
}

void Clustering::setName(std::string name) {
	this->name = name;
}

std::string Clustering::getName() const {
	return this->name;
}

bool Clustering::isOneClustering(Graph& G) {
	return (this->numberOfClusters() == 1);
}

bool Clustering::isSingletonClustering(Graph& G) {
	return (this->numberOfClusters() == G.numberOfNodes());
}

bool Clustering::inSameCluster(node u, node v) {
	assert(this->contains(u));
	assert(this->contains(v));
	return (this->clusterOf(u) == this->clusterOf(v));
}

bool Clustering::equals(Clustering& other, Graph& G) {
	bool eq = true;
	G.parallelForEdges([&](node u, node v) {
		if (this->inSameCluster(u, v)) {
			if (!other.inSameCluster(u, v)) {
				eq = false;
			}
		}
		else {
			if (other.inSameCluster(u, v)) {
				eq = false;
			}
		}

	});
	return eq;
}

void Clustering::setUpperBound(cluster id) {
	this->upperIdBound = id;
}

void Clustering::compact() {
	std::map<cluster, cluster> compactingMap;
	cluster nextIndex = 0;

	this->forEntries([&](node v, cluster c) {
		if (compactingMap.count(c) == 0) {
			// insert and increase nextIndex
			if (c != none) {
				compactingMap.insert(std::make_pair(c, nextIndex));
				++nextIndex;
			}
			else {
				compactingMap.insert(std::make_pair(none, none));
			}
		}
	});

	this->parallelForEntries([&](node v, cluster c) {
		data[v] = compactingMap[c];
	});

	setUpperBound(nextIndex);
	TRACE("upperBound: " << upperBound());
}

std::vector<count> Clustering::clusterSizes() {
	count numC = this->numberOfClusters();
	std::vector<count> clusterSizes(numC);
	const count n = this->numberOfNodes();
	cluster c = none;

	// does not work with default parallel iterator!
	this->forEntries([&](node v, cluster c) {
		c = data[v];
		++clusterSizes[c];
	});

	return clusterSizes;
}

float Clustering::getImbalance() {
	float avg = ceil((float) this->numberOfNodes() / (float) this->numberOfClusters());
	std::vector<count> clusterSizes = this->clusterSizes();
	float maxClusterSize = (float) *std::max_element(clusterSizes.begin(), clusterSizes.end());
	float imbalance = maxClusterSize / avg;
	return imbalance;
}

void Clustering::append(node u) {
	this->data.push_back(this->defaultValue);
	this->n += 1;
	assert (this->data[u] == this->defaultValue); // assumption: push_back creates entry at index u
}

} /* namespace NetworKit */

<commit_msg>parallel computation of cluster sizes with atomic update, seems to work<commit_after>/*
 * Clustering.cpp
 *
 *  Created on: 31.10.2012
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "Clustering.h"
#include <algorithm>

namespace NetworKit {

Clustering::Clustering() : NodeMap<cluster>(0, none), name("noname")  {
	this->nextCluster = 0; // first cluster index is 0
	this->upperIdBound = 0; // upper id bound = n is okay only for agglomeratively created clusters
}

Clustering::Clustering(count n) :
		NodeMap<cluster>(n, none), name("noname") {
	// all entries are initialized to none, which means that the nodes are unclustered
	this->nextCluster = 0; // first cluster index is 0
	this->upperIdBound = n; // upper id bound = n is okay only for agglomeratively created clusters
}

Clustering::~Clustering() {
	// TODO Auto-generated destructor stub
}

void Clustering::addToCluster(cluster c, node u) {
	assert((*this)[u] == this->defaultValue);
	(*this)[u] = c;
}

void Clustering::toSingleton(node u) {
	(*this)[u] = this->getNextCluster();
}

void Clustering::moveToCluster(cluster c, node u) {
	assert((*this)[u] != this->defaultValue);
	(*this)[u] = c;
}

void Clustering::mergeClusters(cluster c, cluster d) {
	cluster e = this->getNextCluster();
	for (node u = 0; u < this->n; ++u) {
		if (((*this)[u] == c) || (*this)[u] == d) {
			this->moveToCluster(e, u);
		}
	}
}

bool Clustering::isProper(Graph& G) {
	// test whether each node has been assigned to a cluster
	bool success = true;
	G.forNodes([&](node v) {
		bool contained = this->contains(v);
		if (!contained) {
			ERROR("Clustering does not contain node " << v);
			success = false;
		}
	});
	return success;
}

count Clustering::numberOfClusters() const {

	count nc = this->upperBound();
	std::vector<int> exists(nc, 0); // a boolean vector would not be thread-safe

	this->parallelForEntries([&](node u, cluster C) {
		if (C != none) {
			exists[C] = 1;
		}
	});

	count k = 0; // number of actually existing clusters
	#pragma omp parallel for reduction(+:k)
	for (index i = 0; i < nc; ++i) {
		if (exists[i]) {
			k++;
		}
	}

	return k;
}

cluster Clustering::upperBound() const {
	return this->upperIdBound;
}

cluster Clustering::lowerBound() const {
	return 0;
}

void Clustering::allToSingletons() {
	DEBUG("this->n is " << this->n);
	for (node u = 0; u < this->n; ++u) {
		this->data[u] = u;
	}
	this->nextCluster = this->n;
}

cluster Clustering::addCluster() {
	cluster c = this->nextCluster;
	this->nextCluster += 1;
	return c;
}

bool Clustering::isInRange(node v) {
	return ((0 <= v) && (v < this->numberOfNodes()));
}

bool Clustering::contains(node v) {
	// assert (this->isInRange(v));	// assume that node is in range
	return (this->data[v] != this->defaultValue); // check if node is assigned to cluster, i.e. entry is not null
}

void Clustering::setName(std::string name) {
	this->name = name;
}

std::string Clustering::getName() const {
	return this->name;
}

bool Clustering::isOneClustering(Graph& G) {
	return (this->numberOfClusters() == 1);
}

bool Clustering::isSingletonClustering(Graph& G) {
	return (this->numberOfClusters() == G.numberOfNodes());
}

bool Clustering::inSameCluster(node u, node v) {
	assert(this->contains(u));
	assert(this->contains(v));
	return (this->clusterOf(u) == this->clusterOf(v));
}

bool Clustering::equals(Clustering& other, Graph& G) {
	bool eq = true;
	G.parallelForEdges([&](node u, node v) {
		if (this->inSameCluster(u, v)) {
			if (!other.inSameCluster(u, v)) {
				eq = false;
			}
		}
		else {
			if (other.inSameCluster(u, v)) {
				eq = false;
			}
		}

	});
	return eq;
}

void Clustering::setUpperBound(cluster id) {
	this->upperIdBound = id;
}

void Clustering::compact() {
	std::map<cluster, cluster> compactingMap;
	cluster nextIndex = 0;

	this->forEntries([&](node v, cluster c) {
		if (compactingMap.count(c) == 0) {
			// insert and increase nextIndex
			if (c != none) {
				compactingMap.insert(std::make_pair(c, nextIndex));
				++nextIndex;
			}
			else {
				compactingMap.insert(std::make_pair(none, none));
			}
		}
	});

	this->parallelForEntries([&](node v, cluster c) {
		data[v] = compactingMap[c];
	});

	setUpperBound(nextIndex);
	TRACE("upperBound: " << upperBound());
}

std::vector<count> Clustering::clusterSizes() {
	count numC = this->numberOfClusters();
	std::vector<count> clusterSizes(numC);
	const count n = this->numberOfNodes();

// sequential iteration
//	this->forEntries([&](node v, cluster c) {
//		c = data[v];
//		++clusterSizes[c];
//	});

	// does not work with default parallel iterator!
#pragma omp parallel for
	for (index v = 0; v < n; ++v) {
		cluster c = data[v];
#pragma omp atomic
		++clusterSizes[c];
	}

	return clusterSizes;
}

float Clustering::getImbalance() {
	float avg = ceil((float) this->numberOfNodes() / (float) this->numberOfClusters());
	std::vector<count> clusterSizes = this->clusterSizes();
	float maxClusterSize = (float) *std::max_element(clusterSizes.begin(), clusterSizes.end());
	float imbalance = maxClusterSize / avg;
	return imbalance;
}

void Clustering::append(node u) {
	this->data.push_back(this->defaultValue);
	this->n += 1;
	assert (this->data[u] == this->defaultValue); // assumption: push_back creates entry at index u
}

} /* namespace NetworKit */

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "solver/ark/user-supplied.h"

#include <cstdio>
#include <iostream>

#include "solver/ark/ark.h"
#include "solver/ark/mass.h"
#include "solver/ark/rhs.h"

using namespace flint::solver::ark;

using std::cerr;
using std::endl;

int ArkRhs(realtype t, N_Vector y, N_Vector ydot, void *user_data)
{
	try {
		Ark *ark = static_cast<Ark *>(user_data);
		ark->ReadData(t, y);
		if (!ark->rhs()->Evaluate(ark->data()))
			return -1;
		ark->WriteData(1, ydot);
	} catch (...) {
		cerr << "exception occurred in " << __func__ << endl;
		return -1;
	}
	return 0;
}

int ArkDlsDenseMass(long int N, realtype t,
					/*N_Vector y,*/ DlsMat M, void *user_data,
					N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
{
	try {
		Ark *ark = static_cast<Ark *>(user_data);
		ark->ReadTime(t);
		if (!ark->mass()->Evaluate(ark->data()))
			return -1;
		ark->mass()->Write(ark->data(), M);
	} catch (...) {
		cerr << "exception occurred in " << __func__ << endl;
		return -1;
	}
	return 0;
}
<commit_msg>Comment out unused variables<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "solver/ark/user-supplied.h"

#include <cstdio>
#include <iostream>

#include "solver/ark/ark.h"
#include "solver/ark/mass.h"
#include "solver/ark/rhs.h"

using namespace flint::solver::ark;

using std::cerr;
using std::endl;

int ArkRhs(realtype t, N_Vector y, N_Vector ydot, void *user_data)
{
	try {
		Ark *ark = static_cast<Ark *>(user_data);
		ark->ReadData(t, y);
		if (!ark->rhs()->Evaluate(ark->data()))
			return -1;
		ark->WriteData(1, ydot);
	} catch (...) {
		cerr << "exception occurred in " << __func__ << endl;
		return -1;
	}
	return 0;
}

int ArkDlsDenseMass(long int /*N*/, realtype t,
					/*N_Vector y,*/ DlsMat M, void *user_data,
					N_Vector /*tmp1*/, N_Vector /*tmp2*/, N_Vector /*tmp3*/)
{
	try {
		Ark *ark = static_cast<Ark *>(user_data);
		ark->ReadTime(t);
		if (!ark->mass()->Evaluate(ark->data()))
			return -1;
		ark->mass()->Write(ark->data(), M);
	} catch (...) {
		cerr << "exception occurred in " << __func__ << endl;
		return -1;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Clutter-Bullet
 * Copyright (C) 2010 William Hua
 *
 * This program 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.
 *
 * This program 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 more 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 Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <clutter/clutter.h>

#include <btBulletDynamicsCommon.h>

#include "clutter-bullet-private.h"

ClutterBulletMotionState::ClutterBulletMotionState (ClutterActor *a)
: actor (a)
{
}

void
ClutterBulletMotionState::getWorldTransform (btTransform &t) const
{
  CoglMatrix    a;
  ClutterVertex x;
  btVector3     y;

  clutter_actor_get_size (actor, &x.x, &x.y);

  x.x /= 2;
  x.y /= 2;
  x.z  = 0;

  clutter_actor_get_transformation_matrix (actor, &a);

  y.setX (a.xx * x.x + a.xy * x.y + a.xz * x.z + a.xw);
  y.setY (a.yx * x.x + a.yy * x.y + a.yz * x.z + a.yw);
  y.setZ (a.zx * x.x + a.zy * x.y + a.zz * x.z + a.zw);
  y.setW (0);

  t.setOrigin (y);
}

void
ClutterBulletMotionState::setWorldTransform (const btTransform &t)
{
}
<commit_msg>need to double check if btMotionState works<commit_after>/*
 * Clutter-Bullet
 * Copyright (C) 2010 William Hua
 *
 * This program 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.
 *
 * This program 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 more 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 Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <clutter/clutter.h>

#include <btBulletDynamicsCommon.h>

#include "clutter-bullet-private.h"

#define DEG(x) (180 / M_PI * (x))
#define RAD(x) (M_PI / 180 * (x))

ClutterBulletMotionState::ClutterBulletMotionState (ClutterActor *a)
: actor (a)
{
}

void
ClutterBulletMotionState::getWorldTransform (btTransform &t) const
{
  CoglMatrix    a;
  ClutterVertex x;
  gfloat        w;
  gdouble       rx, ry, rz;

  clutter_actor_get_size (actor, &x.x, &x.y);
  clutter_actor_get_transformation_matrix (actor, &a);

  x.x /= 2;
  x.y /= 2;
  x.z  = 0;
  w    = 1;

  cogl_matrix_transform_point (&a, &x.x, &x.y, &x.z, &w);

  g_object_get (actor, "rotation-angle-x", &rx,
                       "rotation-angle-y", &ry,
                       "rotation-angle-z", &rz, NULL);

  t.setOrigin (btVector3 (x.x / w, x.y / w, x.z / w));
  t.getBasis ().setEulerZYX (RAD (rx), RAD (ry), RAD (rz));
}

void
ClutterBulletMotionState::setWorldTransform (const btTransform &t)
{
  CoglMatrix    a;
  ClutterVertex x, dx;
  btScalar      rx0, ry0, rz0;
  gdouble       rx1, ry1, rz1;
  gfloat        w, z;

  t.getBasis ().getEulerZYX (rz0, ry0, rx0);

  rx1 = DEG (rx0);
  ry1 = DEG (ry0);
  rz1 = DEG (rz0);

  g_object_set (actor, "rotation-angle-x", rx1,
                       "rotation-angle-y", ry1,
                       "rotation-angle-z", rz1, NULL);

  clutter_actor_get_size (actor, &x.x, &x.y);
  clutter_actor_get_transformation_matrix (actor, &a);

  x.x /= 2;
  x.y /= 2;
  x.z  = 0;
  w    = 1;

  cogl_matrix_transform_point (&a, &x.x, &x.y, &x.z, &w);

  dx.x = t.getOrigin ().x () - x.x / w;
  dx.y = t.getOrigin ().y () - x.y / w;
  dx.z = t.getOrigin ().z () - x.z / w;

  clutter_actor_move_by (actor, dx.x, dx.y);
  clutter_actor_set_depth (actor, clutter_actor_get_depth (actor) + dx.z);
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <string>
#include "sort_file.h"

using namespace baidu::shuttle;

std::string g_work_dir = "/tmp";
int total = 7500000;

TEST(HdfsTest, Put) {
    Status status;
    SortFileWriter* writer = SortFileWriter::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileWriter::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = writer->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    char key[256] = {'\0'};
    char value[256] = {'\0'};
    for (int i = 1; i <= total; i++) {
        snprintf(key, sizeof(key), "key_%09d", i);
        snprintf(value, sizeof(value), "value_%d", i*2);
        status = writer->Put(key, value);
        EXPECT_EQ(status, kOk);
        if (i % 1000 == 0) {
            printf("%d / %d\n", i , total);
        }
    }
    status = writer->Close();
    EXPECT_EQ(status, kOk);
    printf("done\n");
}

TEST(HdfsTest, Put2) {
    Status status;
    SortFileWriter* writer = SortFileWriter::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileWriter::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = writer->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    char key[256] = {'\0'};
    char value[256] = {'\0'};
    for (int i = 1; i <= 250; i++) {
        snprintf(key, sizeof(key), "key_%09d", i);
        snprintf(value, sizeof(value), "value_%d", i*2);
        status = writer->Put(key, value);
        EXPECT_EQ(status, kOk);
    }
    status = writer->Close();
    EXPECT_EQ(status, kOk);
    printf("done\n");
}

TEST(HdfsTest, Read) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000123", "key_000001123");
    EXPECT_EQ(it->Error(), kOk);
    int n = 123;
    while (!it->Done()) {
        char key[256];
        snprintf(key, sizeof(key), "key_%09d", n);
        EXPECT_EQ(it->Key(), std::string(key));
        it->Next();
        n++;
    }
    EXPECT_EQ(it->Error(), kOk);
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(n, 1123);
    delete it;
}

TEST(HdfsTest, Read2) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("", "");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, total);
    delete it;
}

TEST(HdfsTest, Read3) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "b");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

TEST(HdfsTest, Read4) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000008888", "key_000018888");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 10000);
    delete it;
}

TEST(HdfsTest, Read5) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read6) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read7) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000001", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read8) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000249", "");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 2);
}

TEST(HdfsTest, Read9) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000251", "");
    EXPECT_EQ(it->Error(), kNoMore);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

TEST(HdfsTest, Read10) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000251", "key_000000250");
    EXPECT_EQ(it->Error(), kInvalidArg);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    EXPECT_EQ(it->Error(), kInvalidArg);
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        printf("./sort_test [hdfs work dir]\n");
        return -1;
    }
    g_work_dir = argv[1];
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>add a unit test for duplicated key<commit_after>#include <gtest/gtest.h>
#include <string>
#include "sort_file.h"

using namespace baidu::shuttle;

std::string g_work_dir = "/tmp";
int total = 7500000;

TEST(HdfsTest, Put) {
    Status status;
    SortFileWriter* writer = SortFileWriter::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileWriter::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = writer->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    char key[256] = {'\0'};
    char value[256] = {'\0'};
    for (int i = 1; i <= total; i++) {
        snprintf(key, sizeof(key), "key_%09d", i);
        snprintf(value, sizeof(value), "value_%d", i*2);
        status = writer->Put(key, value);
        EXPECT_EQ(status, kOk);
        if (i % 1000 == 0) {
            printf("%d / %d\n", i , total);
        }
    }
    status = writer->Close();
    EXPECT_EQ(status, kOk);
    printf("done\n");
}

TEST(HdfsTest, Put2) {
    Status status;
    SortFileWriter* writer = SortFileWriter::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileWriter::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = writer->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    char key[256] = {'\0'};
    char value[256] = {'\0'};
    for (int i = 1; i <= 250; i++) {
        snprintf(key, sizeof(key), "key_%09d", i);
        snprintf(value, sizeof(value), "value_%d", i*2);
        status = writer->Put(key, value);
        EXPECT_EQ(status, kOk);
    }
    status = writer->Close();
    EXPECT_EQ(status, kOk);
    printf("done\n");
}

TEST(HdfsTest, PutSameKey) {
    Status status;
    SortFileWriter* writer = SortFileWriter::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileWriter::Param param;
    std::string file_path = g_work_dir + "/put_test_same.data";
    status = writer->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    char value[256] = {'\0'};
    writer->Put("abc", "123");
    for (int i = 1; i <= 100000; i++) {
        snprintf(value, sizeof(value), "value_%d", i*2);
        status = writer->Put("key_999", value);
        EXPECT_EQ(status, kOk);
    }
    status = writer->Close();
    EXPECT_EQ(status, kOk);
    printf("done\n");
}

TEST(HdfsTest, Read) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000123", "key_000001123");
    EXPECT_EQ(it->Error(), kOk);
    int n = 123;
    while (!it->Done()) {
        char key[256];
        snprintf(key, sizeof(key), "key_%09d", n);
        EXPECT_EQ(it->Key(), std::string(key));
        it->Next();
        n++;
    }
    EXPECT_EQ(it->Error(), kOk);
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(n, 1123);
    delete it;
}

TEST(HdfsTest, Read2) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("", "");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, total);
    delete it;
}

TEST(HdfsTest, Read3) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "b");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

TEST(HdfsTest, Read4) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000008888", "key_000018888");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 10000);
    delete it;
}

TEST(HdfsTest, Read5) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read6) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("a", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read7) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000001", "key_000000012");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 11);
    delete it;
}

TEST(HdfsTest, Read8) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000249", "");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 2);
}

TEST(HdfsTest, Read9) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000251", "");
    EXPECT_EQ(it->Error(), kNoMore);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

TEST(HdfsTest, Read10) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test2.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_000000251", "key_000000250");
    EXPECT_EQ(it->Error(), kInvalidArg);
    int count = 0;
    while (!it->Done()) {
        count++;
        printf("%s -> %s\n", it->Key().c_str(), it->Value().c_str());
        it->Next();
    }
    EXPECT_EQ(it->Error(), kInvalidArg);
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 0);
    delete it;
}

TEST(HdfsTest, ReadSameKey) {
    Status status;
    SortFileReader* reader = SortFileReader::Create(kHdfsFile, &status);
    EXPECT_EQ(status, kOk);
    SortFileReader::Param param;
    std::string file_path = g_work_dir + "/put_test_same.data";
    status = reader->Open(file_path, param);
    EXPECT_EQ(status, kOk);
    SortFileReader::Iterator *it = reader->Scan("key_999", "key_999z");
    EXPECT_EQ(it->Error(), kOk);
    int count = 0;
    while (!it->Done()) {
        count++;
        it->Next();
    }
    EXPECT_TRUE(it->Error() == kOk || it->Error() == kNoMore);
    status = reader->Close();
    EXPECT_EQ(status, kOk);
    EXPECT_EQ(count, 100000);
    delete it;
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        printf("./sort_test [hdfs work dir]\n");
        return -1;
    }
    g_work_dir = argv[1];
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/graph-trimmer.h"

#include "src/compiler/graph.h"

namespace v8 {
namespace internal {
namespace compiler {

GraphTrimmer::GraphTrimmer(Zone* zone, Graph* graph)
    : graph_(graph), is_live_(graph, 2), live_(zone) {
  live_.reserve(graph->NodeCount());
}

GraphTrimmer::~GraphTrimmer() {}

void GraphTrimmer::TrimGraph() {
  // Mark end node as live.
  MarkAsLive(graph()->end());
  // Compute transitive closure of live nodes.
  for (size_t i = 0; i < live_.size(); ++i) {
    for (Node* const input : live_[i]->inputs()) {
      DCHECK_EQ(IsLive(input),
                std::find(live_.begin(), live_.end(), input) != live_.end());
      MarkAsLive(input);
    }
  }
  // Remove dead->live edges.
  for (Node* const live : live_) {
    DCHECK(IsLive(live));
    for (Edge edge : live->use_edges()) {
      Node* const user = edge.from();
      DCHECK_EQ(IsLive(user),
                std::find(live_.begin(), live_.end(), user) != live_.end());
      if (!IsLive(user)) {
        if (FLAG_trace_turbo_reduction) {
          OFStream os(stdout);
          os << "DeadLink: " << *user << "(" << edge.index() << ") -> " << *live
             << std::endl;
        }
        edge.UpdateTo(nullptr);
      }
    }
  }
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8
<commit_msg>[turbofan] Deslowify the GraphTrimmer in debug mode.<commit_after>// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/graph-trimmer.h"

#include "src/compiler/graph.h"

namespace v8 {
namespace internal {
namespace compiler {

GraphTrimmer::GraphTrimmer(Zone* zone, Graph* graph)
    : graph_(graph), is_live_(graph, 2), live_(zone) {
  live_.reserve(graph->NodeCount());
}

GraphTrimmer::~GraphTrimmer() {}

void GraphTrimmer::TrimGraph() {
  // Mark end node as live.
  MarkAsLive(graph()->end());
  // Compute transitive closure of live nodes.
  for (size_t i = 0; i < live_.size(); ++i) {
    for (Node* const input : live_[i]->inputs()) MarkAsLive(input);
  }
  // Remove dead->live edges.
  for (Node* const live : live_) {
    DCHECK(IsLive(live));
    for (Edge edge : live->use_edges()) {
      Node* const user = edge.from();
      if (!IsLive(user)) {
        if (FLAG_trace_turbo_reduction) {
          OFStream os(stdout);
          os << "DeadLink: " << *user << "(" << edge.index() << ") -> " << *live
             << std::endl;
        }
        edge.UpdateTo(nullptr);
      }
    }
  }
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8
<|endoftext|>


<commit_before>/*
    Copyright 2011 Joe Hermaszewski. 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.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#pragma once

namespace JoeLang
{
namespace Compiler
{

/**
  * \def CHECK_PARSER
  * Checks if the parser is good to continue, if it isn't return from the
  * current function.
  *
  * To be used after calling any Parser::Expect* function and continuing on a
  * false result.
  */
#define CHECK_PARSER \
    if( !parser.Good() ) return false; \
    else (void)0

#define CHECK_CODE_GENERATOR \
    if( !code_generator.Good() ) return nullptr; \
    else (void)0

/**
  * \defgroup Tokens
  * Tokens must implement a static member function Parse taking a reference to a
  * Parser and a reference to a pointer to the token type. Parse should return
  * true if the token was parsed successfully, otherwise false. It should also
  * return a pointer to the successfully parsed token or nullptr in token
  */

/**
  * \class Token
  * \ingroup Tokens
  * \brief Abstract class for any token in the CST
  */
class Token
{
public:
    enum class TokenTy
    {
        TranslationUnit,

        InitDeclarator,
        Declarator,
        ArraySpecifier,
        Initializer,

        PassDefinition,
        PassDeclarationOrIdentifier,

        TypeSpecifier,
        TypeQualifier,
        StorageClassSpecifier,
        DeclarationSpecifier_Start = TypeSpecifier,
        DeclarationSpecifier_End = StorageClassSpecifier,

        EmptyDeclaration,
        PassDeclaration,
        TechniqueDeclaration,
        VariableDeclarationList,
        FunctionDefinition,
        Declaration_Start = EmptyDeclaration,
        Declaration_End = FunctionDefinition,

        AssignmentOperator,

        SubscriptOperator,
        ArgumentListOperator,
        MemberAccessOperator,
        IncrementOrDecrementOperator,
        PostfixOperator_Start = SubscriptOperator,
        PostfixOperator_End = IncrementOrDecrementOperator,

        StateAssignmentStatement,

        AssignmentExpression,
        ConditionalExpression,

        LogicalOrExpression,
        LogicalAndExpression,
        InclusiveOrExpression,
        ExclusiveOrExpression,
        AndExpression,
        EqualityExpression,
        RelationalExpression,
        ShiftExpression,
        AdditiveExpression,
        MultiplicativeExpression,
        BinaryOperatorExpression_Start = LogicalOrExpression,
        BinaryOperatorExpression_End = MultiplicativeExpression,

        CastExpression,
        UnaryExpression,
        PostfixExpression,
        TypeConstructorExpression,
        IdentifierExpression,

        IntegerLiteralExpression,
        FloatingLiteralExpression,
        BooleanLiteralExpression,
        StringLiteralExpression,
        CharacterLiteralExpression,
        LiteralExpression_Start = IntegerLiteralExpression,
        LiteralExpression_End = CharacterLiteralExpression,

        Expression_Start = AssignmentExpression,
        Expression_End = CharacterLiteralExpression,
    };

    explicit
    Token( TokenTy sub_class_id );
    virtual
    ~Token();

    virtual
    void Print( int depth ) const = 0;

    /** Used for casting **/
    TokenTy GetSubClassID() const;
    /** Used for casting **/
    static
    bool classof( const Token* t );
private:
    const TokenTy m_SubClassID;
};

} // namespace Compiler
} // namespace JoeLang

<commit_msg>[+] documentation<commit_after>/*
    Copyright 2011 Joe Hermaszewski. 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.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#pragma once

namespace JoeLang
{
namespace Compiler
{

/**
  * \def CHECK_PARSER
  * Checks if the parser is good to continue, if it isn't return from the
  * current function.
  *
  * To be used after calling any Parser::Expect* function and continuing on a
  * false result.
  */
#define CHECK_PARSER \
    if( !parser.Good() ) return false; \
    else (void)0

#define CHECK_CODE_GENERATOR \
    if( !code_generator.Good() ) return nullptr; \
    else (void)0

/**
  * \defgroup Tokens
  * Tokens must implement a static member function Parse taking a reference to a
  * Parser and a reference to a pointer to the token type. Parse should return
  * true if the token was parsed successfully, otherwise false. It should also
  * return a pointer to the successfully parsed token or nullptr in token
  *
  * Most Tokens have three states: Parsed, the token has been generated from
  * parsing the stream from the lexer; Analyzed, the token has undergone
  * semantic analysis (this should only happen once); CodeGened, the token has
  * generated some instructions to llvm (this should only happen once).
  */

/**
  * \class Token
  * \ingroup Tokens
  * \brief Abstract class for any token in the CST
  */
class Token
{
public:
    enum class TokenTy
    {
        TranslationUnit,

        InitDeclarator,
        Declarator,
        ArraySpecifier,
        Initializer,

        PassDefinition,
        PassDeclarationOrIdentifier,

        TypeSpecifier,
        TypeQualifier,
        StorageClassSpecifier,
        DeclarationSpecifier_Start = TypeSpecifier,
        DeclarationSpecifier_End = StorageClassSpecifier,

        EmptyDeclaration,
        PassDeclaration,
        TechniqueDeclaration,
        VariableDeclarationList,
        FunctionDefinition,
        Declaration_Start = EmptyDeclaration,
        Declaration_End = FunctionDefinition,

        AssignmentOperator,

        SubscriptOperator,
        ArgumentListOperator,
        MemberAccessOperator,
        IncrementOrDecrementOperator,
        PostfixOperator_Start = SubscriptOperator,
        PostfixOperator_End = IncrementOrDecrementOperator,

        StateAssignmentStatement,

        AssignmentExpression,
        ConditionalExpression,

        LogicalOrExpression,
        LogicalAndExpression,
        InclusiveOrExpression,
        ExclusiveOrExpression,
        AndExpression,
        EqualityExpression,
        RelationalExpression,
        ShiftExpression,
        AdditiveExpression,
        MultiplicativeExpression,
        BinaryOperatorExpression_Start = LogicalOrExpression,
        BinaryOperatorExpression_End = MultiplicativeExpression,

        CastExpression,
        UnaryExpression,
        PostfixExpression,
        TypeConstructorExpression,
        IdentifierExpression,

        IntegerLiteralExpression,
        FloatingLiteralExpression,
        BooleanLiteralExpression,
        StringLiteralExpression,
        CharacterLiteralExpression,
        LiteralExpression_Start = IntegerLiteralExpression,
        LiteralExpression_End = CharacterLiteralExpression,

        Expression_Start = AssignmentExpression,
        Expression_End = CharacterLiteralExpression,
    };

    explicit
    Token( TokenTy sub_class_id );
    virtual
    ~Token();

    virtual
    void Print( int depth ) const = 0;

    /** Used for casting **/
    TokenTy GetSubClassID() const;
    /** Used for casting **/
    static
    bool classof( const Token* t );
private:
    const TokenTy m_SubClassID;
};

} // namespace Compiler
} // namespace JoeLang

<|endoftext|>


<commit_before>/************************************************************************************
 * Copyright (C) 2020, Copyright Holders of the ALICE Collaboration                 *
 * All rights reserved.                                                             *
 *                                                                                *
 * 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.       *
 *     * Neither the name of the <organization> nor the                             *
 *       names of its contributors may be used to endorse or promote products       *
 *       derived from this software without specific prior written permission.      *
 *                                                                                *
 * 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 ALICE COLLABORATION 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 <THistManager.h>
#include <TLinearBinning.h>
#include <TCustomBinning.h>
#include <TString.h>
#include <TVector2.h>

#include "AliAnalysisTaskEmcalJetSpectrumSDPart.h"
#include "AliAnalysisManager.h"
#include "AliLog.h"

ClassImp(PWGJE::EMCALJetTasks::AliAnalysisTaskEmcalJetSpectrumSDPart)

using namespace PWGJE::EMCALJetTasks;

AliAnalysisTaskEmcalJetSpectrumSDPart::AliAnalysisTaskEmcalJetSpectrumSDPart():
    AliAnalysisTaskEmcalJet(),
    AliAnalysisEmcalSoftdropHelperImpl(),
    fHistos(nullptr),
    fBeta(0),
    fZcut(0.1),
    fUseChargedConstituents(true),
    fUseNeutralConstituents(true)
{
}

AliAnalysisTaskEmcalJetSpectrumSDPart::AliAnalysisTaskEmcalJetSpectrumSDPart(const char *name):
    AliAnalysisTaskEmcalJet(name, true),
    AliAnalysisEmcalSoftdropHelperImpl(),
    fHistos(nullptr),
    fBeta(0),
    fZcut(0.1),
    fUseChargedConstituents(true),
    fUseNeutralConstituents(true)
{
    SetMakeGeneralHistograms(true);
}

AliAnalysisTaskEmcalJetSpectrumSDPart::~AliAnalysisTaskEmcalJetSpectrumSDPart()
{
}

void AliAnalysisTaskEmcalJetSpectrumSDPart::UserCreateOutputObjects()
{
    AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
    fHistos = new THistManager(Form("Histos%s", GetName()));

    // Event property
    fHistos->CreateTH1("fNevents", "Number of events", 1, 0.5, 1.5);

    // Jet spectrum and QA
    fHistos->CreateTH1("hJetPt", "Jet Pt spectrum", 1000, 0., 1000.);
    fHistos->CreateTH2("hJetEtaPhi", "Jet #eta and #phi", 100, -1., 1, 100, 0., TMath::TwoPi());
    fHistos->CreateTH2("hJetNEFPt", "Neutral energy fraction vs. pt", 500, 0., 500., 100, 0., 1.);
    fHistos->CreateTH2("hJetNconstPt", "Number of jet constituents vs. pt", 500, 0., 500., 100, 0., 100.);
    fHistos->CreateTH2("hPtLeading", "Pt of the leading constituent vs. jet pt", 500, 0., 500., 500, 0., 500.);
    fHistos->CreateTH2("hDrLeading", "DeltaR of the leading constituent vs. jet pt", 500, 0., 500., 100, 0., 1.);
    fHistos->CreateTH2("hFailedSD", "Jets failing SoftDrop", 300, 0., 300., 101, -0.5, 100.5);

    // SoftDrop
    double R = double(int(GetJetContainer("partjets")->GetJetRadius() * 1000.))/1000.;  // Save cast from float to double truncating after 3rd decimal digit
    TLinearBinning ptbinning(500, 0., 500.),
                   nsdbinning(22, -1.5, 20.5),
                   thetagbinning(11, -0.5, 1.);
    std::unique_ptr<TBinning> zgbinning(GetZgBinning(fZcut)),
                              rgbinning(GetRgBinning(R));
    fHistos->CreateTH2("hSDZg", "Zg vs. pt", *zgbinning, ptbinning);
    fHistos->CreateTH2("hSDRg", "Rg vs. pt", *rgbinning, ptbinning);
    fHistos->CreateTH2("fSDNsd", "Nsd vs. pt", nsdbinning, ptbinning);
    fHistos->CreateTH2("fSDThetag", "Thetag vs. pt", thetagbinning, ptbinning);

    for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h);
    PostData(1, fOutput);
}

bool AliAnalysisTaskEmcalJetSpectrumSDPart::Run()
{
    fHistos->FillTH1("fNevents", 1.);
    auto jets = GetJetContainer("partjets");

    if(!jets) {
        AliErrorStream() << GetName() << ": Part. level jet container not found" << std::endl;
        return false;
    }

    Double_t vertex[3] = {0,0,0};
    AliAnalysisEmcalSoftdropHelperImpl::SoftdropParams sdsettings;
    sdsettings.fBeta = fBeta;
    sdsettings.fZcut = fZcut;
    sdsettings.fReclusterizer = AliAnalysisEmcalSoftdropHelperImpl::EReclusterizer_t::kCAAlgo;
    sdsettings.fUseChargedConstituents = fUseChargedConstituents;
    sdsettings.fUseNeutralConstituents = fUseNeutralConstituents;

    for(auto j : jets->accepted()) {
        fHistos->FillTH1("hJetPt", j->Pt());
        fHistos->FillTH2("hJetEtaPhi", j->Eta(), TVector2::Phi_0_2pi(j->Phi()));
        fHistos->FillTH2("hJetNEFPt", j->Pt(), j->NEF());
        fHistos->FillTH2("hJetNconstPt", j->Pt(), j->N());

        auto leading = j->GetLeadingTrack(jets->GetParticleContainer()->GetArray());
        if(leading) {
            fHistos->FillTH2("hPtLeading", j->Pt(), leading->Pt());
            TVector3 jetvec(j->Px(), j->Py(), j->Px()),
                     leadingvec(leading->Px(), leading->Py(), leading->Pz());
            fHistos->FillTH2("hDrLeading", j->Pt(), jetvec.DeltaR(leadingvec));
        }

        // SoftDrop
        try {
            auto sdparams = this->MakeSoftdrop(*j, jets->GetJetRadius(), true, sdsettings, AliVCluster::VCluUserDefEnergy_t::kNonLinCorr, vertex);
            auto splittings = this->IterativeDecluster(*j, jets->GetJetRadius(), true, sdsettings, AliVCluster::VCluUserDefEnergy_t::kNonLinCorr, vertex);

            fHistos->FillTH2("hSDZg", sdparams.fZg, j->Pt());
            fHistos->FillTH2("hSDRg", sdparams.fZg < sdsettings.fZcut ? -0.02 : sdparams.fRg, j->Pt());
            fHistos->FillTH2("fSDNsd", sdparams.fZg < sdsettings.fZcut ? -1. : splittings.size(), j->Pt());
            fHistos->FillTH2("fSDThetag", sdparams.fZg < sdsettings.fZcut ? -0.2 : sdparams.fRg/jets->GetJetRadius(), j->Pt());
        } catch(...) {
            fHistos->FillTH2("hFailedSD", j->Pt(), j->N());
        }
    }

    return true;
}

AliAnalysisTaskEmcalJetSpectrumSDPart *AliAnalysisTaskEmcalJetSpectrumSDPart::AddTaskEmcalJetSpectrumSDPart(AliJetContainer::EJetType_t jettype, double R, const char *nameparticles) {
    auto mgr = AliAnalysisManager::GetAnalysisManager();
    if(!mgr) {
        AliErrorGeneralStream("AliAnalysisTaskEmcalJetSpectrumSDPart::AddTaskEmcalJetSpectrumSDPart") << "No analysis manager available" << std::endl;
        return nullptr;
    }

    TString rstring = Form("R%02d", int(R * 10.)),
            jtstring = "";

    switch (jettype) {
        case AliJetContainer::kChargedJet: jtstring = "ChargedJet"; break;
        case AliJetContainer::kFullJet:    jtstring = "FullJet"; break;
        case AliJetContainer::kNeutralJet: jtstring = "NeutralJet"; break;
        case AliJetContainer::kUndefinedJetType: break;
    };

    auto task = new AliAnalysisTaskEmcalJetSpectrumSDPart(Form("PartLevelJetTask%s%s", jtstring.Data(), rstring.Data()));
    mgr->AddTask(task);

    // Adding particle and jet container
    auto partcont = task->AddMCParticleContainer(nameparticles);
    partcont->SetMinPt(0.);
    auto jetcont = task->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, R, AliJetContainer::kTPCfid, partcont, nullptr);
    jetcont->SetName("partjets");
    jetcont->SetMaxTrackPt(1000);
    jetcont->SetMinPt(0);
    jetcont->SetMaxPt(1000.);

    // Link input and output
    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("PartLevelJetResults%s%s", jtstring.Data(), rstring.Data()), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName()));

    return task;
}<commit_msg>Align Thetag binning with what is used for data<commit_after>/************************************************************************************
 * Copyright (C) 2020, Copyright Holders of the ALICE Collaboration                 *
 * All rights reserved.                                                             *
 *                                                                                *
 * 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.       *
 *     * Neither the name of the <organization> nor the                             *
 *       names of its contributors may be used to endorse or promote products       *
 *       derived from this software without specific prior written permission.      *
 *                                                                                *
 * 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 ALICE COLLABORATION 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 <THistManager.h>
#include <TLinearBinning.h>
#include <TCustomBinning.h>
#include <TString.h>
#include <TVector2.h>

#include "AliAnalysisTaskEmcalJetSpectrumSDPart.h"
#include "AliAnalysisManager.h"
#include "AliLog.h"

ClassImp(PWGJE::EMCALJetTasks::AliAnalysisTaskEmcalJetSpectrumSDPart)

using namespace PWGJE::EMCALJetTasks;

AliAnalysisTaskEmcalJetSpectrumSDPart::AliAnalysisTaskEmcalJetSpectrumSDPart():
    AliAnalysisTaskEmcalJet(),
    AliAnalysisEmcalSoftdropHelperImpl(),
    fHistos(nullptr),
    fBeta(0),
    fZcut(0.1),
    fUseChargedConstituents(true),
    fUseNeutralConstituents(true)
{
}

AliAnalysisTaskEmcalJetSpectrumSDPart::AliAnalysisTaskEmcalJetSpectrumSDPart(const char *name):
    AliAnalysisTaskEmcalJet(name, true),
    AliAnalysisEmcalSoftdropHelperImpl(),
    fHistos(nullptr),
    fBeta(0),
    fZcut(0.1),
    fUseChargedConstituents(true),
    fUseNeutralConstituents(true)
{
    SetMakeGeneralHistograms(true);
}

AliAnalysisTaskEmcalJetSpectrumSDPart::~AliAnalysisTaskEmcalJetSpectrumSDPart()
{
}

void AliAnalysisTaskEmcalJetSpectrumSDPart::UserCreateOutputObjects()
{
    AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
    fHistos = new THistManager(Form("Histos%s", GetName()));

    // Event property
    fHistos->CreateTH1("fNevents", "Number of events", 1, 0.5, 1.5);

    // Jet spectrum and QA
    fHistos->CreateTH1("hJetPt", "Jet Pt spectrum", 1000, 0., 1000.);
    fHistos->CreateTH2("hJetEtaPhi", "Jet #eta and #phi", 100, -1., 1, 100, 0., TMath::TwoPi());
    fHistos->CreateTH2("hJetNEFPt", "Neutral energy fraction vs. pt", 500, 0., 500., 100, 0., 1.);
    fHistos->CreateTH2("hJetNconstPt", "Number of jet constituents vs. pt", 500, 0., 500., 100, 0., 100.);
    fHistos->CreateTH2("hPtLeading", "Pt of the leading constituent vs. jet pt", 500, 0., 500., 500, 0., 500.);
    fHistos->CreateTH2("hDrLeading", "DeltaR of the leading constituent vs. jet pt", 500, 0., 500., 100, 0., 1.);
    fHistos->CreateTH2("hFailedSD", "Jets failing SoftDrop", 300, 0., 300., 101, -0.5, 100.5);

    // SoftDrop
    double R = double(int(GetJetContainer("partjets")->GetJetRadius() * 1000.))/1000.;  // Save cast from float to double truncating after 3rd decimal digit
    TLinearBinning ptbinning(500, 0., 500.),
                   nsdbinning(22, -1.5, 20.5),
                   thetagbinning(11, -0.1, 1.);
    std::unique_ptr<TBinning> zgbinning(GetZgBinning(fZcut)),
                              rgbinning(GetRgBinning(R));
    fHistos->CreateTH2("hSDZg", "Zg vs. pt", *zgbinning, ptbinning);
    fHistos->CreateTH2("hSDRg", "Rg vs. pt", *rgbinning, ptbinning);
    fHistos->CreateTH2("fSDNsd", "Nsd vs. pt", nsdbinning, ptbinning);
    fHistos->CreateTH2("fSDThetag", "Thetag vs. pt", thetagbinning, ptbinning);

    for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h);
    PostData(1, fOutput);
}

bool AliAnalysisTaskEmcalJetSpectrumSDPart::Run()
{
    fHistos->FillTH1("fNevents", 1.);
    auto jets = GetJetContainer("partjets");

    if(!jets) {
        AliErrorStream() << GetName() << ": Part. level jet container not found" << std::endl;
        return false;
    }

    Double_t vertex[3] = {0,0,0};
    AliAnalysisEmcalSoftdropHelperImpl::SoftdropParams sdsettings;
    sdsettings.fBeta = fBeta;
    sdsettings.fZcut = fZcut;
    sdsettings.fReclusterizer = AliAnalysisEmcalSoftdropHelperImpl::EReclusterizer_t::kCAAlgo;
    sdsettings.fUseChargedConstituents = fUseChargedConstituents;
    sdsettings.fUseNeutralConstituents = fUseNeutralConstituents;

    for(auto j : jets->accepted()) {
        fHistos->FillTH1("hJetPt", j->Pt());
        fHistos->FillTH2("hJetEtaPhi", j->Eta(), TVector2::Phi_0_2pi(j->Phi()));
        fHistos->FillTH2("hJetNEFPt", j->Pt(), j->NEF());
        fHistos->FillTH2("hJetNconstPt", j->Pt(), j->N());

        auto leading = j->GetLeadingTrack(jets->GetParticleContainer()->GetArray());
        if(leading) {
            fHistos->FillTH2("hPtLeading", j->Pt(), leading->Pt());
            TVector3 jetvec(j->Px(), j->Py(), j->Px()),
                     leadingvec(leading->Px(), leading->Py(), leading->Pz());
            fHistos->FillTH2("hDrLeading", j->Pt(), jetvec.DeltaR(leadingvec));
        }

        // SoftDrop
        try {
            auto sdparams = this->MakeSoftdrop(*j, jets->GetJetRadius(), true, sdsettings, AliVCluster::VCluUserDefEnergy_t::kNonLinCorr, vertex);
            auto splittings = this->IterativeDecluster(*j, jets->GetJetRadius(), true, sdsettings, AliVCluster::VCluUserDefEnergy_t::kNonLinCorr, vertex);

            fHistos->FillTH2("hSDZg", sdparams.fZg, j->Pt());
            fHistos->FillTH2("hSDRg", sdparams.fZg < sdsettings.fZcut ? -0.02 : sdparams.fRg, j->Pt());
            fHistos->FillTH2("fSDNsd", sdparams.fZg < sdsettings.fZcut ? -1. : splittings.size(), j->Pt());
            fHistos->FillTH2("fSDThetag", sdparams.fZg < sdsettings.fZcut ? -0.05 : sdparams.fRg/jets->GetJetRadius(), j->Pt());
        } catch(...) {
            fHistos->FillTH2("hFailedSD", j->Pt(), j->N());
        }
    }

    return true;
}

AliAnalysisTaskEmcalJetSpectrumSDPart *AliAnalysisTaskEmcalJetSpectrumSDPart::AddTaskEmcalJetSpectrumSDPart(AliJetContainer::EJetType_t jettype, double R, const char *nameparticles) {
    auto mgr = AliAnalysisManager::GetAnalysisManager();
    if(!mgr) {
        AliErrorGeneralStream("AliAnalysisTaskEmcalJetSpectrumSDPart::AddTaskEmcalJetSpectrumSDPart") << "No analysis manager available" << std::endl;
        return nullptr;
    }

    TString rstring = Form("R%02d", int(R * 10.)),
            jtstring = "";

    switch (jettype) {
        case AliJetContainer::kChargedJet: jtstring = "ChargedJet"; break;
        case AliJetContainer::kFullJet:    jtstring = "FullJet"; break;
        case AliJetContainer::kNeutralJet: jtstring = "NeutralJet"; break;
        case AliJetContainer::kUndefinedJetType: break;
    };

    auto task = new AliAnalysisTaskEmcalJetSpectrumSDPart(Form("PartLevelJetTask%s%s", jtstring.Data(), rstring.Data()));
    mgr->AddTask(task);

    // Adding particle and jet container
    auto partcont = task->AddMCParticleContainer(nameparticles);
    partcont->SetMinPt(0.);
    auto jetcont = task->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, R, AliJetContainer::kTPCfid, partcont, nullptr);
    jetcont->SetName("partjets");
    jetcont->SetMaxTrackPt(1000);
    jetcont->SetMinPt(0);
    jetcont->SetMaxPt(1000.);

    // Link input and output
    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("PartLevelJetResults%s%s", jtstring.Data(), rstring.Data()), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName()));

    return task;
}<|endoftext|>


<commit_before>#ifndef DBG_H
#define DBG_H

#include <vector>
#include <iostream>
#include <iterator>

namespace utils
{

struct Dbg
{
    Dbg()
        : m_flags(std::cout.flags())
    {
        std::cout << "[ ";
    }

    ~Dbg()
    {
        std::cout << "]\n" << std::flush;
        std::cout.flags(m_flags);
    }

    template<typename T>
    Dbg& operator<< (T d)
    {
        std::cout << d << " ";
        return *this;
    }

    template <typename T>
    Dbg& operator<< (std::vector<T> v)
    {
        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
        return *this;
    }

    Dbg& operator<< (char* d)
    {
        return (*this) << (void*)d;
    }

    Dbg& operator<< (const char *&d)
    {
        return (*this) << (void*)d;
    }
private:
    std::ios::fmtflags m_flags;
};

class Debugging
{
public:
    static Debugging& get()
    {
        static Debugging d;
        return d;
    }

    void set(bool enabled)
    {
        m_enabled = enabled;
    }

    bool enabled()
    {
        return m_enabled;
    }

private:
    Debugging()
        : m_enabled(false)
    {
    }

    bool m_enabled;
};

} // ns utils

#ifdef DEBUG
#define D(x) if (utils::Debugging::get().enabled()) utils::Dbg()
#else
    #define D(x) if (false) utils::Dbg()
#endif

#endif // DBG_H
<commit_msg>Dbg improvements<commit_after>#ifndef DBG_H
#define DBG_H

#include <vector>
#include <set>
#include <iostream>
#include <iterator>
#include <typeinfo>

namespace utils
{

struct Dbg
{
    Dbg()
        : m_flags(std::cout.flags())
    {
        std::cout << "[ ";
    }

    ~Dbg()
    {
        std::cout << "]\n" << std::flush;
        std::cout.flags(m_flags);
    }

    template<typename T>
    Dbg& operator<< (T d)
    {
        std::cout << d << " ";
        return *this;
    }

    template <typename T>
    Dbg& operator<< (std::vector<T> v)
    {
        std::cout << " vector<" << typeid(T).name() << ">(";
        std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ", "));
        std::cout << ")";
        return *this;
    }

    Dbg& operator<< (std::vector<char> v)
    {
        std::cout << " vector<char>(";
        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ", "));
        std::cout << ")";
        return *this;
    }

    template <typename T>
    Dbg& operator<< (std::set<T> v)
    {
        std::cout << " set<" << typeid(T).name() << ">(";
        std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ", "));
        std::cout << ")";
        return *this;
    }

    Dbg& operator<< (char* d)
    {
        return (*this) << (void*)d;
    }

    Dbg& operator<< (const char *&d)
    {
        return (*this) << (void*)d;
    }
private:
    std::ios::fmtflags m_flags;
};

class Debugging
{
public:
    static Debugging& get()
    {
        static Debugging d;
        return d;
    }

    void set(bool enabled)
    {
        m_enabled = enabled;
    }

    bool enabled()
    {
        return m_enabled;
    }

private:
    Debugging()
        : m_enabled(false)
    {
    }

    bool m_enabled;
};

} // ns utils

#ifdef DEBUG
#define D(x) if (utils::Debugging::get().enabled()) utils::Dbg()
#else
    #define D(x) if (false) utils::Dbg()
#endif

#endif // DBG_H
<|endoftext|>


<commit_before>#include "compsys/MetaComponent.hpp"
#include "compsys/Component.hpp"
#include "ComponentRegistry.hpp"
#include <unordered_map>
#include "LuaUtils.hpp"
#include "svc/ServiceLocator.hpp"
#include "svc/LuaVm.hpp"
#include "Logfile.hpp"
#include <boost/format.hpp>

static char const libname[] = "ComponentSystem";
#include "luaexport/ExportThis.hpp"
#include <luabind/class_info.hpp>
#include <luabind/raw_policy.hpp>
#include <luabind/adopt_policy.hpp>
#include <luabind/operator.hpp>
#include <ssig.hpp>
#include "Entity.hpp"

namespace {

static void registerMetaComponent(lua_State* L, std::string const& name)
{
    static std::vector<std::unique_ptr<LuaMetaComponent>> components;
    components.push_back(std::unique_ptr<LuaMetaComponent>(new LuaMetaComponent(L, name)));
}

static std::string const& Component_componentName(Component const& c)
{
    return c.metaComponent().name();
}

luabind::object Component_parent(Component const& c, lua_State* L)
{
    if (c.parent())
        return luabind::object(L, c.parent()->ref());
    else
        return luabind::object();
}

static std::ostream& operator<< (std::ostream& os, Component const& c)
{
    return os << "jd.Component (" << c.metaComponent().name() << " @" << &c << ')';
}

static ConnectionBase* connectEvent(
    lua_State* L,
    Component& sender,
    std::string const& eventname,
    luabind::object const& receiver)
{
    receiver.push(L);
    ConnectionBase* result = sender.metaComponent().connectEvent(
        L, &sender, eventname);
    lua_pop(L, 1);
    if (!result)
        throw luaU::Error("Event \"" + eventname + "\" not found!");
    return result;
}

class wrap_Component: public Component, public luabind::wrap_base {
public:
    wrap_Component(lua_State* L, Entity& parent, std::string const& classname)
    {
        m_metaComponent = ComponentRegistry::get(L)[classname];
        if (!m_metaComponent)
            throw InvalidMetaComponentName(classname);

        parent.add(*this);
        assert(this->parent() == &parent);
    }

	void bindLuaPart()
	{
		luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this);
		if (wrapper.m_strong_ref.is_valid()) {
			LOG_W("Double call to wrap_Component::bindLuaPart");
			return;
		}
		wrapper.get(wrapper.state());
		wrapper.m_strong_ref.set(wrapper.state());
	}

    virtual MetaComponent const& metaComponent() const { return *m_metaComponent; }

    virtual void initComponent()
	{
		luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this);
		if (!wrapper.m_strong_ref.is_valid()) {
			LOG_W("wrap_Component::bindLuaPart was not called yet! Calling it now.");
			bindLuaPart();
		}
		call<void>("initComponent");
	}
    virtual void cleanupComponent()
	{
		if (ServiceLocator::luaVm().L()) {
			call<void>("cleanupComponent");
		} else {
			LOG_W(boost::format("wrap_Component::cleanupComponent: cannot dispatch to Lua, because"
			     " the lua_State is closing. (this=%1%; name=%2%)") % this % m_metaComponent->name());
		}
	}

    static void nop(Component*) { /* NOP */ }

private:
    MetaComponent const* m_metaComponent;
};

class wrap_ConnectionBase: public ConnectionBase, public luabind::wrap_base {
public:
    virtual void disconnect() { call<void>("disconnect"); }
    virtual bool isConnected() const { return call<bool>("isConnected"); }
};

} // anonymous namespace

static bool operator==(Component const& lhs, Component const* rhs)
    { return &lhs == rhs; }

static void init(LuaVm& vm)
{
    LUAU_BALANCED_STACK_DBG(vm.L());

    LHMODULE [
        // Component class
        // Note: metaComponent() is left out and implemented in wrap_Component
        class_<Component, wrap_Component, WeakRef<Component>>("Component")
            .def(constructor<lua_State*, Entity&, std::string const&>())
            .def("initComponent", &Component::initComponent, &wrap_Component::nop)
            .def("cleanupComponent", &Component::cleanupComponent, &wrap_Component::nop)
            .property("parent", &Component_parent)
            .property("componentName", &Component_componentName)
			.def("_bindLuaPart", &wrap_Component::bindLuaPart)
            .def(const_self == other<Component*>())
            .def(tostring(const_self))
            .LHISREFVALID2(Component),
        def("registerComponent", &registerMetaComponent),
        def("connect", &connectEvent, adopt(result)),
        class_<ConnectionBase, wrap_ConnectionBase>("ConnectionBase")
            .def(constructor<>())
            .def("disconnect", &ConnectionBase::disconnect)
            .def("getIsConnected", &ConnectionBase::isConnected)
            .property("isConnected", &ConnectionBase::isConnected)
    ];

    lua_getglobal(vm.L(), "jd");
    luabind::object(vm.L(), static_cast<Component*>(nullptr)).push(vm.L());
    lua_setfield(vm.L(), -2, "NIL_COMPONENT");
    lua_pop(vm.L(), 1);
}

bool operator== (MetaComponent const& lhs, MetaComponent const& rhs)
{
    if (&lhs == &rhs) {
        assert(&lhs.name() == &rhs.name());
        return true;
    }
    assert(&lhs.name() != &rhs.name());
    assert(lhs.name() != rhs.name());
    return false;
}

bool operator!= (MetaComponent const& lhs, MetaComponent const& rhs)
{
    return !(lhs == rhs);
}

bool operator<  (MetaComponent const& lhs, MetaComponent const& rhs)
{
    return lhs.name() < rhs.name();
}

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

LuaMetaComponent::LuaMetaComponent(lua_State* L, std::string const& name):
    m_L(L),
    m_name(name)
{
    ComponentRegistry::get(L).registerComponent(this);
}

std::string const& LuaMetaComponent::name() const
{
    return m_name;
}

Component* LuaMetaComponent::create() const
{
    using namespace luabind;
    return call_function<Component*>(m_L, m_name.c_str())[adopt(result)];
}

void LuaMetaComponent::castUp(lua_State* L, Component* c) const
{
    assert(dynamic_cast<wrap_Component*>(c));
	luabind::object o(L, c->ref<wrap_Component>());
    o.push(L);
}

ConnectionBase* LuaMetaComponent::connectEvent(Component* c, std::string const& name) const
{
    using namespace luabind;
    object receiver(from_stack(m_L, -1));
    object callback = globals(m_L)[jd::moduleName]["callback_connectLuaEvent"];
    if (type(callback) != LUA_TFUNCTION)
        throw std::runtime_error("no callback for event connection defined (must be a plain function)");
    return object_cast<ConnectionBase*>(callback(c, name, receiver)[adopt(result)]);
}
<commit_msg>wrap_ConnectionBase::isConnected(): Call getIsConnected.<commit_after>#include "compsys/MetaComponent.hpp"
#include "compsys/Component.hpp"
#include "ComponentRegistry.hpp"
#include <unordered_map>
#include "LuaUtils.hpp"
#include "svc/ServiceLocator.hpp"
#include "svc/LuaVm.hpp"
#include "Logfile.hpp"
#include <boost/format.hpp>

static char const libname[] = "ComponentSystem";
#include "luaexport/ExportThis.hpp"
#include <luabind/class_info.hpp>
#include <luabind/raw_policy.hpp>
#include <luabind/adopt_policy.hpp>
#include <luabind/operator.hpp>
#include <ssig.hpp>
#include "Entity.hpp"

namespace {

static void registerMetaComponent(lua_State* L, std::string const& name)
{
    static std::vector<std::unique_ptr<LuaMetaComponent>> components;
    components.push_back(std::unique_ptr<LuaMetaComponent>(new LuaMetaComponent(L, name)));
}

static std::string const& Component_componentName(Component const& c)
{
    return c.metaComponent().name();
}

luabind::object Component_parent(Component const& c, lua_State* L)
{
    if (c.parent())
        return luabind::object(L, c.parent()->ref());
    else
        return luabind::object();
}

static std::ostream& operator<< (std::ostream& os, Component const& c)
{
    return os << "jd.Component (" << c.metaComponent().name() << " @" << &c << ')';
}

static ConnectionBase* connectEvent(
    lua_State* L,
    Component& sender,
    std::string const& eventname,
    luabind::object const& receiver)
{
    receiver.push(L);
    ConnectionBase* result = sender.metaComponent().connectEvent(
        L, &sender, eventname);
    lua_pop(L, 1);
    if (!result)
        throw luaU::Error("Event \"" + eventname + "\" not found!");
    return result;
}

class wrap_Component: public Component, public luabind::wrap_base {
public:
    wrap_Component(lua_State* L, Entity& parent, std::string const& classname)
    {
        m_metaComponent = ComponentRegistry::get(L)[classname];
        if (!m_metaComponent)
            throw InvalidMetaComponentName(classname);

        parent.add(*this);
        assert(this->parent() == &parent);
    }

	void bindLuaPart()
	{
		luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this);
		if (wrapper.m_strong_ref.is_valid()) {
			LOG_W("Double call to wrap_Component::bindLuaPart");
			return;
		}
		wrapper.get(wrapper.state());
		wrapper.m_strong_ref.set(wrapper.state());
	}

    virtual MetaComponent const& metaComponent() const { return *m_metaComponent; }

    virtual void initComponent()
	{
		luabind::wrapped_self_t& wrapper = luabind::detail::wrap_access::ref(*this);
		if (!wrapper.m_strong_ref.is_valid()) {
			LOG_W("wrap_Component::bindLuaPart was not called yet! Calling it now.");
			bindLuaPart();
		}
		call<void>("initComponent");
	}
    virtual void cleanupComponent()
	{
		if (ServiceLocator::luaVm().L()) {
			call<void>("cleanupComponent");
		} else {
			LOG_W(boost::format("wrap_Component::cleanupComponent: cannot dispatch to Lua, because"
			     " the lua_State is closing. (this=%1%; name=%2%)") % this % m_metaComponent->name());
		}
	}

    static void nop(Component*) { /* NOP */ }

private:
    MetaComponent const* m_metaComponent;
};

class wrap_ConnectionBase: public ConnectionBase, public luabind::wrap_base {
public:
    virtual void disconnect() { call<void>("disconnect"); }
    virtual bool isConnected() const { return call<bool>("getIsConnected"); }
};

} // anonymous namespace

static bool operator==(Component const& lhs, Component const* rhs)
    { return &lhs == rhs; }

static void init(LuaVm& vm)
{
    LUAU_BALANCED_STACK_DBG(vm.L());

    LHMODULE [
        // Component class
        // Note: metaComponent() is left out and implemented in wrap_Component
        class_<Component, wrap_Component, WeakRef<Component>>("Component")
            .def(constructor<lua_State*, Entity&, std::string const&>())
            .def("initComponent", &Component::initComponent, &wrap_Component::nop)
            .def("cleanupComponent", &Component::cleanupComponent, &wrap_Component::nop)
            .property("parent", &Component_parent)
            .property("componentName", &Component_componentName)
			.def("_bindLuaPart", &wrap_Component::bindLuaPart)
            .def(const_self == other<Component*>())
            .def(tostring(const_self))
            .LHISREFVALID2(Component),
        def("registerComponent", &registerMetaComponent),
        def("connect", &connectEvent, adopt(result)),
        class_<ConnectionBase, wrap_ConnectionBase>("ConnectionBase")
            .def(constructor<>())
            .def("disconnect", &ConnectionBase::disconnect)
            .def("getIsConnected", &ConnectionBase::isConnected)
            .property("isConnected", &ConnectionBase::isConnected)
    ];

    lua_getglobal(vm.L(), "jd");
    luabind::object(vm.L(), static_cast<Component*>(nullptr)).push(vm.L());
    lua_setfield(vm.L(), -2, "NIL_COMPONENT");
    lua_pop(vm.L(), 1);
}

bool operator== (MetaComponent const& lhs, MetaComponent const& rhs)
{
    if (&lhs == &rhs) {
        assert(&lhs.name() == &rhs.name());
        return true;
    }
    assert(&lhs.name() != &rhs.name());
    assert(lhs.name() != rhs.name());
    return false;
}

bool operator!= (MetaComponent const& lhs, MetaComponent const& rhs)
{
    return !(lhs == rhs);
}

bool operator<  (MetaComponent const& lhs, MetaComponent const& rhs)
{
    return lhs.name() < rhs.name();
}

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

LuaMetaComponent::LuaMetaComponent(lua_State* L, std::string const& name):
    m_L(L),
    m_name(name)
{
    ComponentRegistry::get(L).registerComponent(this);
}

std::string const& LuaMetaComponent::name() const
{
    return m_name;
}

Component* LuaMetaComponent::create() const
{
    using namespace luabind;
    return call_function<Component*>(m_L, m_name.c_str())[adopt(result)];
}

void LuaMetaComponent::castUp(lua_State* L, Component* c) const
{
    assert(dynamic_cast<wrap_Component*>(c));
	luabind::object o(L, c->ref<wrap_Component>());
    o.push(L);
}

ConnectionBase* LuaMetaComponent::connectEvent(Component* c, std::string const& name) const
{
    using namespace luabind;
    object receiver(from_stack(m_L, -1));
    object callback = globals(m_L)[jd::moduleName]["callback_connectLuaEvent"];
    if (type(callback) != LUA_TFUNCTION)
        throw std::runtime_error("no callback for event connection defined (must be a plain function)");
    return object_cast<ConnectionBase*>(callback(c, name, receiver)[adopt(result)]);
}
<|endoftext|>


<commit_before>#ifndef CONCURRENCY_NEW_MUTEX_HPP_
#define CONCURRENCY_NEW_MUTEX_HPP_

#include "concurrency/rwlock.hpp"

// This is a mutex, following the usual semantics (seen in rwlock_t,
// fifo_enforcer_sink_t, buf_lock_t) where construction puts you in the queue, a
// signal is pulsed when you have exclusive access, and acquirers gain exclusive
// access in the same order as construction.  You should favor this instead of
// mutex_t (you might want to make a mutex_acq_t type first).

class new_mutex_t {
public:
    new_mutex_t() { }
    ~new_mutex_t() { }

private:
    friend class new_mutex_in_line_t;

    rwlock_t rwlock_;

    DISABLE_COPYING(new_mutex_t);
};

class new_mutex_in_line_t {
public:
    new_mutex_in_line_t() { }

    explicit new_mutex_in_line_t(new_mutex_t *new_mutex)
        : rwlock_in_line_(&new_mutex->rwlock_, access_t::write) { }

    const signal_t *acq_signal() const {
        return rwlock_in_line_.write_signal();
    }

    void reset() {
        rwlock_in_line_.reset();
    }

private:
    rwlock_in_line_t rwlock_in_line_;

    DISABLE_COPYING(new_mutex_in_line_t);
};

class new_mutex_acq_t : private new_mutex_in_line_t {
public:
    // Acquires the lock.  The constructor blocks the coroutine, it doesn't return
    // until the lock is acquired.
    new_mutex_acq_t(new_mutex_t *lock) : new_mutex_in_line_t(lock) {
        acq_signal()->wait();
    }
    ~new_mutex_acq_t() { }

private:
    DISABLE_COPYING(new_mutex_acq_t);
};

#endif  // CONCURRENCY_NEW_MUTEX_HPP_
<commit_msg>Removed pointless destructor.<commit_after>#ifndef CONCURRENCY_NEW_MUTEX_HPP_
#define CONCURRENCY_NEW_MUTEX_HPP_

#include "concurrency/rwlock.hpp"

// This is a mutex, following the usual semantics (seen in rwlock_t,
// fifo_enforcer_sink_t, buf_lock_t) where construction puts you in the queue, a
// signal is pulsed when you have exclusive access, and acquirers gain exclusive
// access in the same order as construction.  You should favor this instead of
// mutex_t (you might want to make a mutex_acq_t type first).

class new_mutex_t {
public:
    new_mutex_t() { }
    ~new_mutex_t() { }

private:
    friend class new_mutex_in_line_t;

    rwlock_t rwlock_;

    DISABLE_COPYING(new_mutex_t);
};

class new_mutex_in_line_t {
public:
    new_mutex_in_line_t() { }

    explicit new_mutex_in_line_t(new_mutex_t *new_mutex)
        : rwlock_in_line_(&new_mutex->rwlock_, access_t::write) { }

    const signal_t *acq_signal() const {
        return rwlock_in_line_.write_signal();
    }

    void reset() {
        rwlock_in_line_.reset();
    }

private:
    rwlock_in_line_t rwlock_in_line_;

    DISABLE_COPYING(new_mutex_in_line_t);
};

class new_mutex_acq_t : private new_mutex_in_line_t {
public:
    // Acquires the lock.  The constructor blocks the coroutine, it doesn't return
    // until the lock is acquired.
    new_mutex_acq_t(new_mutex_t *lock) : new_mutex_in_line_t(lock) {
        acq_signal()->wait();
    }

private:
    DISABLE_COPYING(new_mutex_acq_t);
};

#endif  // CONCURRENCY_NEW_MUTEX_HPP_
<|endoftext|>