<commit_before>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).
** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).
**
** This plugin is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as
** published by the Free Software Foundation, either version 2.1
** of the License, or (at your option) any later version.
**
** This plugin is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/

#include "doxygensettings.h"
#include "doxygen.h"
#include "doxygenplugin.h"
#include "doxygenconstants.h"
#include <plugins/coreplugin/icore.h>
#include <libs/utils/qtcassert.h>
#include <QtCore/QCoreApplication>
#include <QIcon>

namespace DoxyPlugin {

DoxygenSettings* DoxygenSettings::m_doxygenSettingsInstance = 0;

DoxygenSettings::DoxygenSettings()
{
    m_doxygenSettingsInstance = this;
    if(QSettings *settings = Core::ICore::instance()->settings())
        m_settings.fromSettings(settings);
    setId("A.General");
    setDisplayName(tr("Doxygen"));
    setCategory(Core::Id::fromString(QString(Constants::DOXYGEN_SETTINGS_CATEGORY)));
    setDisplayCategory("Doxygen");
    setCategoryIcon(":/doxygen.png");
}

QWidget* DoxygenSettings::createPage(QWidget *parent)
{
    m_widget = new DoxygenSettingsWidget(parent);
    m_widget->setSettings(settings());
    return m_widget;
}

QWidget* DoxygenSettings::widget()
{
    m_widget = new DoxygenSettingsWidget;
    m_widget->setSettings(settings());
    return m_widget;
}

void DoxygenSettings::apply()
{
    //DoxygenPlugin::instance()->setSettings(m_widget->settings());
}

void DoxygenSettings::finish()
{
 delete m_widget;
}

DoxygenSettingsStruct DoxygenSettings::settings() const
{
    return m_settings;
}

void DoxygenSettings::setSettings(const DoxygenSettingsStruct &s)
{
    if (s != m_settings)
    {
        m_settings = s;
        if(QSettings *settings = Core::ICore::instance()->settings())
            m_settings.toSettings(settings);
    }
}

DoxygenSettings* DoxygenSettings::instance()
{
    QTC_ASSERT(m_doxygenSettingsInstance, return m_doxygenSettingsInstance);
    return m_doxygenSettingsInstance;
}
}
<commit_msg>Fix setting application<commit_after>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).
** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).
**
** This plugin is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as
** published by the Free Software Foundation, either version 2.1
** of the License, or (at your option) any later version.
**
** This plugin is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/

#include "doxygensettings.h"
#include "doxygen.h"
#include "doxygenplugin.h"
#include "doxygenconstants.h"
#include <plugins/coreplugin/icore.h>
#include <libs/utils/qtcassert.h>
#include <QtCore/QCoreApplication>
#include <QIcon>

namespace DoxyPlugin {
namespace Internal {

DoxygenSettings* DoxygenSettings::m_doxygenSettingsInstance = 0;

DoxygenSettings::DoxygenSettings()
{
    m_doxygenSettingsInstance = this;
    if(QSettings *settings = Core::ICore::instance()->settings())
        m_settings.fromSettings(settings);
    setId("A.General");
    setDisplayName(tr("Doxygen"));
    setCategory(Core::Id::fromString(QString(Constants::DOXYGEN_SETTINGS_CATEGORY)));
    setDisplayCategory("Doxygen");
    setCategoryIcon(":/doxygen.png");
}

QWidget* DoxygenSettings::createPage(QWidget *parent)
{
    m_widget = new DoxygenSettingsWidget(parent);
    m_widget->setSettings(settings());
    return m_widget;
}

QWidget* DoxygenSettings::widget()
{
    m_widget = new DoxygenSettingsWidget;
    m_widget->setSettings(settings());
    return m_widget;
}

void DoxygenSettings::apply()
{
    setSettings(m_widget->settings());
}

void DoxygenSettings::finish()
{
    delete m_widget;
}

DoxygenSettingsStruct DoxygenSettings::settings() const
{
    return m_settings;
}

void DoxygenSettings::setSettings(const DoxygenSettingsStruct &s)
{
    if (s != m_settings)
    {
        m_settings = s;
        if(QSettings *settings = Core::ICore::instance()->settings())
            m_settings.toSettings(settings);
    }
}

DoxygenSettings* DoxygenSettings::instance()
{
    QTC_ASSERT(m_doxygenSettingsInstance, return m_doxygenSettingsInstance);
    return m_doxygenSettingsInstance;
}

}
}
<|endoftext|>


<commit_before>#include "MightyPass.hpp"

using namespace std;
using namespace Geometry2d;

REGISTER_PLAY_CATEGORY(Gameplay::Plays::MightyPass, "Playing")

namespace Gameplay {
	namespace Plays {
		REGISTER_CONFIGURABLE(MightyPass)
	}
}

ConfigDouble *Gameplay::Plays::MightyPass::_planningHysterisis;

void Gameplay::Plays::MightyPass::createConfiguration(Configuration *cfg)
{
	_planningHysterisis = new ConfigDouble(cfg, "MightyPass/Planning Hysterisis", .2);
}

Gameplay::Plays::MightyPass::MightyPass(GameplayModule *gameplay):
	Play(gameplay),
	_leftFullback(gameplay, Behaviors::Fullback::Left),
	_rightFullback(gameplay, Behaviors::Fullback::Right),
	// _centerFullback(gameplay, Behaviors::Fullback::Center),
	// _kicker1(gameplay),
	// _kicker2(gameplay),
	_fieldEval(gameplay->state())
{
	_leftFullback.otherFullbacks.insert(&_rightFullback);
	// _leftFullback.otherFullbacks.insert(&_centerFullback);
	_rightFullback.otherFullbacks.insert(&_leftFullback);
	// _rightFullback.otherFullbacks.insert(&_centerFullback);
	// _centerFullback.otherFullbacks.insert(&_rightFullback);
	// _centerFullback.otherFullbacks.insert(&_leftFullback);

	_fieldEval.visualize = true;
}

float Gameplay::Plays::MightyPass::score ( Gameplay::GameplayModule* gameplay )
{
	// only run if we are playing and not in a restart
	bool refApplicable = gameplay->state()->gameState.playing();
	return refApplicable ? 0 : INFINITY;
}

bool Gameplay::Plays::MightyPass::run()
{
	Rect rect(Point(-Field_Width / 2.0f, 0), Point(Field_Width / 2.0f, Field_Length));
	_fieldEval.visualize = true;
	_fieldEval.bestPointInRect(rect);

	return true;

	// // handle assignments
	// set<OurRobot *> available = _gameplay->playRobots();

	// // defense first - closest to goal
	// assignNearest(_leftFullback.robot, available, Geometry2d::Point());
	// assignNearest(_rightFullback.robot, available, Geometry2d::Point());

	// // choose offense, we want both robots to attack
	// assignNearest(_kicker1.robot, available, ball().pos);
	// assignNearest(_kicker2.robot, available, ball().pos);

	// // additional defense - if it exists
	// assignNearest(_centerFullback.robot, available, Geometry2d::Point());

	// // manually reset any kickers so they keep kicking
	// // if (_kicker1.done())
	// // 	_kicker1.restart();
	// // if (_kicker2.done())
	// // 	_kicker2.restart();

	// // add obstacles - always bias to kicker1
	// if (_kicker1.robot && _kicker2.robot) {
	// 	unsigned k1 = _kicker1.robot->shell(), k2 = _kicker2.robot->shell();
	// 	_kicker1.robot->avoidTeammateRadius(k2, 0.8 * Robot_Radius);
	// 	_kicker2.robot->avoidTeammateRadius(k1, 0.5);
	// }

	// // execute kickers dumbly
	// if (_kicker1.robot) _kicker1.run();
	// if (_kicker2.robot) _kicker2.run();

	// // run standard fullback behavior
	// if (_leftFullback.robot) _leftFullback.run();
	// if (_rightFullback.robot) _rightFullback.run();
	// if (_centerFullback.robot) _centerFullback.run();

	// return true;
}

// #pragma mark -

// bool Gameplay::Plays::MightyPass::run() {

// 	bool haveBall = true;	//	FIXME: ?

// 	if ( haveBall ) {
// 		//******	maintain some defensively-positioned bots just in case
// 		//	have a defensiveness score?
// 		float defensiveness = 0;		//	= field length - average OurRobot->pos.
// 		float theirOffensiveness = 0;	//

// 		//***** build a graph of possible actions that lead from active bot to goal
// 		OurRobot *activeRobot = NULL;	//	FIXME: ?

// 	} else {

// 	}

// }

// #pragma mark Evaluation
// //================================================================================

// float Gameplay::Plays::MightyPass::evaluatePass(Point &from, Point &to) {

// }

// float Gameplay::Plays::MightyPass::evaluateShot(Point &from, Segment &goalSegment) {

// }

// float Gameplay::Plays::MightyPass::evaluateReposition(Point &from, Point &to) {
// 	const float multiplier = 1;	//	FIXME: get a real multiplier
// 	float dist = (to - from).mag();

// 	return dist * multiplier;
// }

// class MightyPassPlan : {

// };

// class MightyPassPlanAction :  {
// public:

// 	typedef enum {
// 		MightyPassPlanActionTypeShoot,
// 		MightyPassPlanActionTypePass,
// 		MightyPassPlanActionTypeReposition
// 	} MightyPassPlanActionType;

// 	OurRobot *fromBot;
// 	OurRobot *toBot;

// 	float cost;
// };

<commit_msg>cleaned up MightyPass some<commit_after>#include "MightyPass.hpp"

using namespace std;
using namespace Geometry2d;

REGISTER_PLAY_CATEGORY(Gameplay::Plays::MightyPass, "Playing")

namespace Gameplay {
	namespace Plays {
		REGISTER_CONFIGURABLE(MightyPass)
	}
}

ConfigDouble *Gameplay::Plays::MightyPass::_planningHysterisis;

void Gameplay::Plays::MightyPass::createConfiguration(Configuration *cfg)
{
	_planningHysterisis = new ConfigDouble(cfg, "MightyPass/Planning Hysterisis", .2);
}

Gameplay::Plays::MightyPass::MightyPass(GameplayModule *gameplay):
	Play(gameplay),
	_leftFullback(gameplay, Behaviors::Fullback::Left),
	_rightFullback(gameplay, Behaviors::Fullback::Right),
	_fieldEval(gameplay->state())
{
	_leftFullback.otherFullbacks.insert(&_rightFullback);
	_rightFullback.otherFullbacks.insert(&_leftFullback);

	_fieldEval.visualize = true;
}

float Gameplay::Plays::MightyPass::score ( Gameplay::GameplayModule* gameplay )
{
	// only run if we are playing and not in a restart
	bool refApplicable = gameplay->state()->gameState.playing();
	return refApplicable ? 0 : INFINITY;
}

bool Gameplay::Plays::MightyPass::run()
{
	Rect rect(Point(-Field_Width / 2.0f, 0), Point(Field_Width / 2.0f, Field_Length));
	_fieldEval.visualize = true;
	_fieldEval.bestPointInRect(rect);

	return true;

	// // handle assignments
	// set<OurRobot *> available = _gameplay->playRobots();

	// // defense first - closest to goal
	// assignNearest(_leftFullback.robot, available, Geometry2d::Point());
	// assignNearest(_rightFullback.robot, available, Geometry2d::Point());

	// // choose offense, we want both robots to attack
	// assignNearest(_kicker1.robot, available, ball().pos);
	// assignNearest(_kicker2.robot, available, ball().pos);

	// // additional defense - if it exists
	// assignNearest(_centerFullback.robot, available, Geometry2d::Point());

	// // manually reset any kickers so they keep kicking
	// // if (_kicker1.done())
	// // 	_kicker1.restart();
	// // if (_kicker2.done())
	// // 	_kicker2.restart();

	// // add obstacles - always bias to kicker1
	// if (_kicker1.robot && _kicker2.robot) {
	// 	unsigned k1 = _kicker1.robot->shell(), k2 = _kicker2.robot->shell();
	// 	_kicker1.robot->avoidTeammateRadius(k2, 0.8 * Robot_Radius);
	// 	_kicker2.robot->avoidTeammateRadius(k1, 0.5);
	// }

	// // execute kickers dumbly
	// if (_kicker1.robot) _kicker1.run();
	// if (_kicker2.robot) _kicker2.run();

	// // run standard fullback behavior
	// if (_leftFullback.robot) _leftFullback.run();
	// if (_rightFullback.robot) _rightFullback.run();
	// if (_centerFullback.robot) _centerFullback.run();

	// return true;
}

// #pragma mark -

// bool Gameplay::Plays::MightyPass::run() {

// 	bool haveBall = true;	//	FIXME: ?

// 	if ( haveBall ) {
// 		//******	maintain some defensively-positioned bots just in case
// 		//	have a defensiveness score?
// 		float defensiveness = 0;		//	= field length - average OurRobot->pos.
// 		float theirOffensiveness = 0;	//

// 		//***** build a graph of possible actions that lead from active bot to goal
// 		OurRobot *activeRobot = NULL;	//	FIXME: ?

// 	} else {

// 	}

// }

// #pragma mark Evaluation
// //================================================================================

// float Gameplay::Plays::MightyPass::evaluatePass(Point &from, Point &to) {

// }

// float Gameplay::Plays::MightyPass::evaluateShot(Point &from, Segment &goalSegment) {

// }

// float Gameplay::Plays::MightyPass::evaluateReposition(Point &from, Point &to) {
// 	const float multiplier = 1;	//	FIXME: get a real multiplier
// 	float dist = (to - from).mag();

// 	return dist * multiplier;
// }

<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-3-30 21:24:12
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcd(long long x, long long y)
{
  return y ? gcd(y, x % y) : x;
}

ll Inv(ll x)
{
  return power(x, MOD - 2);
}

ll B, W;
ll N;

typedef tuple<ll, ll> Q;

Q operator+(Q p, Q q)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll c = get<0>(q);
  ll d = get<1>(q);
  ll y = ((a * d) % MOD) + ((b * c) % MOD);
  y %= MOD;
  ll z = (b * d) % MOD;
  return Q(y, z);
}

Q operator-(Q p)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll y = (MOD - a) % MOD;
  return Q(y, b);
}

Q operator-(Q p, Q q)
{
  return p + (-q);
}

Q operator*(Q p, Q q)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll c = get<0>(q);
  ll d = get<1>(q);
  ll y = (a * c) % MOD;
  ll z = (b * d) % MOD;
  return Q(y, z);
}

ostream &operator<<(ostream &o_str, const Q &p)
{
  o_str << "{ " << get<0>(p) << " / " << get<1>(p);
  return o_str << " }";
}

vector<Q> ans;

void flush()
{
  assert((ll)ans.size() == B + W);
  for (auto x : ans)
  {
    ll y = get<0>(x);
    ll z = get<1>(x);
    cout << (y * Inv(z)) % MOD << endl;
  }
}

Q b[200010];
Q w[200010];

int main()
{
  init();
  cin >> B >> W;
  N = B + W;
  b[0] = Q(0, 1);
  w[0] = Q(0, 1);
  for (auto i = 0LL; i < N; i++)
  {
    Q x = Q(1, 2);
    ll z = power(2, i) * fact[W];
    z %= MOD;
    z *= fact[B];
    z %= MOD;
    z *= factinv[N - i];
    z %= MOD;
    if (i - W > 0)
    {
      ll y = fact[W] * fact[i - W];
      y %= MOD;
      y *= C(i - 1, W - 1);
      y %= MOD;
      b[i + 1] = b[i] + Q(y, z);
      x = x + b[i + 1] * Q(1, 2);
    }
    else
    {
      b[i + 1] = Q(0, 1);
    }
    if (i - B > 0)
    {
      ll y = fact[W] * fact[i - B];
      y %= MOD;
      y *= C(i - 1, B - 1);
      y %= MOD;
      w[i + 1] = w[i] + Q(y, z);
      x = x - w[i + 1] * Q(1, 2);
    }
    else
    {
      w[i + 1] = Q(0, 1);
    }
#if DEBUG == 1
    cerr << "b[" << i + 1 << "] = " << b[i + 1] << endl;
    cerr << "w[" << i + 1 << "] = " << w[i + 1] << endl;
#endif
    ans.push_back(x);
  }
  flush();
}<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1

/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-3-30 21:24:12
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcd(long long x, long long y)
{
  return y ? gcd(y, x % y) : x;
}

ll Inv(ll x)
{
  return power(x, MOD - 2);
}

ll B, W;
ll N;

typedef tuple<ll, ll> Q;

Q operator+(Q p, Q q)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll c = get<0>(q);
  ll d = get<1>(q);
  ll y = ((a * d) % MOD) + ((b * c) % MOD);
  y %= MOD;
  ll z = (b * d) % MOD;
  return Q(y, z);
}

Q operator-(Q p)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll y = (MOD - a) % MOD;
  return Q(y, b);
}

Q operator-(Q p, Q q)
{
  return p + (-q);
}

Q operator*(Q p, Q q)
{
  ll a = get<0>(p);
  ll b = get<1>(p);
  ll c = get<0>(q);
  ll d = get<1>(q);
  ll y = (a * c) % MOD;
  ll z = (b * d) % MOD;
  return Q(y, z);
}

ostream &operator<<(ostream &o_str, const Q &p)
{
  o_str << "{ " << get<0>(p) << " / " << get<1>(p);
  return o_str << " }";
}

vector<Q> ans;

void flush()
{
  assert((ll)ans.size() == B + W);
  for (auto x : ans)
  {
    ll y = get<0>(x);
    ll z = get<1>(x);
    cout << (y * Inv(z)) % MOD << endl;
  }
}

Q b[200010];
Q w[200010];

int main()
{
  init();
  cin >> B >> W;
  N = B + W;
  b[0] = Q(0, 1);
  w[0] = Q(0, 1);
  for (auto i = 0LL; i < N; i++)
  {
    Q x = Q(1, 2);
    ll z = power(2, i) * fact[W];
    z %= MOD;
    z *= fact[B];
    z %= MOD;
    z *= factinv[N - i];
    z %= MOD;
    if (i - W >= 0)
    {
      ll y = fact[W] * fact[i - W];
      y %= MOD;
      y *= C(i - 1, W - 1);
      y %= MOD;
      b[i + 1] = b[i] + Q(y, z);
      x = x + b[i + 1] * Q(1, 2);
    }
    else
    {
      b[i + 1] = Q(0, 1);
    }
    if (i - B >= 0)
    {
      ll y = fact[W] * fact[i - B];
      y %= MOD;
      y *= C(i - 1, B - 1);
      y %= MOD;
      w[i + 1] = w[i] + Q(y, z);
      x = x - w[i + 1] * Q(1, 2);
    }
    else
    {
      w[i + 1] = Q(0, 1);
    }
#if DEBUG == 1
    cerr << "b[" << i + 1 << "] = " << b[i + 1] << endl;
    cerr << "w[" << i + 1 << "] = " << w[i + 1] << endl;
#endif
    ans.push_back(x);
  }
  flush();
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : E2.cpp
 * Author  : Kazune Takahashi
 * Created : 3/15/2020, 1:01:22 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

constexpr int D{10};

class Solve
{
  string A, B, C;
  set<int> diff_AB, diff_BC, diff_CA;

public:
  Solve(string A, string B, string C) : A{A}, B{B}, C{C}
  {
    int ans{10000};
    make_diff();
#if DEBUG == 1
    cerr << A << ", " << B << endl;
    for (auto x : diff_AB)
    {
      cerr << x << endl;
    }
    cerr << B << ", " << C << endl;
    for (auto x : diff_BC)
    {
      cerr << x << endl;
    }
    cerr << C << ", " << A << endl;
    for (auto x : diff_CA)
    {
      cerr << x << endl;
    }
#endif
    for (auto x : diff_AB)
    {
      for (auto y : diff_BC)
      {
        auto z{-(x + y)};
        if (diff_CA.find(z) != diff_CA.end())
        {
          int start{min({0, -x, -x - y})};
          int finish{max({static_cast<int>(A.size()), static_cast<int>(B.size()) - x, static_cast<int>(C.size()) - x - y})};
#if DEBUG == 1
          if (x == -4 && y == 2)
          {
            cerr << "start = " << start << endl;
            cerr << "finish = " << finish << endl;
          }
#endif
          ch_min(ans, finish - start);
        }
      }
    }
    cout << ans << endl;
  }

private:
  static bool same(char x, char y)
  {
    return (x == y || x == '?' || y == '?');
  }

  static bool overlap(string const &S, string const &T, int K)
  {
    for (auto i = 0; i < static_cast<int>(S.size()); ++i)
    {
      int j{i + K};
      if (0 <= j && j < static_cast<int>(T.size()) && !same(S[i], T[j]))
      {
        return false;
      }
    }
    return true;
  }

  static void make_diff(string const &S, string const &T, set<int> &diff)
  {
    for (auto K = -D; K < D; ++K)
    {
      if (overlap(S, T, K))
      {
        diff.insert(K);
      }
    }
  }

  void make_diff()
  {
    make_diff(A, B, diff_AB);
    make_diff(B, C, diff_BC);
    make_diff(C, A, diff_CA);
  }
};

int main()
{
  string A, B, C;
  cin >> A >> B >> C;
  Solve solve(A, B, C);
}
<commit_msg>submit E2.cpp to 'E - Three Substrings' (panasonic2020) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : E2.cpp
 * Author  : Kazune Takahashi
 * Created : 3/15/2020, 1:01:22 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

constexpr int D{2010};

class Solve
{
  string A, B, C;
  set<int> diff_AB, diff_BC, diff_CA;

public:
  Solve(string A, string B, string C) : A{A}, B{B}, C{C}
  {
    int ans{10000};
    make_diff();
    for (auto x : diff_AB)
    {
      for (auto y : diff_BC)
      {
        auto z{-(x + y)};
        if (diff_CA.find(z) != diff_CA.end())
        {
          int start{min({0, -x, -x - y})};
          int finish{max({static_cast<int>(A.size()), static_cast<int>(B.size()) - x, static_cast<int>(C.size()) - x - y})};
          ch_min(ans, finish - start);
        }
      }
    }
    cout << ans << endl;
  }

private:
  static bool same(char x, char y)
  {
    return (x == y || x == '?' || y == '?');
  }

  static bool overlap(string const &S, string const &T, int K)
  {
    for (auto i = 0; i < static_cast<int>(S.size()); ++i)
    {
      int j{i + K};
      if (0 <= j && j < static_cast<int>(T.size()) && !same(S[i], T[j]))
      {
        return false;
      }
    }
    return true;
  }

  static void make_diff(string const &S, string const &T, set<int> &diff)
  {
    for (auto K = -D; K < D; ++K)
    {
      if (overlap(S, T, K))
      {
        diff.insert(K);
      }
    }
  }

  void make_diff()
  {
    make_diff(A, B, diff_AB);
    make_diff(B, C, diff_BC);
    make_diff(C, A, diff_CA);
  }
};

int main()
{
  string A, B, C;
  cin >> A >> B >> C;
  Solve solve(A, B, C);
}
<|endoftext|>


<commit_before>
#include "types.hpp"
#include "uGraph.hpp"

#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <pthread.h>
#include <stdlib.h>

// Global Vals

uint64_t clique_num;
uint64_t max_clique_size;
std::ofstream cfile;
pthread_mutex_t *f_lock;

void     print_vlist(vlist *v);

// type definitions

// @task_t represents a indenpendent task to compute cliques from @cand
// @flag is the biggest index of vertices having visited
struct task_t{

    task_t( vlist *x_cand, vlist *x_c, vid_t x_flag,
            task_t *x_pre = NULL, task_t *x_next = NULL):
        cand(x_cand), c(x_c), flag(x_flag), pre(x_pre), next(x_next){}

    vlist   *cand;
    vlist   *c;
    vid_t   flag;
    task_t  *pre;
    task_t  *next;
};

struct tasklist {

    tasklist(task_t *h, task_t *t): head(h), tail(t), len(0){
        //t_lock = (pthread_mutex_t)(malloc(sizeof(pthread_mutex_t)));
        if( pthread_mutex_init(&t_lock, NULL) != 0 &&
            pthread_mutex_init(&h_lock, NULL) != 0 ) {
            std::cout << "The Pthread Lock in Tasklist is Wrong" << std::endl;
            exit(0);
        }
    }

    void insert_tail( task_t *tmp ){

        ++len;

        if( head == NULL && tail == NULL ){
            head = tmp;
            tail = tmp;
            tmp->pre = NULL;
            tmp->next = NULL;
        } else if(head != NULL && tail != NULL){
            tmp->pre = tail;
            tail->next = tmp;
            tail = tmp;
            tmp->next = NULL;
        } else {
            std::cout << "Error: " << std::endl;
        }

    }

    void remove_head() {

        --len;

        if(tail == NULL && head == NULL){
            return ;
        } else if (tail != NULL && head != NULL && tail != head) {
            if( head->next == NULL ) std::cout << "head->next == NULL " << std::endl;
            head->next->pre = NULL;
            if( head->next == NULL )std::cout << "end" << std::endl;
            head = head->next;
        } else if (tail != NULL && head != NULL && tail == head) {
            head = NULL;
            tail = NULL;
        } else {
            std::cout << "Remove queue's head Error" << std::endl;
            exit(0);
        }
    }

    task_t *head;
    task_t *tail;
    pthread_mutex_t h_lock;
    pthread_mutex_t t_lock;
    size_t len;
};

struct thread_busy_count {

    thread_busy_count(){
        cnt = 0;
        pthread_mutex_init(&lock, NULL);
    }
    size_t cnt;
    pthread_mutex_t lock;
};

struct thread_task {

    thread_task( uGraph* xg,
                 tasklist *xtl,
                 thread_busy_count *xtc,
                 void (*xoutput)(vlist*)):
        g(xg), tl(xtl), tbc(xtc), output(xoutput){}

    uGraph *g;
    tasklist *tl;
    thread_busy_count *tbc;
    void (*output)(vlist *);
};

// some tools to deal with parameters of program
int         deal_parameters(size_t , char **);
std::string get_option_string(std::string);
int         get_option_int(std::string);

void        do_task( task_t   *t,
                     tasklist *tasks,
                     uGraph   *g,
                     void    (*output_func)(vlist *));

void*       thread_compute_clique( void *thread_info_ptr );

// return a new vlist that is the intersection of @v1 and @v2
vlist*   get_intsct(vlist *v1, vlist *v2);

// return a vlist that contains all elems in @vl and @v
vlist*   set_insert_copy(vlist *vl, vid_t v);
vlist*   set_insert_copy(vid_t v);

// release all memory of task_t
void     release_task(task_t *t);

// print a vlist in standard output
void     print_vlist(vlist *v);

// compute all maximal cliques with BFS method
// it means all cliques of size k is generated from size k-1

// all kinds of implementation of @output_func should delete the memory of vlist
void
clique_compute( uGraph *g,
                void (*output_func)(vlist *),
                int  thread_num){

    vlist *allvtx = new vlist();
    g->vtx_set(allvtx);

    tasklist tasks(NULL, NULL);

    for(vlist::const_iterator iter = allvtx->begin();
        iter != allvtx->end();
        ++iter){

        vlist *tmp_cand = new vlist( *(g->adjlist(*iter)) );
        task_t *tmp = new task_t( tmp_cand, set_insert_copy(*iter), *iter);
        tasks.insert_tail(tmp);
    }

    // Create @thread_num Threads to Compute Maximal Cliques

    thread_busy_count *t_count = new thread_busy_count();
    pthread_t **threads = (pthread_t **)(malloc(sizeof(pthread_t *) * thread_num));

    for(int i = 0; i != thread_num; ++i){
        thread_task *thread_info_ptr = new thread_task(g, &tasks, t_count, output_func);
        threads[i] = (pthread_t *)(malloc(sizeof(pthread_t)));
        if((pthread_create( threads[i],
                            NULL,
                            thread_compute_clique,
                            (void*)thread_info_ptr ) ) != 0 ) {
            std::cout << "Thread Creating has wrong" << std::endl;
            i--;
        }
    }

    while(true){
        if( t_count->cnt == thread_num && tasks.head == NULL ){
            std::cout << "All works have been done" << std::endl;
            break;
        }
    }

    return ;
}

void*
thread_compute_clique(void *thread_info_ptr){

    thread_task *tt = (thread_task *)(thread_info_ptr);
    tasklist *tasks = (tasklist *)(tt->tl);
    uGraph   *g     = (uGraph *)(tt->g);
    thread_busy_count *tbc = (thread_busy_count *)(tt->tbc);

    while(true){

        pthread_mutex_lock(&tbc->lock);
        tbc->cnt++;
        pthread_mutex_unlock(&tbc->lock);

        pthread_mutex_lock(&tasks->h_lock);
        while( tasks->head == NULL );
        pthread_mutex_lock(&tasks->t_lock);

        pthread_mutex_lock(&tbc->lock);
        tbc->cnt--;
        pthread_mutex_unlock(&tbc->lock);

        task_t *t = tasks->head;
        tasks->remove_head();

        pthread_mutex_unlock(&tasks->t_lock);
        pthread_mutex_unlock(&tasks->h_lock);

        do_task(t, tasks, g, tt->output);
    }

    return NULL;
}

// finish one task
void
do_task( task_t   *t,
         tasklist *tasks,
         uGraph   *g,
         void    (*output_func)(vlist *) ){

    if( t->cand->size() == 0 ){
        output_func(t->c);
        release_task(t);
        return ;
    }

    for( vlist::const_iterator iter = t->cand->begin();
         iter != t->cand->end();
         ++iter ){

        if( *iter < t->flag )
            continue;

        vlist *adjl = g->adjlist(*iter);
        vlist *candidate = get_intsct(adjl, t->cand);

        if(candidate->size() != 0){
            vlist  *newc = set_insert_copy(t->c, *iter);
            task_t *tmp  = new task_t(candidate, newc, *iter);

            pthread_mutex_lock(&tasks->t_lock);
            tasks->insert_tail(tmp);
            pthread_mutex_unlock(&tasks->t_lock);

        } else {
            vlist *res = set_insert_copy(t->c, *iter);
            output_func(res);
            delete res;
            delete candidate;
        }

    }

    release_task(t);
}

vlist*
get_intsct(vlist *v1, vlist *v2){

    vlist *res    = new vlist();
    vlist *lo     = v1->size() > v2->size() ? v2 : v1;
    vlist *check  = lo == v1 ? v2 : v1;

    for( vlist::const_iterator iter = lo->begin();
         iter != lo->end();
         ++iter )
        if( check->find(*iter) != check->end() )
            res->insert(*iter);

    return res;
}

/*
vlist*
get_intsct(vlist *v1, vlist *v2){

    vlist *res = new vlist();
    vlist *lo  = v1->size() > v2->size() ? v2 : v1;
    vlist *ch  = lo == v1 ? v2 : v1;

    for( vlist::const_iterator iter = lo->begin();
         iter != lo->end();
         ++iter)
        if( e )
}
*/

void
release_task(task_t *t){

    delete t->cand;
    delete t->c;
    delete t;
}

vlist*
set_insert_copy( vlist* vl, vid_t v){

    vlist *res = new vlist(*vl);
    res->insert(v);
    return res;
}

vlist*
set_insert_copy( vid_t v ){

    vlist *res = new vlist();
    res->insert(v);
    return res;
}

// some implementations of global functions whose duty is to store all cliques
void
print_vlist(vlist *v){

    for(vlist::iterator iter = v->begin();
        iter != v->end();
        ++iter )
        std::cout << *iter << ' ';
    std::cout << std::endl;
}

void
write_vlist(vlist *v){

    pthread_mutex_lock(f_lock);

    for(vlist::iterator iter = v->begin();
        iter != v->end();
        ++iter)
        cfile << *iter << ' ';
    cfile << std::endl;
    pthread_mutex_unlock(f_lock);
}

int
main(int argc, char **argv){

    if( argc ==  0) {
        std::cout << "The Program needs two parameters." << std::endl;
        std::cout << "1 - The input Graph File" << std::endl;
        std::cout << "2 - The Thread's Number" << std::endl;
        return 0;
    }
    uGraph *g = new uGraph(argv[1]);
    std::string filepath(argv[1]);
    filepath += ".bfs.multithreads.clique";
    cfile.open(filepath.c_str());

    f_lock = (pthread_mutex_t *)(malloc(sizeof(pthread_mutex_t)));
    pthread_mutex_init(f_lock, NULL);

    int thread_num = atoi(argv[2]);

    clique_compute(g, write_vlist, thread_num);

    cfile.close();

    //std::cout << "Total Clique Numbers: " << clique_num << std::endl;
    //std::cout << "Maximum size of cliques: " << max_clique_size << std::endl;

    return 0;
}

<commit_msg>move the thread_count mutex<commit_after>
#include "types.hpp"
#include "uGraph.hpp"

#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <pthread.h>
#include <stdlib.h>

// Global Vals

uint64_t clique_num;
uint64_t max_clique_size;
std::ofstream cfile;
pthread_mutex_t *f_lock;

void     print_vlist(vlist *v);

// type definitions

// @task_t represents a indenpendent task to compute cliques from @cand
// @flag is the biggest index of vertices having visited
struct task_t{

    task_t( vlist *x_cand, vlist *x_c, vid_t x_flag,
            task_t *x_pre = NULL, task_t *x_next = NULL):
        cand(x_cand), c(x_c), flag(x_flag), pre(x_pre), next(x_next){}

    vlist   *cand;
    vlist   *c;
    vid_t   flag;
    task_t  *pre;
    task_t  *next;
};

struct tasklist {

    tasklist(task_t *h, task_t *t): head(h), tail(t), len(0){
        //t_lock = (pthread_mutex_t)(malloc(sizeof(pthread_mutex_t)));
        if( pthread_mutex_init(&t_lock, NULL) != 0 &&
            pthread_mutex_init(&h_lock, NULL) != 0 ) {
            std::cout << "The Pthread Lock in Tasklist is Wrong" << std::endl;
            exit(0);
        }
    }

    void insert_tail( task_t *tmp ){

        ++len;

        if( head == NULL && tail == NULL ){
            head = tmp;
            tail = tmp;
            tmp->pre = NULL;
            tmp->next = NULL;
        } else if(head != NULL && tail != NULL){
            tmp->pre = tail;
            tail->next = tmp;
            tail = tmp;
            tmp->next = NULL;
        } else {
            std::cout << "Error: " << std::endl;
        }

    }

    void remove_head() {

        --len;

        if(tail == NULL && head == NULL){
            return ;
        } else if (tail != NULL && head != NULL && tail != head) {
            if( head->next == NULL ) std::cout << "head->next == NULL " << std::endl;
            head->next->pre = NULL;
            if( head->next == NULL )std::cout << "end" << std::endl;
            head = head->next;
        } else if (tail != NULL && head != NULL && tail == head) {
            head = NULL;
            tail = NULL;
        } else {
            std::cout << "Remove queue's head Error" << std::endl;
            exit(0);
        }
    }

    task_t *head;
    task_t *tail;
    pthread_mutex_t h_lock;
    pthread_mutex_t t_lock;
    size_t len;
};

struct thread_busy_count {

    thread_busy_count(){
        cnt = 0;
        pthread_mutex_init(&lock, NULL);
    }
    size_t cnt;
    pthread_mutex_t lock;
};

struct thread_task {

    thread_task( uGraph* xg,
                 tasklist *xtl,
                 thread_busy_count *xtc,
                 void (*xoutput)(vlist*)):
        g(xg), tl(xtl), tbc(xtc), output(xoutput){}

    uGraph *g;
    tasklist *tl;
    thread_busy_count *tbc;
    void (*output)(vlist *);
};

// some tools to deal with parameters of program
int         deal_parameters(size_t , char **);
std::string get_option_string(std::string);
int         get_option_int(std::string);

void        do_task( task_t   *t,
                     tasklist *tasks,
                     uGraph   *g,
                     void    (*output_func)(vlist *));

void*       thread_compute_clique( void *thread_info_ptr );

// return a new vlist that is the intersection of @v1 and @v2
vlist*   get_intsct(vlist *v1, vlist *v2);

// return a vlist that contains all elems in @vl and @v
vlist*   set_insert_copy(vlist *vl, vid_t v);
vlist*   set_insert_copy(vid_t v);

// release all memory of task_t
void     release_task(task_t *t);

// print a vlist in standard output
void     print_vlist(vlist *v);

// compute all maximal cliques with BFS method
// it means all cliques of size k is generated from size k-1

// all kinds of implementation of @output_func should delete the memory of vlist
void
clique_compute( uGraph *g,
                void (*output_func)(vlist *),
                int  thread_num){

    vlist *allvtx = new vlist();
    g->vtx_set(allvtx);

    tasklist tasks(NULL, NULL);

    for(vlist::const_iterator iter = allvtx->begin();
        iter != allvtx->end();
        ++iter){

        vlist *tmp_cand = new vlist( *(g->adjlist(*iter)) );
        task_t *tmp = new task_t( tmp_cand, set_insert_copy(*iter), *iter);
        tasks.insert_tail(tmp);
    }

    // Create @thread_num Threads to Compute Maximal Cliques

    thread_busy_count *t_count = new thread_busy_count();
    pthread_t **threads = (pthread_t **)(malloc(sizeof(pthread_t *) * thread_num));

    for(int i = 0; i != thread_num; ++i){
        thread_task *thread_info_ptr = new thread_task(g, &tasks, t_count, output_func);
        threads[i] = (pthread_t *)(malloc(sizeof(pthread_t)));
        if((pthread_create( threads[i],
                            NULL,
                            thread_compute_clique,
                            (void*)thread_info_ptr ) ) != 0 ) {
            std::cout << "Thread Creating has wrong" << std::endl;
            i--;
        }
    }

    while(true){
        if( t_count->cnt == 0 && tasks.head == NULL ){
            std::cout << "All works have been done" << std::endl;
            /* cancal all worker threads */
            for(int i = 0; i != thread_num; ++i) {
                if(pthread_cancel(*(threads[i])) != 0) i--;
            }
            break;
        }
    }

    return ;
}

void*
thread_compute_clique(void *thread_info_ptr){

    thread_task *tt = (thread_task *)(thread_info_ptr);
    tasklist *tasks = (tasklist *)(tt->tl);
    uGraph   *g     = (uGraph *)(tt->g);
    thread_busy_count *tbc = (thread_busy_count *)(tt->tbc);

    while(true){

        pthread_mutex_lock(&tasks->h_lock);
        while( tasks->head == NULL );
        pthread_mutex_lock(&tasks->t_lock);

        task_t *t = tasks->head;
        tasks->remove_head();

        pthread_mutex_lock(&tbc->lock);
        tbc->cnt++;
        pthread_mutex_unlock(&tbc->lock);

        pthread_mutex_unlock(&tasks->t_lock);
        pthread_mutex_unlock(&tasks->h_lock);

        do_task(t, tasks, g, tt->output);

        pthread_mutex_lock(&tbc->lock);
        tbc->cnt--;
        pthread_mutex_unlock(&tbc->lock);
    }

    return NULL;
}

// finish one task
void
do_task( task_t   *t,
         tasklist *tasks,
         uGraph   *g,
         void    (*output_func)(vlist *) ){

    if( t->cand->size() == 0 ){
        output_func(t->c);
        release_task(t);
        return ;
    }

    for( vlist::const_iterator iter = t->cand->begin();
         iter != t->cand->end();
         ++iter ){

        if( *iter < t->flag )
            continue;

        vlist *adjl = g->adjlist(*iter);
        vlist *candidate = get_intsct(adjl, t->cand);

        if(candidate->size() != 0){
            vlist  *newc = set_insert_copy(t->c, *iter);
            task_t *tmp  = new task_t(candidate, newc, *iter);

            pthread_mutex_lock(&tasks->t_lock);
            tasks->insert_tail(tmp);
            pthread_mutex_unlock(&tasks->t_lock);

        } else {
            vlist *res = set_insert_copy(t->c, *iter);
            output_func(res);
            delete res;
            delete candidate;
        }

    }

    release_task(t);
}

vlist*
get_intsct(vlist *v1, vlist *v2){

    vlist *res    = new vlist();
    vlist *lo     = v1->size() > v2->size() ? v2 : v1;
    vlist *check  = lo == v1 ? v2 : v1;

    for( vlist::const_iterator iter = lo->begin();
         iter != lo->end();
         ++iter )
        if( check->find(*iter) != check->end() )
            res->insert(*iter);

    return res;
}

/*
vlist*
get_intsct(vlist *v1, vlist *v2){

    vlist *res = new vlist();
    vlist *lo  = v1->size() > v2->size() ? v2 : v1;
    vlist *ch  = lo == v1 ? v2 : v1;

    for( vlist::const_iterator iter = lo->begin();
         iter != lo->end();
         ++iter)
        if( e )
}
*/

void
release_task(task_t *t){

    delete t->cand;
    delete t->c;
    delete t;
}

vlist*
set_insert_copy( vlist* vl, vid_t v){

    if(vl == NULL)
        std::cout << "vl is null" << std::endl;
    vlist *res = new vlist(*vl);
    res->insert(v);
    return res;
}

vlist*
set_insert_copy( vid_t v ){

    vlist *res = new vlist();
    res->insert(v);
    return res;
}

// some implementations of global functions whose duty is to store all cliques
void
print_vlist(vlist *v){

    for(vlist::iterator iter = v->begin();
        iter != v->end();
        ++iter )
        std::cout << *iter << ' ';
    std::cout << std::endl;
}

void
write_vlist(vlist *v){

    pthread_mutex_lock(f_lock);

    for(vlist::iterator iter = v->begin();
        iter != v->end();
        ++iter)
        cfile << *iter << ' ';
    cfile << std::endl;
    pthread_mutex_unlock(f_lock);
}

int
main(int argc, char **argv){

    if( argc ==  0) {
        std::cout << "The Program needs two parameters." << std::endl;
        std::cout << "1 - The input Graph File" << std::endl;
        std::cout << "2 - The Thread's Number" << std::endl;
        return 0;
    }
    uGraph *g = new uGraph(argv[1]);
    std::string filepath(argv[1]);
    filepath += ".bfs.multithreads.clique";
    cfile.open(filepath.c_str());

    f_lock = (pthread_mutex_t *)(malloc(sizeof(pthread_mutex_t)));
    pthread_mutex_init(f_lock, NULL);

    int thread_num = atoi(argv[2]);

    clique_compute(g, write_vlist, thread_num);

    cfile.close();

    //std::cout << "Total Clique Numbers: " << clique_num << std::endl;
    //std::cout << "Maximum size of cliques: " << max_clique_size << std::endl;

    return 0;
}

<|endoftext|>


<commit_before>/*
   fskit: a library for creating multi-threaded in-RAM filesystems
   Copyright (C) 2014  Jude Nelson

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
*/

#include "read.h"
#include "route.h"

// run the user-given read route callback
// return the number of bytes read on success
// return negative on failure
ssize_t fskit_run_user_read( struct fskit_core* core, char const* path, struct fskit_entry* fent, char* buf, size_t buflen, off_t offset ) {

   int rc = 0;
   int cbrc = 0;
   struct fskit_route_dispatch_args dargs;

   fskit_route_io_args( &dargs, buf, buflen, offset );

   rc = fskit_route_call_read( core, path, fent, &dargs, &cbrc );

   if( rc == -EPERM || rc == -ENOSYS ) {
      // no routes, so EOF
      return 0;
   }

   return (ssize_t)cbrc;
}

// read up to buflen bytes into buf, starting at the given offset in the file.
// return the number of bytes read on success.
// return negative on failure.
ssize_t fskit_read( struct fskit_core* core, struct fskit_file_handle* fh, char* buf, size_t buflen, off_t offset ) {

   fskit_file_handle_rlock( fh );

   // sanity check
   if( (fh->flags & (O_RDWR | O_WRONLY)) == 0 ) {

      fskit_file_handle_unlock( fh );
      return -EBADF;
   }

   ssize_t num_read = fskit_run_user_read( core, fh->path, fh->fent, buf, buflen, offset );

   if( num_read >= 0 ) {

      // update metadata
      fskit_entry_wlock( fh->fent );

      fskit_entry_set_atime( fh->fent, NULL );

      fskit_entry_unlock( fh->fent );
   }

   fskit_file_handle_unlock( fh );

   return num_read;
}
<commit_msg>File handle is invalid if it has no read-compatible flags.<commit_after>/*
   fskit: a library for creating multi-threaded in-RAM filesystems
   Copyright (C) 2014  Jude Nelson

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
*/

#include "read.h"
#include "route.h"

// run the user-given read route callback
// return the number of bytes read on success
// return negative on failure
ssize_t fskit_run_user_read( struct fskit_core* core, char const* path, struct fskit_entry* fent, char* buf, size_t buflen, off_t offset ) {

   int rc = 0;
   int cbrc = 0;
   struct fskit_route_dispatch_args dargs;

   fskit_route_io_args( &dargs, buf, buflen, offset );

   rc = fskit_route_call_read( core, path, fent, &dargs, &cbrc );

   if( rc == -EPERM || rc == -ENOSYS ) {
      // no routes, so EOF
      return 0;
   }

   return (ssize_t)cbrc;
}

// read up to buflen bytes into buf, starting at the given offset in the file.
// return the number of bytes read on success.
// return negative on failure.
ssize_t fskit_read( struct fskit_core* core, struct fskit_file_handle* fh, char* buf, size_t buflen, off_t offset ) {

   fskit_file_handle_rlock( fh );

   // sanity check
   if( (fh->flags & (O_RDWR | O_RDONLY)) == 0 ) {

      fskit_file_handle_unlock( fh );
      return -EBADF;
   }

   ssize_t num_read = fskit_run_user_read( core, fh->path, fh->fent, buf, buflen, offset );

   if( num_read >= 0 ) {

      // update metadata
      fskit_entry_wlock( fh->fent );

      fskit_entry_set_atime( fh->fent, NULL );

      fskit_entry_unlock( fh->fent );
   }

   fskit_file_handle_unlock( fh );

   return num_read;
}
<|endoftext|>


<commit_before>#include "save.hpp"
#include <exception>
#include <iostream>
#include <string.h>
#include <cassert>
#include "physconst.h"

using namespace GadgetWriter;
using namespace std;

#define BUFFER 48

gadget_header generate_header(std::valarray<int64_t> & npart, double Omega, double OmegaBaryon, double OmegaNuPart, double OmegaLambda, double HubbleParam, double Box, double InitTime, double UnitMass_in_g, double UnitLength_in_cm, double UnitVelocity_in_cm_per_s, bool combined_neutrinos)
{
  gadget_header header;
  //No factor of h^2 because mass is in 10^10 M_sun/h
  double scale = 3* HUBBLE* HUBBLE / (UnitMass_in_g / pow(UnitLength_in_cm, 3) * 8 * M_PI * GRAVITY) * pow(Box,3);
  /*Set masses*/
  for(int i = 0; i < N_TYPE; i++)
      header.mass[i] = 0;
  /*Don't forget to set masses correctly when the CDM actually incorporates other species*/
  double OmegaCDM = Omega;
  if(npart[BARYON_TYPE]) {
    header.mass[BARYON_TYPE] = OmegaBaryon * scale / npart[BARYON_TYPE];
    OmegaCDM -= OmegaBaryon;
  }

  if(npart[NEUTRINO_TYPE]){
    header.mass[NEUTRINO_TYPE] = OmegaNuPart * scale / npart[NEUTRINO_TYPE];
#ifdef NEUTRINO_PAIRS
    header.mass[NEUTRINO_TYPE] /= 2;
#endif //NEUTRINO_PAIRS
    OmegaCDM -=OmegaNuPart;
  }
  /*For the "edit the transfer function" neutrino simulation method, we would *not* want to do this.
   * For true kspace neutrinos, we do. */
  else if (!combined_neutrinos){
          OmegaCDM-=OmegaNuPart;
  }

  if(npart[DM_TYPE])
    header.mass[DM_TYPE] = OmegaCDM * scale / npart[DM_TYPE];

  for(int i=0; i< N_TYPE; ++i){
    header.NallHW[i] = ( npart[i] >> 32);
    header.npartTotal[i] = npart[i] - ((uint64_t)header.NallHW[i] << 32);
  }

  header.time = InitTime;
  header.redshift = 1.0 / InitTime - 1;

  header.BoxSize = Box;
  header.Omega0 = Omega;
  header.OmegaB = OmegaBaryon;
  header.OmegaLambda = OmegaLambda;
  header.HubbleParam = HubbleParam;
  /*Various flags; Most set by gadget later*/
  header.flag_sfr = 0;
  header.flag_feedback = 0;
  header.flag_cooling = 0;
  header.flag_stellarage = 0;
  header.flag_metals = 0;
  header.flag_entropy_instead_u=0;
  header.flag_doubleprecision=0;
  header.flag_ic_info=1;
  header.lpt_scalingfactor=1;
  header.UnitLength_in_cm = UnitLength_in_cm;
  header.UnitMass_in_g = UnitMass_in_g;
  header.UnitVelocity_in_cm_per_s = UnitVelocity_in_cm_per_s;
  return header;
}

class BufferedWrite
{
    public:
        BufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, int ItemsPart, const std::string& groupstring, const std::string& dtype) :
            snap(snap), NumPart(NumPart), ItemsPart(ItemsPart), groupstring(groupstring), dtype(dtype), blockmaxlen(BUFFER * 1024 * 1024)
        {
            if(!(block = (float *) malloc(blockmaxlen*ItemsPart*sizeof(float))))
                throw std::ios_base::failure("Failed to allocate "+std::to_string(ItemsPart*sizeof(float)*blockmaxlen/1024/1024)+" MB for write buffer");
        }
        ~BufferedWrite()
        {
            free(block);
        }
        int64_t do_write(int type, void * data, int64_t np_write, int64_t begin)
        {
            int64_t retval;
            try{
                retval = dynamic_cast<GWriteSnap&>(snap).WriteBlocks(groupstring, type, data, np_write, begin);
            } catch (const std::bad_cast & e) {
#ifdef HAVE_BIGFILE
                try {
                retval = dynamic_cast<GWriteBigSnap&>(snap).WriteBlocks(groupstring, type, data, np_write, begin, dtype.c_str(), ItemsPart);
                } catch(const std::bad_cast & e) {
#endif
                std::cout << e.what() << '\n';
                exit(1);
#ifdef HAVE_BIGFILE
                }
#endif
            }
            return retval;
        }
        int writeparticles(int type)
        {
            int64_t written=0, pc = 0;
            for(int64_t i = 0; i < NumPart; i++){
                for(int k = 0; k < ItemsPart; k++){
                    assert(ItemsPart*pc + k < blockmaxlen*ItemsPart);
                    block[ItemsPart * pc + k] = setter(i,k,type);
                }
                pc++;
#ifdef NEUTRINO_PAIRS
                /*Add an extra copy of the position vector for the double neutrino*/
                if(type == NEUTRINO_TYPE) {
                    for(int k = 0; k < ItemsPart; k++)
                      block[ItemsPart * pc + k] = setter(i, k, type);
                    pc++;
                }
#endif //NEUTRINO_PAIRS
                if(pc >= blockmaxlen){
                  if(do_write(type, block, pc,written) != pc)
                      throw std::ios_base::failure("Could not write data at particle "+std::to_string(i));
                  written+=pc;
                  pc = 0;
                }
            }
            if(pc > 0 && do_write(type, block, pc,written) != pc)
                  throw std::ios_base::failure("Could not write final data");
            return written;
       }
    protected:
       virtual double setter(int i, int k, int type) = 0;
    private:
        float * block;
        GWriteBaseSnap& snap;
        const int64_t NumPart;
        const int ItemsPart;
        const std::string & groupstring;
        const std::string & dtype;
        const int64_t blockmaxlen;
};

class PosBufferedWrite : public BufferedWrite
{
    public:
        PosBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, lpt_data * outdata, part_grid & Pgrid) :
            BufferedWrite(snap, NumPart, 3, name(snap.GetFormat()), "f4"),
            Pgrid(Pgrid), outdata(outdata)
            {}
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "Coordinates";
                case 4:
                    return "Position";
                default:
                    return "POS ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
          double value = Pgrid.Pos(i,k, type);
          if(outdata)
            value += outdata->GetDisp(i,k);
          value = periodic_wrap(value, Pgrid.GetBox());
          return value;
        }
        part_grid & Pgrid;
        lpt_data * outdata;
};

class VelBufferedWrite : public BufferedWrite
{
    public:
        VelBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, FermiDiracVel * therm_vels, lpt_data * outdata) :
            BufferedWrite(snap, NumPart, 3, name(snap.GetFormat()), "f4"),
            therm_vels(therm_vels), outdata(outdata)
            {
              memset(vtherm, 0, 3);
            }
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "Velocities";
                case 4:
                    return "Velocity";
                default:
                    return "VEL ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
          if(k == 0)
              get_new_therm_vels();
          assert(k >= 0 || k <= 2);
          double value = vtherm[k];
          if(outdata)
            value += outdata->GetVel(i,k);
          return value;
        }
          void get_new_therm_vels()
          {
              memset(vtherm, 0, 3);
              if(!therm_vels)
                  return;
              therm_vels->add_thermal_speeds(vtherm);
          }
        FermiDiracVel *therm_vels;
        lpt_data * outdata;
        float vtherm[3];
};

class IDBufferedWrite : public BufferedWrite
{
    public:
        IDBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, int64_t FirstId) :
            BufferedWrite(snap, NumPart, 1, name(snap.GetFormat()), "i"+std::to_string(sizeof(id_type))),
#ifdef NEUTRINO_PAIRS
            sw(0),
#endif
            FirstId(FirstId)
            {
            }
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "ParticleIDs";
                case 4:
                    return "ID";
                default:
                    return "ID  ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
#ifdef NEUTRINO_PAIRS
            if(type == NEUTRINO_TYPE) {
            sw != sw;
            return 2*(i+ FirstId) + sw;
            }
            else
#else
            return i + FirstId;
#endif
        }
#ifdef NEUTRINO_PAIRS
            bool sw;
#endif
            const int64_t FirstId;
};

/*Class to write zero energies*/
class EnergyBufferedWrite : public BufferedWrite
{
    public:
    EnergyBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart) :
        BufferedWrite(snap, NumPart, 1, snap.GetFormat() > 2 ? "InternalEnergy" : "U   ", "f4")
        {}
    private:
    virtual double setter(int i, int k, int type)
    {
        return 0;
    }
};

int64_t write_particle_data(GWriteBaseSnap& snap, int type, lpt_data * outdata, part_grid& Pgrid, FermiDiracVel *therm_vels, int64_t FirstId)
{
  const int64_t NumPart = Pgrid.GetNumPart(type)*Pgrid.GetNumPart(type)*Pgrid.GetNumPart(type);
  printf("\nWriting IC-file\n");
  {
    PosBufferedWrite pp(snap, NumPart, outdata, Pgrid);
    pp.writeparticles(type);
  }
  {
    VelBufferedWrite pp(snap, NumPart, therm_vels, outdata);
    pp.writeparticles(type);
  }
  {
    IDBufferedWrite pp(snap, NumPart, FirstId);
    pp.writeparticles(type);
  }
  {
    EnergyBufferedWrite pp(snap, NumPart);
    pp.writeparticles(type);
  }
  printf("Finished writing IC file.\n");
  FirstId+=NumPart;
#ifdef NEUTRINO_PAIRS
  if(type==2)
          FirstId+=NumPart;
#endif
  return FirstId;
}

double periodic_wrap(double x, double box)
{
  x = fmod(x, box);

  if (x < 0)
    x += box;

  return x;
}

<commit_msg>Use template shenanigans to ensure that the write buffer has the desired class. Fix up so that the dtype is specified at the same time.<commit_after>#include "save.hpp"
#include <exception>
#include <iostream>
#include <string.h>
#include <cassert>
#include "physconst.h"

using namespace GadgetWriter;
using namespace std;

#define BUFFER 48

gadget_header generate_header(std::valarray<int64_t> & npart, double Omega, double OmegaBaryon, double OmegaNuPart, double OmegaLambda, double HubbleParam, double Box, double InitTime, double UnitMass_in_g, double UnitLength_in_cm, double UnitVelocity_in_cm_per_s, bool combined_neutrinos)
{
  gadget_header header;
  //No factor of h^2 because mass is in 10^10 M_sun/h
  double scale = 3* HUBBLE* HUBBLE / (UnitMass_in_g / pow(UnitLength_in_cm, 3) * 8 * M_PI * GRAVITY) * pow(Box,3);
  /*Set masses*/
  for(int i = 0; i < N_TYPE; i++)
      header.mass[i] = 0;
  /*Don't forget to set masses correctly when the CDM actually incorporates other species*/
  double OmegaCDM = Omega;
  if(npart[BARYON_TYPE]) {
    header.mass[BARYON_TYPE] = OmegaBaryon * scale / npart[BARYON_TYPE];
    OmegaCDM -= OmegaBaryon;
  }

  if(npart[NEUTRINO_TYPE]){
    header.mass[NEUTRINO_TYPE] = OmegaNuPart * scale / npart[NEUTRINO_TYPE];
#ifdef NEUTRINO_PAIRS
    header.mass[NEUTRINO_TYPE] /= 2;
#endif //NEUTRINO_PAIRS
    OmegaCDM -=OmegaNuPart;
  }
  /*For the "edit the transfer function" neutrino simulation method, we would *not* want to do this.
   * For true kspace neutrinos, we do. */
  else if (!combined_neutrinos){
          OmegaCDM-=OmegaNuPart;
  }

  if(npart[DM_TYPE])
    header.mass[DM_TYPE] = OmegaCDM * scale / npart[DM_TYPE];

  for(int i=0; i< N_TYPE; ++i){
    header.NallHW[i] = ( npart[i] >> 32);
    header.npartTotal[i] = npart[i] - ((uint64_t)header.NallHW[i] << 32);
  }

  header.time = InitTime;
  header.redshift = 1.0 / InitTime - 1;

  header.BoxSize = Box;
  header.Omega0 = Omega;
  header.OmegaB = OmegaBaryon;
  header.OmegaLambda = OmegaLambda;
  header.HubbleParam = HubbleParam;
  /*Various flags; Most set by gadget later*/
  header.flag_sfr = 0;
  header.flag_feedback = 0;
  header.flag_cooling = 0;
  header.flag_stellarage = 0;
  header.flag_metals = 0;
  header.flag_entropy_instead_u=0;
  header.flag_doubleprecision=0;
  header.flag_ic_info=1;
  header.lpt_scalingfactor=1;
  header.UnitLength_in_cm = UnitLength_in_cm;
  header.UnitMass_in_g = UnitMass_in_g;
  header.UnitVelocity_in_cm_per_s = UnitVelocity_in_cm_per_s;
  return header;
}

template <typename T> class BufferedWrite
{
    public:
        BufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, int ItemsPart, const std::string& groupstring) :
            snap(snap), NumPart(NumPart), ItemsPart(ItemsPart), groupstring(groupstring), blockmaxlen(BUFFER * 1024 * 1024)
        {
            if(!(block = (T *) malloc(blockmaxlen*ItemsPart*sizeof(T))))
                throw std::ios_base::failure("Failed to allocate "+std::to_string(ItemsPart*sizeof(float)*blockmaxlen/1024/1024)+" MB for write buffer");
        }
        ~BufferedWrite()
        {
            free(block);
        }
        int64_t do_write(int type, void * data, int64_t np_write, int64_t begin)
        {
            int64_t retval;
            try{
                retval = dynamic_cast<GWriteSnap&>(snap).WriteBlocks(groupstring, type, data, np_write, begin);
            } catch (const std::bad_cast & e) {
#ifdef HAVE_BIGFILE
                try {
                retval = dynamic_cast<GWriteBigSnap&>(snap).WriteBlocks(groupstring, type, data, np_write, begin, dtype().c_str(), ItemsPart);
                } catch(const std::bad_cast & e) {
#endif
                std::cout << e.what() << '\n';
                exit(1);
#ifdef HAVE_BIGFILE
                }
#endif
            }
            return retval;
        }
        int writeparticles(int type)
        {
            int64_t written=0, pc = 0;
            for(int64_t i = 0; i < NumPart; i++){
                for(int k = 0; k < ItemsPart; k++){
                    assert(ItemsPart*pc + k < blockmaxlen*ItemsPart);
                    block[ItemsPart * pc + k] = setter(i,k,type);
                }
                pc++;
#ifdef NEUTRINO_PAIRS
                /*Add an extra copy of the position vector for the double neutrino*/
                if(type == NEUTRINO_TYPE) {
                    for(int k = 0; k < ItemsPart; k++)
                      block[ItemsPart * pc + k] = setter(i, k, type);
                    pc++;
                }
#endif //NEUTRINO_PAIRS
                if(pc >= blockmaxlen){
                  if(do_write(type, block, pc,written) != pc)
                      throw std::ios_base::failure("Could not write data at particle "+std::to_string(i));
                  written+=pc;
                  pc = 0;
                }
            }
            if(pc > 0 && do_write(type, block, pc,written) != pc)
                  throw std::ios_base::failure("Could not write final data");
            return written;
       }
    protected:
       virtual double setter(int i, int k, int type) = 0;
    private:
        std::string dtype(void) {
            throw std::runtime_error("Need to specialise dtype for class");
        }
        T * block;
        GWriteBaseSnap& snap;
        const int64_t NumPart;
        const int ItemsPart;
        const std::string & groupstring;
        const int64_t blockmaxlen;
};

template <> std::string BufferedWrite<float>::dtype(void) {
    return "f4";
};
template <> std::string BufferedWrite<double>::dtype(void) {
    return "f8";
};
template <> std::string BufferedWrite<id_type>::dtype(void) {
        return "i"+std::to_string(sizeof(id_type));
};

class PosBufferedWrite : public BufferedWrite<float>
{
    public:
        PosBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, lpt_data * outdata, part_grid & Pgrid) :
            BufferedWrite(snap, NumPart, 3, name(snap.GetFormat())),
            Pgrid(Pgrid), outdata(outdata)
            {}
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "Coordinates";
                case 4:
                    return "Position";
                default:
                    return "POS ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
          double value = Pgrid.Pos(i,k, type);
          if(outdata)
            value += outdata->GetDisp(i,k);
          value = periodic_wrap(value, Pgrid.GetBox());
          return value;
        }
        part_grid & Pgrid;
        lpt_data * outdata;
};

class VelBufferedWrite : public BufferedWrite<float>
{
    public:
        VelBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, FermiDiracVel * therm_vels, lpt_data * outdata) :
            BufferedWrite(snap, NumPart, 3, name(snap.GetFormat())),
            therm_vels(therm_vels), outdata(outdata)
            {
              memset(vtherm, 0, 3);
            }
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "Velocities";
                case 4:
                    return "Velocity";
                default:
                    return "VEL ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
          if(k == 0)
              get_new_therm_vels();
          assert(k >= 0 || k <= 2);
          double value = vtherm[k];
          if(outdata)
            value += outdata->GetVel(i,k);
          return value;
        }
          void get_new_therm_vels()
          {
              memset(vtherm, 0, 3);
              if(!therm_vels)
                  return;
              therm_vels->add_thermal_speeds(vtherm);
          }
        FermiDiracVel *therm_vels;
        lpt_data * outdata;
        float vtherm[3];
};

class IDBufferedWrite : public BufferedWrite<id_type>
{
    public:
        IDBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart, int64_t FirstId) :
            BufferedWrite(snap, NumPart, 1, name(snap.GetFormat())),
#ifdef NEUTRINO_PAIRS
            sw(0),
#endif
            FirstId(FirstId)
            {
            }
    private:
        std::string name(int format)
        {
            switch(format)
            {
                case 3:
                    return "ParticleIDs";
                case 4:
                    return "ID";
                default:
                    return "ID  ";
            }
        }
        virtual double setter(int i, int k, int type)
        {
#ifdef NEUTRINO_PAIRS
            if(type == NEUTRINO_TYPE) {
            sw != sw;
            return 2*(i+ FirstId) + sw;
            }
            else
#else
            return i + FirstId;
#endif
        }
#ifdef NEUTRINO_PAIRS
            bool sw;
#endif
            const int64_t FirstId;
};

/*Class to write zero energies*/
class EnergyBufferedWrite : public BufferedWrite<float>
{
    public:
    EnergyBufferedWrite(GWriteBaseSnap& snap, int64_t NumPart) :
        BufferedWrite(snap, NumPart, 1, snap.GetFormat() > 2 ? "InternalEnergy" : "U   ")
        {}
    private:
    virtual double setter(int i, int k, int type)
    {
        return 0;
    }
};

int64_t write_particle_data(GWriteBaseSnap& snap, int type, lpt_data * outdata, part_grid& Pgrid, FermiDiracVel *therm_vels, int64_t FirstId)
{
  const int64_t NumPart = Pgrid.GetNumPart(type)*Pgrid.GetNumPart(type)*Pgrid.GetNumPart(type);
  printf("\nWriting IC-file\n");
  {
    PosBufferedWrite pp(snap, NumPart, outdata, Pgrid);
    pp.writeparticles(type);
  }
  {
    VelBufferedWrite pp(snap, NumPart, therm_vels, outdata);
    pp.writeparticles(type);
  }
  {
    IDBufferedWrite pp(snap, NumPart, FirstId);
    pp.writeparticles(type);
  }
  {
    EnergyBufferedWrite pp(snap, NumPart);
    pp.writeparticles(type);
  }
  printf("Finished writing IC file.\n");
  FirstId+=NumPart;
#ifdef NEUTRINO_PAIRS
  if(type==2)
          FirstId+=NumPart;
#endif
  return FirstId;
}

double periodic_wrap(double x, double box)
{
  x = fmod(x, box);

  if (x < 0)
    x += box;

  return x;
}

<|endoftext|>


<commit_before>#ifndef VECTORLISTMODEL_HH
#define VECTORLISTMODEL_HH

#include <QAbstractListModel>

class VectorListModel : public QAbstractListModel
{
    Q_OBJECT

    std::vector<std::string> vec_ = {};
    Qt::ItemFlags flags_;
public:
    VectorListModel(Qt::ItemFlags flags) : flags_(flags) {}
    void add(std::string s) {
        auto len = vec_.size();
        beginInsertRows(QModelIndex(), len, len);
        vec_.push_back(std::move(s));
        endInsertRows();
    }

    int rowCount(const QModelIndex&) const {
        return vec_.size();
    }

    QVariant data(const QModelIndex &index, int role) const {
        if (!index.isValid())
            return QVariant();
        switch(role) {
        case Qt::DisplayRole:
        case Qt::EditRole:
            return QString::fromStdString(vec_[index.row()]);
        }

        return QVariant();
    }

    Qt::ItemFlags flags(const QModelIndex &index) const {
        if (!index.isValid())
            return Qt::ItemIsEnabled;

        return QAbstractItemModel::flags(index) | flags_;
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role) {
        if (index.isValid() && role == Qt::EditRole) {

            vec_[index.row()] = value.toString().toStdString();
            emit dataChanged(index, index);
            return true;
        }

        return false;
    }

};

#endif // VECTORLISTMODEL_HH
<commit_msg>vectorlistmodel vector interface updates<commit_after>#ifndef VECTORLISTMODEL_HH
#define VECTORLISTMODEL_HH

#include <QAbstractListModel>

class VectorListModel : public QAbstractListModel
{
    Q_OBJECT

    std::vector<std::string> vec_ = {};
    Qt::ItemFlags flags_;
public:
    // vector interface
    using value_type = std::string;
    using size_type = std::vector<std::string>::size_type;
    size_type size() const { return vec_.size(); }
    void resize (size_type n, value_type val = value_type()) {
        int ldiff = vec_.size() - n;
        if(ldiff < 0) { // grow
            beginInsertRows(QModelIndex{}, vec_.size(), n);
            vec_.resize(n);
            endInsertRows();
        } else if(ldiff > 0) { // shrink
            beginRemoveRows(QModelIndex{}, n, vec_.size());
            vec_.resize(n, std::move(val));
            endRemoveRows();
        }
    }
    bool empty() const { return vec_.empty(); }
    void push_back (const value_type& val) {
        beginInsertRows(QModelIndex{}, vec_.size(), vec_.size());
        vec_.push_back(val);
        endInsertRows();
    }
    template <class... Args>
    void emplace_back (Args&&... args) {
        beginInsertRows(QModelIndex{}, vec_.size(), vec_.size());
        vec_.emplace_back(std::forward(args)...);
        endInsertRows();
    }

    // QAbstractListModel interface

    VectorListModel(Qt::ItemFlags flags) : flags_(flags) {}

    int rowCount(const QModelIndex&) const {
        return vec_.size();
    }

    QVariant data(const QModelIndex &index, int role) const {
        if (!index.isValid())
            return QVariant();
        switch(role) {
        case Qt::DisplayRole:
        case Qt::EditRole:
            return QString::fromStdString(vec_[index.row()]);
        }

        return QVariant();
    }

    Qt::ItemFlags flags(const QModelIndex &index) const {
        if (!index.isValid())
            return Qt::ItemIsEnabled;

        return QAbstractItemModel::flags(index) | flags_;
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role) {
        if (index.isValid() && role == Qt::EditRole) {

            vec_[index.row()] = value.toString().toStdString();
            emit dataChanged(index, index);
            return true;
        }

        return false;
    }

};

#endif // VECTORLISTMODEL_HH
<|endoftext|>


<commit_before>#include "Database.h"

#include <QDebug>

Database::Database() : db(QSqlDatabase::addDatabase("QSQLITE"))
{
    db.setHostName("localhost");
    db.setDatabaseName("ascension.db");
}

bool Database::init()
{
    bool status = db.open();
    if (!status)
    {
        qDebug("Couldn't connect to the database!");
        return false;
    }

    QSqlQuery createQuery(db);
    createQuery.exec("CREATE TABLE IF NOT EXISTS games(ID INTEGER PRIMARY KEY ASC, GAMENAME TEXT NOT NULL, GAMEDIRECTORY TEXT NOT NULL, GAMEEXECUTABLE TEXT NOT NULL);");

    return true;
}

bool Database::reset()
{
    QSqlQuery query(db);
    return  query.exec("DROP TABLES *");
}

bool Database::addGame(QString gameName, QString gameDirectory, QString executablePath)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO GAMES(GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE) VALUES (:gameName, :gameDirectory, :executablePath);");
    query.bindValue(":gameName", gameName);
    query.bindValue(":gameDirectory", gameDirectory);
    query.bindValue(":executablePath", executablePath);
    return query.exec();
}

bool Database::removeGameById(unsigned int id)
{
    QSqlQuery query(db);
    query.prepare("DELETE FROM GAMES WHERE id = :id;");
    query.bindValue(":id", id);
    return query.exec();
}

Game Database::getGameById(unsigned int id)
{
    QSqlQuery query(db);
    query.prepare("SELECT GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES WHERE ID = :id;");
    query.bindValue(":ID", id);
    query.exec();

    if (!query.next())
    {
        return {0}; // TODO: ERROR HANDLING
    }

    QString name = query.value(0).toString();
    QString path = query.value(1).toString();
    QString exe = query.value(2).toString();

    return {id, name, path, exe};
}

Game Database::getGameByName(QString name)
{
    QSqlQuery query(db);
    query.prepare("SELECT GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES WHERE GAMENAME = :NAME;");
    query.bindValue(":NAME", name);
    query.exec();

    if (!query.next())
    {
        return {0}; // TODO: ERROR HANDLING
    }

    QString name = query.value(0).toString();
    QString path = query.value(1).toString();
    QString exe = query.value(2).toString();

    return {id, name, path, exe};
}

QList<Game> Database::getGames()
{
    QList<Game> games;
    QSqlQuery query;
    query.exec("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES;");
    while(query.next())
    {
        unsigned int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString path = query.value(2).toString();
        QString exe = query.value(3).toString();

        games.append({id, name, path, exe});
    }
    return games;
}

unsigned int Database::getGameCount()
{
    QSqlQuery query(db);
    query.exec("SELECT count() FROM GAMES;");
    if (!query.next())
    {
        return 0;
    }

    return query.value(0).toInt();
}
<commit_msg>Fix initalizer list for getGameByName<commit_after>#include "Database.h"

#include <QDebug>

Database::Database() : db(QSqlDatabase::addDatabase("QSQLITE"))
{
    db.setHostName("localhost");
    db.setDatabaseName("ascension.db");
}

bool Database::init()
{
    bool status = db.open();
    if (!status)
    {
        qDebug("Couldn't connect to the database!");
        return false;
    }

    QSqlQuery createQuery(db);
    createQuery.exec("CREATE TABLE IF NOT EXISTS games(ID INTEGER PRIMARY KEY ASC, GAMENAME TEXT NOT NULL, GAMEDIRECTORY TEXT NOT NULL, GAMEEXECUTABLE TEXT NOT NULL);");

    return true;
}

bool Database::reset()
{
    QSqlQuery query(db);
    return  query.exec("DROP TABLES *");
}

bool Database::addGame(QString gameName, QString gameDirectory, QString executablePath)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO GAMES(GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE) VALUES (:gameName, :gameDirectory, :executablePath);");
    query.bindValue(":gameName", gameName);
    query.bindValue(":gameDirectory", gameDirectory);
    query.bindValue(":executablePath", executablePath);
    return query.exec();
}

bool Database::removeGameById(unsigned int id)
{
    QSqlQuery query(db);
    query.prepare("DELETE FROM GAMES WHERE id = :id;");
    query.bindValue(":id", id);
    return query.exec();
}

Game Database::getGameById(unsigned int id)
{
    QSqlQuery query(db);
    query.prepare("SELECT GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES WHERE ID = :id;");
    query.bindValue(":ID", id);
    query.exec();

    if (!query.next())
    {
        return {0}; // TODO: ERROR HANDLING
    }

    QString name = query.value(0).toString();
    QString path = query.value(1).toString();
    QString exe = query.value(2).toString();

    return {id, name, path, exe};
}

Game Database::getGameByName(QString name)
{
    QSqlQuery query(db);
    query.prepare("SELECT ID, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES WHERE GAMENAME = :NAME;");
    query.bindValue(":NAME", name);
    query.exec();

    if (!query.next())
    {
        return {0}; // TODO: ERROR HANDLING
    }

    unsigned int id = query.value(0).toInt();
    QString path = query.value(1).toString();
    QString exe = query.value(2).toString();

    Game game = {id, name, path, exe};
    return game;
}

QList<Game> Database::getGames()
{
    QList<Game> games;
    QSqlQuery query;
    query.exec("SELECT ID, GAMENAME, GAMEDIRECTORY, GAMEEXECUTABLE FROM GAMES;");
    while(query.next())
    {
        unsigned int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString path = query.value(2).toString();
        QString exe = query.value(3).toString();

        games.append({id, name, path, exe});
    }
    return games;
}

unsigned int Database::getGameCount()
{
    QSqlQuery query(db);
    query.exec("SELECT count() FROM GAMES;");
    if (!query.next())
    {
        return 0;
    }

    return query.value(0).toInt();
}
<|endoftext|>


<commit_before>// Filename: test_texmem.cxx
// Created by:  drose (03Sep02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "pandaFramework.h"
#include "geomQuad.h"
#include "textureAttrib.h"

NodePath bogus_scene;

void
event_T(CPT_Event, void *data) {
  PandaFramework *framework = (PandaFramework *)data;
  WindowFramework *wf = framework->get_window(0);

  GraphicsStateGuardian *gsg = wf->get_graphics_window()->get_gsg();
  Camera *camera = wf->get_camera(0);
  NodePath models = framework->get_models();
  NodePath render = wf->get_render();

  if (!bogus_scene.is_empty()) {
    // We are undoing a previous shift-t.
    bogus_scene.remove_node();
    models.show();
    return;
  }

  // We are doing a new shift-t.  Hide the normal models, and create a
  // new bogus node to show the texture grid object.
  models.hide();
  bogus_scene = render.attach_new_node("bogus");

  // Try to force a flush of the texture memory by making a scene with
  // lots of bogus textures.
  static const int num_quads_side = 20;
  static const int tex_x_size = 256;
  static const int tex_y_size = 256;

  cerr << "Loading " << num_quads_side * num_quads_side << " textures at "
       << tex_x_size << ", " << tex_y_size << "\n";

  GeomNode *gnode = new GeomNode("quads");
  bogus_scene.attach_new_node(gnode);

  PTA_Colorf colors;
  colors.push_back(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  for (int yi = 0; yi < num_quads_side; yi++) {
    float y0 = (float)yi / (float)num_quads_side;
    float y1 = (float)(yi + 1) / (float)num_quads_side;
    for (int xi = 0; xi < num_quads_side; xi++) {
      float x0 = (float)xi / (float)num_quads_side;
      float x1 = (float)(xi + 1) / (float)num_quads_side;

      PNMImage bogus_image(tex_x_size, tex_y_size);
      bogus_image.fill(x0, (xi + yi) & 1, y0);

      PT(Texture) tex = new Texture;
      tex->set_minfilter(Texture::FT_linear_mipmap_linear);
      tex->load(bogus_image);

      PTA_Vertexf coords;
      PTA_TexCoordf uvs;
      coords.push_back(Vertexf(x0, 0.0f, y0));
      coords.push_back(Vertexf(x1, 0.0f, y0));
      coords.push_back(Vertexf(x1, 0.0f, y1));
      coords.push_back(Vertexf(x0, 0.0f, y1));
      uvs.push_back(TexCoordf(0.0f, 0.0f));
      uvs.push_back(TexCoordf(1.0f, 0.0f));
      uvs.push_back(TexCoordf(1.0f, 1.0f));
      uvs.push_back(TexCoordf(0.0f, 1.0f));

      PT(GeomQuad) quad = new GeomQuad;
      quad->set_coords(coords);
      quad->set_colors(colors, G_OVERALL);
      quad->set_num_prims(1);
      quad->set_texcoords(uvs, G_PER_VERTEX);
      gnode->add_geom(quad, RenderState::make(TextureAttrib::make(tex)));
    }
  }

  cerr << "Done.\n";
}

int
main(int argc, char *argv[]) {
  PandaFramework framework;
  framework.open_framework(argc, argv);
  framework.set_window_title("Panda Viewer");

  WindowFramework *window = framework.open_window();
  if (window != (WindowFramework *)NULL) {
    // We've successfully opened a window.

    window->enable_keyboard();
    window->setup_trackball();
    framework.get_models().instance_to(window->get_render());
    if (argc < 2) {
      // If we have no arguments, get that trusty old triangle out.
      window->load_default_model(framework.get_models());
    } else {
      window->load_models(framework.get_models(), argc, argv);
    }
    window->loop_animations();

    framework.enable_default_keys();
    framework.get_event_handler().add_hook("shift-t", event_T, &framework);
    framework.main_loop();
  }

  framework.report_frame_rate(nout);
  return (0);
}
<commit_msg>test_texmem<commit_after>// Filename: test_texmem.cxx
// Created by:  drose (03Sep02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "pandaFramework.h"
#include "geomQuad.h"
#include "textureAttrib.h"
#include "cmath.h"
#include "mathNumbers.h"

NodePath bogus_scene;

void
event_T(CPT_Event, void *data) {
  PandaFramework *framework = (PandaFramework *)data;
  WindowFramework *wf = framework->get_window(0);

  GraphicsStateGuardian *gsg = wf->get_graphics_window()->get_gsg();
  Camera *camera = wf->get_camera(0);
  NodePath models = framework->get_models();
  NodePath render = wf->get_render();

  if (!bogus_scene.is_empty()) {
    // We are undoing a previous shift-t.
    bogus_scene.remove_node();
    models.show();
    return;
  }

  // We are doing a new shift-t.  Hide the normal models, and create a
  // new bogus node to show the texture grid object.
  models.hide();
  bogus_scene = render.attach_new_node("bogus");

  // Try to force a flush of the texture memory by making a scene with
  // lots of bogus textures.
  static const int num_quads_side = 20;
  static const int tex_x_size = 256;
  static const int tex_y_size = 256;

  cerr << "Loading " << num_quads_side * num_quads_side << " textures at "
       << tex_x_size << ", " << tex_y_size << "\n";

  GeomNode *gnode = new GeomNode("quads");
  bogus_scene.attach_new_node(gnode);

  PNMImage white_center(tex_x_size / 4, tex_y_size / 4);
  white_center.fill(1.0f, 1.0f, 1.0f);

  PTA_Colorf colors;
  colors.push_back(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  for (int yi = 0; yi < num_quads_side; yi++) {
    float y0 = (float)yi / (float)num_quads_side;
    float y1 = (float)(yi + 1) / (float)num_quads_side;

    // Map the x, y vertices onto a sphere just for fun.
    float px0 = ccos((y0 - 0.5f) * MathNumbers::pi_f);
    float px1 = ccos((y1 - 0.5f) * MathNumbers::pi_f);
    float py0 = csin((y0 - 0.5f) * MathNumbers::pi_f);
    float py1 = csin((y1 - 0.5f) * MathNumbers::pi_f);
    for (int xi = 0; xi < num_quads_side; xi++) {
      float x0 = (float)xi / (float)num_quads_side;
      float x1 = (float)(xi + 1) / (float)num_quads_side;

      float hx0 = ccos(x0 * MathNumbers::pi_f * 2.0f);
      float hx1 = ccos(x1 * MathNumbers::pi_f * 2.0f);
      float hy0 = csin(x0 * MathNumbers::pi_f * 2.0f);
      float hy1 = csin(x1 * MathNumbers::pi_f * 2.0f);

      PNMImage bogus_image(tex_x_size, tex_y_size);
      bogus_image.fill(x0, (xi + yi) & 1, y0);
      bogus_image.copy_sub_image(white_center,
                                 (tex_x_size - white_center.get_x_size()) / 2,
                                 (tex_y_size - white_center.get_y_size()) / 2);

      PT(Texture) tex = new Texture;
      tex->set_minfilter(Texture::FT_linear_mipmap_linear);
      tex->load(bogus_image);

      PTA_Vertexf coords;
      PTA_TexCoordf uvs;
      coords.push_back(Vertexf(hx0 * px0, hy0 * px0, py0));
      coords.push_back(Vertexf(hx1 * px0, hy1 * px0, py0));
      coords.push_back(Vertexf(hx1 * px1, hy1 * px1, py1));
      coords.push_back(Vertexf(hx0 * px1, hy0 * px1, py1));
      uvs.push_back(TexCoordf(0.0f, 0.0f));
      uvs.push_back(TexCoordf(1.0f, 0.0f));
      uvs.push_back(TexCoordf(1.0f, 1.0f));
      uvs.push_back(TexCoordf(0.0f, 1.0f));

      PT(GeomQuad) quad = new GeomQuad;
      quad->set_coords(coords);
      quad->set_colors(colors, G_OVERALL);
      quad->set_num_prims(1);
      quad->set_texcoords(uvs, G_PER_VERTEX);
      gnode->add_geom(quad, RenderState::make(TextureAttrib::make(tex)));
    }
  }
  cerr << "Done.\n";
}

int
main(int argc, char *argv[]) {
  PandaFramework framework;
  framework.open_framework(argc, argv);
  framework.set_window_title("Panda Viewer");

  WindowFramework *window = framework.open_window();
  if (window != (WindowFramework *)NULL) {
    // We've successfully opened a window.

    window->enable_keyboard();
    window->setup_trackball();
    framework.get_models().instance_to(window->get_render());
    if (argc < 2) {
      // If we have no arguments, get that trusty old triangle out.
      window->load_default_model(framework.get_models());
    } else {
      window->load_models(framework.get_models(), argc, argv);
    }
    window->loop_animations();

    framework.enable_default_keys();
    framework.get_event_handler().add_hook("shift-t", event_T, &framework);
    framework.main_loop();
  }

  framework.report_frame_rate(nout);
  return (0);
}
<|endoftext|>