<commit_before>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-5-20 21:54:52
 * 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 <random> // random_device rd; mt19937 mt(rd());
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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;

int N;
ll A[200010];
bool ok[200010];

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  if (A[0] != 0)
  {
    cout << "-1" << endl;
    return 0;
  }
  for (auto i = 1; i < N; i++)
  {
    if (A[i - 1] + 1 == A[i])
    {
      cerr << "A[" << i - 1 << "] = " << A[i - 1] << endl;
      A[i - 1] = true;
    }
    else
    {
      A[i - 1] = false;
    }
  }
  A[N - 1] = false;
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    if (!ok[i])
    {
      ans += A[i];
    }
  }
  cout << ans << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-5-20 21:54:52
 * 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 <random> // random_device rd; mt19937 mt(rd());
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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;

int N;
ll A[200010];
bool ok[200010];

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  if (A[0] != 0)
  {
    cout << "-1" << endl;
    return 0;
  }
  for (auto i = 1; i < N; i++)
  {
    if (A[i - 1] + 1 == A[i])
    {
      cerr << "A[" << i - 1 << "] = " << A[i - 1] << endl;
      A[i - 1] = true;
    }
    else
    {
      A[i - 1] = false;
    }
  }
  A[N - 1] = false;
  ll ans = 0;
  for (auto i = 0; i < N; i++)
  {
    if (!ok[i])
    {
      cerr << A[i] << endl;
      ans += A[i];
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 3/23/2019, 10:22:47 PM
 * 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;

int N;
vector<vector<int>> V;
typedef tuple<int, int> edge;
vector<edge> E;

void flush()
{
  int S = V.size();
  for (auto i = 0; i < S; i++)
  {
    for (auto j = i + 1; j < S; j++)
    {
      for (auto x : V[i])
      {
        for (auto y : V[j])
        {
          E.push_back(edge(x, y));
        }
      }
    }
  }
}

int main()
{
  cin >> N;
  if (N % 2 == 0)
  {
    for (auto i = 1; i <= N / 2; i++)
    {
      V.push_back({i, N + 1 - i});
    }
  }
  else
  {
    V.push_back({N});
    N--;
    for (auto i = 1; i <= N / 2; i++)
    {
      V.push_back({i, N + 1 - i});
    }
  }
  flush();
}<commit_msg>tried B.cpp to 'B'<commit_after>#define DEBUG 1

/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 3/23/2019, 10:22:47 PM
 * 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;

int N;
vector<vector<int>> V;
typedef tuple<int, int> edge;
vector<edge> E;

void flush()
{
  int S = V.size();
  for (auto i = 0; i < S; i++)
  {
    for (auto j = i + 1; j < S; j++)
    {
      for (auto x : V[i])
      {
        for (auto y : V[j])
        {
          E.push_back(edge(x, y));
        }
      }
    }
  }
  for (auto x : E)
  {
    cout << get<0>(x) << " " << get<1>(x) << endl;
  }
}

int main()
{
  cin >> N;
  if (N % 2 == 0)
  {
    for (auto i = 1; i <= N / 2; i++)
    {
      V.push_back({i, N + 1 - i});
    }
  }
  else
  {
    V.push_back({N});
    N--;
    for (auto i = 1; i <= N / 2; i++)
    {
      V.push_back({i, N + 1 - i});
    }
  }
  flush();
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 7/7/2019, 9:06:20 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % 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*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= 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; }
  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;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

constexpr ll C = 2019;

ll up(ll x)
{
  for (auto i = 0; i <= C; i++)
  {
    if (x + i % C == 0)
    {
      return x + i;
    }
  }
  return -1;
}

void zero()
{
  cout << 0 << endl;
  exit(0);
}

ll L, R;

int main()
{
  // init();
  cin >> L >> R;
  ll t = up(L);
#if DEBUG == 1
  cerr << "up(" << L << ") = " << t << endl;
#endif
  if (t <= R)
  {
    zero();
  }
  ll ans = C;
  for (auto i = L; i <= R; i++)
  {
    for (auto j = i + 1; j <= R; j++)
    {
      ll t = (i * j) % C;
      mins(ans, t);
    }
  }
  cout << ans << endl;
}<commit_msg>submit C.cpp to 'C - Remainder Minimization 2019' (abc133) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 7/7/2019, 9:06:20 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % 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*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= 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; }
  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;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

constexpr ll C = 2019;

ll up(ll x)
{
  for (auto i = 0; i <= C; i++)
  {
    if ((x + i) % C == 0)
    {
      return x + i;
    }
  }
  return -1;
}

void zero()
{
  cout << 0 << endl;
  exit(0);
}

ll L, R;

int main()
{
  // init();
  cin >> L >> R;
  ll t = up(L);
#if DEBUG == 1
  cerr << "up(" << L << ") = " << t << endl;
#endif
  if (t <= R)
  {
    zero();
  }
  ll ans = C;
  for (auto i = L; i <= R; i++)
  {
    for (auto j = i + 1; j <= R; j++)
    {
      ll t = (i * j) % C;
      mins(ans, t);
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2007-03-16
// Updated : 2008-10-24
// Licence : This source is under MIT License
// File    : glm/gtx/compatibility.inl
///////////////////////////////////////////////////////////////////////////////////////////////////

namespace glm{
namespace gtx{
namespace compatibility{

// isfinite
template <typename genType>
inline bool isfinite(
	genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _finite(x);
#else//(GLM_COMPILER & GLM_COMPILER_GCC)
	return std::isfinite(x);
#endif
}

template <typename valType>
inline detail::tvec2<bool> isfinite(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isfinite(x.x),
		isfinite(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isfinite(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isfinite(x.x),
		isfinite(x.y),
		isfinite(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isfinite(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isfinite(x.x),
		isfinite(x.y),
		isfinite(x.z),
		isfinite(x.w));
}

// isinf
template <typename genType>
inline bool isinf(
	genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _fpclass(x) == _FPCLASS_NINF || _fpclass(x) == _FPCLASS_PINF;
#else
	return std::isinf(x);
#endif
}

template <typename valType>
inline detail::tvec2<bool> isinf(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isinf(x.x),
		isinf(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isinf(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isinf(x.x),
		isinf(x.y),
		isinf(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isinf(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isinf(x.x),
		isinf(x.y),
		isinf(x.z),
		isinf(x.w));
}

// isnan
template <typename genType>
inline bool isnan(genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _isnan(x);
#else
	return std::isnan(x);
#endif
}

template <typename valType>
inline detail::tvec2<bool> isnan(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isnan(x.x),
		isnan(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isnan(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isnan(x.x),
		isnan(x.y),
		isnan(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isnan(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isnan(x.x),
		isnan(x.y),
		isnan(x.z),
		isnan(x.w));
}

}//namespace compatibility
}//namespace gtx
}//namespace glm
<commit_msg>Fixed warnings, ticket #79<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2007-03-16
// Updated : 2008-10-24
// Licence : This source is under MIT License
// File    : glm/gtx/compatibility.inl
///////////////////////////////////////////////////////////////////////////////////////////////////

namespace glm{
namespace gtx{
namespace compatibility{

// isfinite
template <typename genType>
inline bool isfinite(
	genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _finite(x);
#else//(GLM_COMPILER & GLM_COMPILER_GCC)
	return std::isfinite(x) != 0;
#endif
}

template <typename valType>
inline detail::tvec2<bool> isfinite(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isfinite(x.x),
		isfinite(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isfinite(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isfinite(x.x),
		isfinite(x.y),
		isfinite(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isfinite(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isfinite(x.x),
		isfinite(x.y),
		isfinite(x.z),
		isfinite(x.w));
}

// isinf
template <typename genType>
inline bool isinf(
	genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _fpclass(x) == _FPCLASS_NINF || _fpclass(x) == _FPCLASS_PINF;
#else
	return std::isinf(x) != 0;
#endif
}

template <typename valType>
inline detail::tvec2<bool> isinf(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isinf(x.x),
		isinf(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isinf(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isinf(x.x),
		isinf(x.y),
		isinf(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isinf(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isinf(x.x),
		isinf(x.y),
		isinf(x.z),
		isinf(x.w));
}

// isnan
template <typename genType>
inline bool isnan(genType const & x)
{
#if(GLM_COMPILER & GLM_COMPILER_VC)
	return _isnan(x);
#else
	return std::isnan(x) != 0;
#endif
}

template <typename valType>
inline detail::tvec2<bool> isnan(
	detail::tvec2<valType> const & x)
{
	return detail::tvec2<bool>(
		isnan(x.x),
		isnan(x.y));
}

template <typename valType>
inline detail::tvec3<bool> isnan(
	detail::tvec3<valType> const & x)
{
	return detail::tvec3<bool>(
		isnan(x.x),
		isnan(x.y),
		isnan(x.z));
}

template <typename valType>
inline detail::tvec4<bool> isnan(
	detail::tvec4<valType> const & x)
{
	return detail::tvec4<bool>(
		isnan(x.x),
		isnan(x.y),
		isnan(x.z),
		isnan(x.w));
}

}//namespace compatibility
}//namespace gtx
}//namespace glm
<|endoftext|>


<commit_before>// Copyright (c) 2020 The Novo developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the NOVO software license, see the accompanying
// file COPYING

//Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage)
#ifdef DLL_EXPORT
#undef DLL_EXPORT
#endif

#include "appname.h"
#include "net.h"
#include "net_processing.h"
#include "validation/validation.h"
#include "ui_interface.h"
#include "utilstrencodings.h"

#include <wallet/wallet.h>
#include <wallet/account.h>
#include <wallet/witness_operations.h>

// Unity specific includes
#include "../unity_impl.h"
#include "i_wallet_controller.hpp"
#include "i_wallet_listener.hpp"
#include "account_record.hpp"

std::shared_ptr<IWalletListener> walletListener;

// rate limited mutations notifier
static CRateLimit<std::pair<uint256, bool>>* walletNewMutationsNotifier=nullptr;
// rate limited balance change notifier
static CRateLimit<int>* walletBalanceChangeNotifier=nullptr;

void IWalletController::setListener(const std::shared_ptr<IWalletListener>& walletListener_)
{
    walletListener = walletListener_;

    if (pactiveWallet && walletListener)
    {
        walletBalanceChangeNotifier = new CRateLimit<int>([](int)
        {
            if (pactiveWallet && walletListener)
            {
                WalletBalances balances;
                pactiveWallet->GetBalances(balances, nullptr, true);
                walletListener->notifyBalanceChange(BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked));
            }
        }, std::chrono::milliseconds(BALANCE_NOTIFY_THRESHOLD_MS));

        walletNewMutationsNotifier = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo)
        {
            if (pactiveWallet && walletListener)
            {
                const uint256& txHash = txInfo.first;
                const bool fSelfComitted = txInfo.second;

                LOCK2(cs_main, pactiveWallet->cs_wallet);
                if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end())
                {
                    const CWalletTx& wtx = pactiveWallet->mapWallet[txHash];
                    std::vector<MutationRecord> mutations;
                    addMutationsForTransaction(&wtx, mutations, nullptr);
                    for (auto& m: mutations)
                    {
                        LogPrintf("unity: notify new wallet mutation for tx %s", txHash.ToString().c_str());
                        walletListener->notifyNewMutation(m, fSelfComitted);
                    }
                }
            }
        }, std::chrono::milliseconds(NEW_MUTATIONS_NOTIFY_THRESHOLD_MS));

        // Fire events for transaction depth changes (up to depth 10 only)
        pactiveWallet->NotifyTransactionDepthChanged.connect( [&](CWallet* pwallet, const uint256& hash)
        {
            DS_LOCK2(cs_main, pwallet->cs_wallet);
            if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
            {
                const CWalletTx& wtx = pwallet->mapWallet[hash];
                LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str());
                if (walletListener)
                {
                    bool anyInputsOrOutputsAreMine = false;
                    std::vector<CAccount*> forAccounts;
                    for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts)
                    {
                        forAccounts.push_back(account);
                    }
                    TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
                    if (anyInputsOrOutputsAreMine)
                    {
                        walletListener->notifyUpdatedTransaction(walletTransaction);
                    }
                }
            }
        } );
        // Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes)
        pactiveWallet->NotifyTransactionChanged.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) {
            DS_LOCK2(cs_main, pwallet->cs_wallet);
            if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
            {
                if (status == CT_NEW) {
                    walletNewMutationsNotifier->trigger(std::make_pair(hash, fSelfComitted));
                }
                else if (status == CT_UPDATED && walletListener)
                {
                    LogPrintf("unity: notify tx updated %s",hash.ToString().c_str());
                    const CWalletTx& wtx = pwallet->mapWallet[hash];
                    bool anyInputsOrOutputsAreMine = false;
                    std::vector<CAccount*> forAccounts;
                    for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts)
                    {
                        forAccounts.push_back(account);
                    }
                    TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
                    if (anyInputsOrOutputsAreMine)
                    {
                        walletListener->notifyUpdatedTransaction(walletTransaction);
                    }
                }
                //fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted...
                // else if (status == CT_DELETED)
            }
            walletBalanceChangeNotifier->trigger(0);
        });
    }
}

bool IWalletController::HaveUnconfirmedFunds()
{
    if (!pactiveWallet)
        return true;

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);

    if (balances.unconfirmedIncludingLocked > 0 || balances.immatureIncludingLocked > 0)
    {
        return true;
    }
    return false;
}

BalanceRecord IWalletController::GetBalance()
{
    if (!pactiveWallet)
        return BalanceRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);
    return BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked);

}

int64_t IWalletController::GetBalanceSimple()
{
    if (!pactiveWallet)
        return 0;

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);
    return balances.availableIncludingLocked + balances.unconfirmedIncludingLocked + balances.immatureIncludingLocked;
}

bool IWalletController::AbandonTransaction(const std::string& txHash)
{
    if (!pactiveWallet)
        return false;

    uint256 hash = uint256S(txHash);
    return pactiveWallet->AbandonTransaction(hash);
}

std::string IWalletController::GetUUID()
{
    if (!pactiveWallet)
        return "";

    return getUUIDAsString(pactiveWallet->getActiveSeed()->getUUID());
}

<commit_msg>QA: Use account instead of seed for wallet UUID<commit_after>// Copyright (c) 2020 The Novo developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the NOVO software license, see the accompanying
// file COPYING

//Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage)
#ifdef DLL_EXPORT
#undef DLL_EXPORT
#endif

#include "appname.h"
#include "net.h"
#include "net_processing.h"
#include "validation/validation.h"
#include "ui_interface.h"
#include "utilstrencodings.h"

#include <wallet/wallet.h>
#include <wallet/account.h>
#include <wallet/witness_operations.h>

// Unity specific includes
#include "../unity_impl.h"
#include "i_wallet_controller.hpp"
#include "i_wallet_listener.hpp"
#include "account_record.hpp"

std::shared_ptr<IWalletListener> walletListener;

// rate limited mutations notifier
static CRateLimit<std::pair<uint256, bool>>* walletNewMutationsNotifier=nullptr;
// rate limited balance change notifier
static CRateLimit<int>* walletBalanceChangeNotifier=nullptr;

void IWalletController::setListener(const std::shared_ptr<IWalletListener>& walletListener_)
{
    walletListener = walletListener_;

    if (pactiveWallet && walletListener)
    {
        walletBalanceChangeNotifier = new CRateLimit<int>([](int)
        {
            if (pactiveWallet && walletListener)
            {
                WalletBalances balances;
                pactiveWallet->GetBalances(balances, nullptr, true);
                walletListener->notifyBalanceChange(BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked));
            }
        }, std::chrono::milliseconds(BALANCE_NOTIFY_THRESHOLD_MS));

        walletNewMutationsNotifier = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo)
        {
            if (pactiveWallet && walletListener)
            {
                const uint256& txHash = txInfo.first;
                const bool fSelfComitted = txInfo.second;

                LOCK2(cs_main, pactiveWallet->cs_wallet);
                if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end())
                {
                    const CWalletTx& wtx = pactiveWallet->mapWallet[txHash];
                    std::vector<MutationRecord> mutations;
                    addMutationsForTransaction(&wtx, mutations, nullptr);
                    for (auto& m: mutations)
                    {
                        LogPrintf("unity: notify new wallet mutation for tx %s", txHash.ToString().c_str());
                        walletListener->notifyNewMutation(m, fSelfComitted);
                    }
                }
            }
        }, std::chrono::milliseconds(NEW_MUTATIONS_NOTIFY_THRESHOLD_MS));

        // Fire events for transaction depth changes (up to depth 10 only)
        pactiveWallet->NotifyTransactionDepthChanged.connect( [&](CWallet* pwallet, const uint256& hash)
        {
            DS_LOCK2(cs_main, pwallet->cs_wallet);
            if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
            {
                const CWalletTx& wtx = pwallet->mapWallet[hash];
                LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str());
                if (walletListener)
                {
                    bool anyInputsOrOutputsAreMine = false;
                    std::vector<CAccount*> forAccounts;
                    for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts)
                    {
                        forAccounts.push_back(account);
                    }
                    TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
                    if (anyInputsOrOutputsAreMine)
                    {
                        walletListener->notifyUpdatedTransaction(walletTransaction);
                    }
                }
            }
        } );
        // Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes)
        pactiveWallet->NotifyTransactionChanged.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) {
            DS_LOCK2(cs_main, pwallet->cs_wallet);
            if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
            {
                if (status == CT_NEW) {
                    walletNewMutationsNotifier->trigger(std::make_pair(hash, fSelfComitted));
                }
                else if (status == CT_UPDATED && walletListener)
                {
                    LogPrintf("unity: notify tx updated %s",hash.ToString().c_str());
                    const CWalletTx& wtx = pwallet->mapWallet[hash];
                    bool anyInputsOrOutputsAreMine = false;
                    std::vector<CAccount*> forAccounts;
                    for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts)
                    {
                        forAccounts.push_back(account);
                    }
                    TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
                    if (anyInputsOrOutputsAreMine)
                    {
                        walletListener->notifyUpdatedTransaction(walletTransaction);
                    }
                }
                //fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted...
                // else if (status == CT_DELETED)
            }
            walletBalanceChangeNotifier->trigger(0);
        });
    }
}

bool IWalletController::HaveUnconfirmedFunds()
{
    if (!pactiveWallet)
        return true;

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);

    if (balances.unconfirmedIncludingLocked > 0 || balances.immatureIncludingLocked > 0)
    {
        return true;
    }
    return false;
}

BalanceRecord IWalletController::GetBalance()
{
    if (!pactiveWallet)
        return BalanceRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);
    return BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked);

}

int64_t IWalletController::GetBalanceSimple()
{
    if (!pactiveWallet)
        return 0;

    WalletBalances balances;
    pactiveWallet->GetBalances(balances, nullptr, true);
    return balances.availableIncludingLocked + balances.unconfirmedIncludingLocked + balances.immatureIncludingLocked;
}

bool IWalletController::AbandonTransaction(const std::string& txHash)
{
    if (!pactiveWallet)
        return false;

    uint256 hash = uint256S(txHash);
    return pactiveWallet->AbandonTransaction(hash);
}

std::string IWalletController::GetUUID()
{
    if (!pactiveWallet || !pactiveWallet->getActiveAccount())
        return "";

    return getUUIDAsString(pactiveWallet->getActiveAccount()->getUUID());
}

<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 <https://www.gnu.org/licenses/>.
//

#include "host/ui/host_main.h"

#include "base/command_line.h"
#include "base/sys_info.h"
#include "build/version.h"
#include "host/integrity_check.h"
#include "host/system_settings.h"
#include "host/ui/application.h"
#include "host/ui/main_window.h"
#include "host/ui/settings_util.h"
#include "common/ui/update_dialog.h"
#include "qt_base/scoped_qt_logging.h"

#if defined(OS_WIN)
#include "base/win/mini_dump_writer.h"
#include "base/win/process_util.h"
#include "base/win/scoped_thread_desktop.h"
#endif // defined(OS_WIN)

#include <QMessageBox>

namespace {

bool waitForValidInputDesktop()
{
    int max_attempt_count = 600;

    do
    {
        base::Desktop input_desktop(base::Desktop::inputDesktop());
        if (input_desktop.isValid())
        {
            if (input_desktop.setThreadDesktop())
                break;
        }

        Sleep(100);
    }
    while (--max_attempt_count > 0);

    if (max_attempt_count == 0)
    {
        LOG(LS_WARNING) << "Exceeded the number of attempts";
        return false;
    }

    return true;
}

} // namespace

int hostMain(int argc, char* argv[])
{
    Q_INIT_RESOURCE(qt_translations);
    Q_INIT_RESOURCE(common);
    Q_INIT_RESOURCE(common_translations);

#if defined(OS_WIN)
    base::installFailureHandler(L"aspia_host");
#endif

    qt_base::ScopedQtLogging scoped_logging;
    base::CommandLine command_line(argc, argv);

    LOG(LS_INFO) << "Version: " << ASPIA_VERSION_STRING;
    LOG(LS_INFO) << "Command line: " << command_line.commandLineString();
    LOG(LS_INFO) << "OS: " << base::SysInfo::operatingSystemName()
                 << " (version: " << base::SysInfo::operatingSystemVersion()
                 <<  " arch: " << base::SysInfo::operatingSystemArchitecture() << ")";
    LOG(LS_INFO) << "CPU: " << base::SysInfo::processorName()
                 << " (vendor: " << base::SysInfo::processorVendor()
                 << " packages: " << base::SysInfo::processorPackages()
                 << " cores: " << base::SysInfo::processorCores()
                 << " threads: " << base::SysInfo::processorThreads() << ")";

    bool is_hidden = command_line.hasSwitch(u"hidden");
    if (!is_hidden)
    {
        LOG(LS_INFO) << "No 'hidden' switch";

        if (!base::win::isProcessElevated())
        {
            LOG(LS_INFO) << "Process not elevated";

            if (base::win::createProcess(command_line, base::win::ProcessExecuteMode::ELEVATE))
                return 0;
        }
        else
        {
            LOG(LS_INFO) << "Process elevated";
        }
    }
    else
    {
        LOG(LS_INFO) << "Has 'hidden' switch";

        if (!waitForValidInputDesktop())
            return 1;
    }

    host::Application::setAttribute(Qt::AA_EnableHighDpiScaling, true);
    host::Application::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    host::Application application(argc, argv);

    if (!host::integrityCheck())
    {
        LOG(LS_WARNING) << "Integrity check failed";

        QMessageBox::warning(
            nullptr,
            QApplication::translate("Host", "Warning"),
            QApplication::translate("Host", "Application integrity check failed. Components are "
                                            "missing or damaged."),
            QMessageBox::Ok);
        return 1;
    }
    else
    {
        LOG(LS_INFO) << "Integrity check passed successfully";
    }

    if (command_line.hasSwitch(u"import") && command_line.hasSwitch(u"export"))
    {
        LOG(LS_WARNING) << "Import and export are specified at the same time";

        if (!command_line.hasSwitch(u"silent"))
        {
            QMessageBox::warning(
                nullptr,
                QApplication::translate("Host", "Warning"),
                QApplication::translate("Host", "Export and import parameters can not be specified together."),
                QMessageBox::Ok);
        }

        return 1;
    }
    else if (command_line.hasSwitch(u"import"))
    {
        if (!host::SettingsUtil::importFromFile(command_line.switchValuePath(u"import"),
                                                command_line.hasSwitch(u"silent")))
        {
            return 1;
        }
    }
    else if (command_line.hasSwitch(u"export"))
    {
        if (!host::SettingsUtil::exportToFile(command_line.switchValuePath(u"export"),
                                              command_line.hasSwitch(u"silent")))
        {
            return 1;
        }
    }
    else if (command_line.hasSwitch(u"update"))
    {
        common::UpdateDialog dialog(
            QString::fromStdU16String(host::SystemSettings().updateServer()), "host");
        dialog.show();
        dialog.activateWindow();

        return application.exec();
    }
    else if (command_line.hasSwitch(u"help"))
    {
        // TODO
    }
    else
    {
        if (application.isRunning())
        {
            LOG(LS_INFO) << "Application already running";
            application.activate();
        }
        else
        {
            LOG(LS_INFO) << "Application not running yet";

            host::MainWindow window;
            QObject::connect(&application, &host::Application::activated,
                             &window, &host::MainWindow::activateHost);

            if (is_hidden)
            {
                LOG(LS_INFO) << "Hide window to tray";
                window.hideToTray();
            }
            else
            {
                LOG(LS_INFO) << "Show window";
                window.show();
                window.activateWindow();
            }

            window.connectToService();

            return application.exec();
        }
    }

    return 0;
}
<commit_msg>Improve debug messages.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 <https://www.gnu.org/licenses/>.
//

#include "host/ui/host_main.h"

#include "base/command_line.h"
#include "base/sys_info.h"
#include "build/version.h"
#include "host/integrity_check.h"
#include "host/system_settings.h"
#include "host/ui/application.h"
#include "host/ui/main_window.h"
#include "host/ui/settings_util.h"
#include "common/ui/update_dialog.h"
#include "qt_base/scoped_qt_logging.h"

#if defined(OS_WIN)
#include "base/win/mini_dump_writer.h"
#include "base/win/process_util.h"
#include "base/win/scoped_thread_desktop.h"
#endif // defined(OS_WIN)

#include <QMessageBox>

namespace {

bool waitForValidInputDesktop()
{
    int max_attempt_count = 600;

    do
    {
        base::Desktop input_desktop(base::Desktop::inputDesktop());
        if (input_desktop.isValid())
        {
            if (input_desktop.setThreadDesktop())
                break;
        }

        Sleep(100);
    }
    while (--max_attempt_count > 0);

    if (max_attempt_count == 0)
    {
        LOG(LS_WARNING) << "Exceeded the number of attempts";
        return false;
    }

    return true;
}

} // namespace

int hostMain(int argc, char* argv[])
{
    Q_INIT_RESOURCE(qt_translations);
    Q_INIT_RESOURCE(common);
    Q_INIT_RESOURCE(common_translations);

#if defined(OS_WIN)
    base::installFailureHandler(L"aspia_host");
#endif

    qt_base::ScopedQtLogging scoped_logging;
    base::CommandLine command_line(argc, argv);

    LOG(LS_INFO) << "Version: " << ASPIA_VERSION_STRING;
    LOG(LS_INFO) << "Command line: " << command_line.commandLineString();
    LOG(LS_INFO) << "OS: " << base::SysInfo::operatingSystemName()
                 << " (version: " << base::SysInfo::operatingSystemVersion()
                 <<  " arch: " << base::SysInfo::operatingSystemArchitecture() << ")";
    LOG(LS_INFO) << "CPU: " << base::SysInfo::processorName()
                 << " (vendor: " << base::SysInfo::processorVendor()
                 << " packages: " << base::SysInfo::processorPackages()
                 << " cores: " << base::SysInfo::processorCores()
                 << " threads: " << base::SysInfo::processorThreads() << ")";

    bool is_hidden = command_line.hasSwitch(u"hidden");
    if (!is_hidden)
    {
        LOG(LS_INFO) << "No 'hidden' switch";

        if (!base::win::isProcessElevated())
        {
            LOG(LS_INFO) << "Process not elevated yet";

            if (base::win::createProcess(command_line, base::win::ProcessExecuteMode::ELEVATE))
            {
                LOG(LS_INFO) << "Elevated process started";
                return 0;
            }
        }
        else
        {
            LOG(LS_INFO) << "Process already elevated";
        }
    }
    else
    {
        LOG(LS_INFO) << "Has 'hidden' switch";

        if (!waitForValidInputDesktop())
            return 1;
    }

    host::Application::setAttribute(Qt::AA_EnableHighDpiScaling, true);
    host::Application::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    host::Application application(argc, argv);

    if (!host::integrityCheck())
    {
        LOG(LS_WARNING) << "Integrity check failed";

        QMessageBox::warning(
            nullptr,
            QApplication::translate("Host", "Warning"),
            QApplication::translate("Host", "Application integrity check failed. Components are "
                                            "missing or damaged."),
            QMessageBox::Ok);
        return 1;
    }
    else
    {
        LOG(LS_INFO) << "Integrity check passed successfully";
    }

    if (command_line.hasSwitch(u"import") && command_line.hasSwitch(u"export"))
    {
        LOG(LS_WARNING) << "Import and export are specified at the same time";

        if (!command_line.hasSwitch(u"silent"))
        {
            QMessageBox::warning(
                nullptr,
                QApplication::translate("Host", "Warning"),
                QApplication::translate("Host", "Export and import parameters can not be specified together."),
                QMessageBox::Ok);
        }

        return 1;
    }
    else if (command_line.hasSwitch(u"import"))
    {
        if (!host::SettingsUtil::importFromFile(command_line.switchValuePath(u"import"),
                                                command_line.hasSwitch(u"silent")))
        {
            return 1;
        }
    }
    else if (command_line.hasSwitch(u"export"))
    {
        if (!host::SettingsUtil::exportToFile(command_line.switchValuePath(u"export"),
                                              command_line.hasSwitch(u"silent")))
        {
            return 1;
        }
    }
    else if (command_line.hasSwitch(u"update"))
    {
        common::UpdateDialog dialog(
            QString::fromStdU16String(host::SystemSettings().updateServer()), "host");
        dialog.show();
        dialog.activateWindow();

        return application.exec();
    }
    else if (command_line.hasSwitch(u"help"))
    {
        // TODO
    }
    else
    {
        if (application.isRunning())
        {
            LOG(LS_INFO) << "Application already running";
            application.activate();
        }
        else
        {
            LOG(LS_INFO) << "Application not running yet";

            host::MainWindow window;
            QObject::connect(&application, &host::Application::activated,
                             &window, &host::MainWindow::activateHost);

            if (is_hidden)
            {
                LOG(LS_INFO) << "Hide window to tray";
                window.hideToTray();
            }
            else
            {
                LOG(LS_INFO) << "Show window";
                window.show();
                window.activateWindow();
            }

            window.connectToService();

            return application.exec();
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <syslog.h>
#include <mpd/status.h>

#include "monitor.h"

using namespace mpc_lcd;

Monitor::Monitor()
{
	Adafruit_SSD1306 display;
	MPClient_cb mpc_client;
}

int Monitor::setup_display()
{
	if (display.init_i2c() != 0) {
		return 2;
	}

	display.clearDisplay();

	display.setTextSize(1);
	display.setTextColor(WHITE);
	display.setCursor(0,0);
	// display.write('t');
	// display.drawCircle(3, 3, 8, WHITE);
	display.display();

	return 0;
}

int Monitor::setup_mpc()
{
	if (mpc_client.connect() != 0) {
		return 3;
	}

	return 0;
}

void Monitor::watch_loop()
{
	mpc_client.update_status();
	on_player();

	void (Monitor::*playerCB)() = &Monitor::on_player;
	mpc_client.set_callback_player(this, playerCB);

	mpc_client.loop();
}

void Monitor::on_player()
{
	display.clearDisplay();
	display.setTextColor(WHITE);
	display.setTextSize(1);
	display.setTextWrap(true);
	switch (mpc_client.get_info_state()) {
		case MPD_STATE_STOP:
			display.fillRect(0, 0, 6, 6, WHITE);
			break;
		case MPD_STATE_PLAY:
			display.fillTriangle(0, 0, 6, 3, 0, 6, WHITE);
			break;
		case MPD_STATE_PAUSE:
			display.fillRect(0, 0, 2, 6, WHITE);
			display.fillRect(4, 0, 2, 6, WHITE);
			break;
	}

	uint16_t mpc_sample_rate = mpc_client.get_info_sample_rate();
	uint16_t mpc_bits = mpc_client.get_info_bits();
	uint8_t mpc_channels = mpc_client.get_info_channels();
	std::string mpc_title = mpc_client.get_info_title();
	std::string mpc_album = mpc_client.get_info_album();

	display.setCursor(0,10);
	if (mpc_sample_rate > 0) {
		display.printf("%iHz", mpc_sample_rate);
		if (mpc_bits > 0) {
			display.printf("/%ibit", mpc_bits);
			if (mpc_channels == 1) {
				display.print("/mono");
			} else if (mpc_channels == 2) {
				display.print("/stereo");
			} else if (mpc_channels > 2) {
				display.print("/multi-channel");
			}
		}
	}

	display.setCursor(0, 19);
	if (!mpc_title.empty()) {
		display.print(mpc_title.c_str());
		syslog(LOG_DAEMON|LOG_INFO, "title: %s\n", mpc_title.c_str());
		printf("title: %s\n", mpc_title.c_str());
	} else if (!mpc_album.empty()) {
		display.print(mpc_album.c_str());
		syslog(LOG_DAEMON|LOG_INFO, "album: %s\n", mpc_album.c_str());
		printf("album: %s\n", mpc_album.c_str());
	}

	display.display();
}

void Monitor::update_status()
{
	mpc_client.update_status();
}

<commit_msg>Dim LCD a little<commit_after>#include <syslog.h>
#include <mpd/status.h>

#include "monitor.h"

using namespace mpc_lcd;

Monitor::Monitor()
{
	Adafruit_SSD1306 display;
	MPClient_cb mpc_client;
}

int Monitor::setup_display()
{
	if (display.init_i2c() != 0) {
		return 2;
	}

	display.dim(1);
	display.clearDisplay();

	display.setTextSize(1);
	display.setTextColor(WHITE);
	display.setCursor(0,0);
	// display.write('t');
	// display.drawCircle(3, 3, 8, WHITE);
	display.display();

	return 0;
}

int Monitor::setup_mpc()
{
	if (mpc_client.connect() != 0) {
		return 3;
	}

	return 0;
}

void Monitor::watch_loop()
{
	mpc_client.update_status();
	on_player();

	void (Monitor::*playerCB)() = &Monitor::on_player;
	mpc_client.set_callback_player(this, playerCB);

	mpc_client.loop();
}

void Monitor::on_player()
{
	display.clearDisplay();
	display.setTextColor(WHITE);
	display.setTextSize(1);
	display.setTextWrap(true);
	switch (mpc_client.get_info_state()) {
		case MPD_STATE_STOP:
			display.fillRect(0, 0, 6, 6, WHITE);
			break;
		case MPD_STATE_PLAY:
			display.fillTriangle(0, 0, 6, 3, 0, 6, WHITE);
			break;
		case MPD_STATE_PAUSE:
			display.fillRect(0, 0, 2, 6, WHITE);
			display.fillRect(4, 0, 2, 6, WHITE);
			break;
	}

	uint16_t mpc_sample_rate = mpc_client.get_info_sample_rate();
	uint16_t mpc_bits = mpc_client.get_info_bits();
	uint8_t mpc_channels = mpc_client.get_info_channels();
	std::string mpc_title = mpc_client.get_info_title();
	std::string mpc_album = mpc_client.get_info_album();

	display.setCursor(0,10);
	if (mpc_sample_rate > 0) {
		display.printf("%iHz", mpc_sample_rate);
		if (mpc_bits > 0) {
			display.printf("/%ibit", mpc_bits);
			if (mpc_channels == 1) {
				display.print("/mono");
			} else if (mpc_channels == 2) {
				display.print("/stereo");
			} else if (mpc_channels > 2) {
				display.print("/multi-channel");
			}
		}
	}

	display.setCursor(0, 19);
	if (!mpc_title.empty()) {
		display.print(mpc_title.c_str());
		syslog(LOG_DAEMON|LOG_INFO, "title: %s\n", mpc_title.c_str());
		printf("title: %s\n", mpc_title.c_str());
	} else if (!mpc_album.empty()) {
		display.print(mpc_album.c_str());
		syslog(LOG_DAEMON|LOG_INFO, "album: %s\n", mpc_album.c_str());
		printf("album: %s\n", mpc_album.c_str());
	}

	display.display();
}

void Monitor::update_status()
{
	mpc_client.update_status();
}

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/LU>

template<typename MatrixType> void lu_non_invertible()
{
  /* this test covers the following files:
     LU.h
  */
  int rows = ei_random<int>(20,200), cols = ei_random<int>(20,200), cols2 = ei_random<int>(20,200);
  int rank = ei_random<int>(1, std::min(rows, cols)-1);

  MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);
  createRandomMatrixOfRank(rank, rows, cols, m1);

  LU<MatrixType> lu(m1);
  typename ei_lu_kernel_impl<MatrixType>::ReturnMatrixType m1kernel = lu.kernel();
  typename ei_lu_image_impl <MatrixType>::ReturnMatrixType m1image  = lu.image();

  // std::cerr << rank << " " << lu.rank() << std::endl;
  VERIFY(rank == lu.rank());
  VERIFY(cols - lu.rank() == lu.dimensionOfKernel());
  VERIFY(!lu.isInjective());
  VERIFY(!lu.isInvertible());
  VERIFY(!lu.isSurjective());
  VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));
  VERIFY(m1image.lu().rank() == rank);
  MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());
  sidebyside << m1, m1image;
  VERIFY(sidebyside.lu().rank() == rank);
  m2 = MatrixType::Random(cols,cols2);
  m3 = m1*m2;
  m2 = MatrixType::Random(cols,cols2);
  // test that the code, which does resize(), may be applied to an xpr
  m2.block(0,0,m2.rows(),m2.cols()) = lu.solve(m3);
  VERIFY_IS_APPROX(m3, m1*m2);

  typedef Matrix<typename MatrixType::Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
  SquareMatrixType m4(rows, rows), m5(rows, rows);
  createRandomMatrixOfRank(rows/2, rows, rows, m4);
  VERIFY(!m4.computeInverseWithCheck(&m5));
}

template<typename MatrixType> void lu_invertible()
{
  /* this test covers the following files:
     LU.h
  */
  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
  int size = ei_random<int>(10,200);

  MatrixType m1(size, size), m2(size, size), m3(size, size);
  m1 = MatrixType::Random(size,size);

  if (ei_is_same_type<RealScalar,float>::ret)
  {
    // let's build a matrix more stable to inverse
    MatrixType a = MatrixType::Random(size,size*2);
    m1 += a * a.adjoint();
  }

  LU<MatrixType> lu(m1);
  VERIFY(0 == lu.dimensionOfKernel());
  VERIFY(size == lu.rank());
  VERIFY(lu.isInjective());
  VERIFY(lu.isSurjective());
  VERIFY(lu.isInvertible());
  VERIFY(lu.image().lu().isInvertible());
  m3 = MatrixType::Random(size,size);
  m2 = lu.solve(m3);
  VERIFY_IS_APPROX(m3, m1*m2);
  VERIFY_IS_APPROX(m2, lu.inverse()*m3);
}

template<typename MatrixType> void lu_verify_assert()
{
  MatrixType tmp;

  LU<MatrixType> lu;
  VERIFY_RAISES_ASSERT(lu.matrixLU())
  VERIFY_RAISES_ASSERT(lu.permutationP())
  VERIFY_RAISES_ASSERT(lu.permutationQ())
  VERIFY_RAISES_ASSERT(lu.kernel())
  VERIFY_RAISES_ASSERT(lu.image())
  VERIFY_RAISES_ASSERT(lu.solve(tmp))
  VERIFY_RAISES_ASSERT(lu.determinant())
  VERIFY_RAISES_ASSERT(lu.rank())
  VERIFY_RAISES_ASSERT(lu.dimensionOfKernel())
  VERIFY_RAISES_ASSERT(lu.isInjective())
  VERIFY_RAISES_ASSERT(lu.isSurjective())
  VERIFY_RAISES_ASSERT(lu.isInvertible())
  VERIFY_RAISES_ASSERT(lu.inverse())

  PartialLU<MatrixType> plu;
  VERIFY_RAISES_ASSERT(plu.matrixLU())
  VERIFY_RAISES_ASSERT(plu.permutationP())
  VERIFY_RAISES_ASSERT(plu.solve(tmp,&tmp))
  VERIFY_RAISES_ASSERT(plu.determinant())
  VERIFY_RAISES_ASSERT(plu.inverse())
}

void test_lu()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( lu_non_invertible<MatrixXf>() );
/*    CALL_SUBTEST( lu_non_invertible<MatrixXd>() );
    CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );
    CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );
    CALL_SUBTEST( lu_invertible<MatrixXf>() );
    CALL_SUBTEST( lu_invertible<MatrixXd>() );
    CALL_SUBTEST( lu_invertible<MatrixXcf>() );
    CALL_SUBTEST( lu_invertible<MatrixXcd>() );*/
  }

/*  CALL_SUBTEST( lu_verify_assert<Matrix3f>() );
  CALL_SUBTEST( lu_verify_assert<Matrix3d>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXf>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXd>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXcf>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXcd>() );*/
}
<commit_msg>oops, didn't want to commit that<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/LU>

template<typename MatrixType> void lu_non_invertible()
{
  /* this test covers the following files:
     LU.h
  */
  int rows = ei_random<int>(20,200), cols = ei_random<int>(20,200), cols2 = ei_random<int>(20,200);
  int rank = ei_random<int>(1, std::min(rows, cols)-1);

  MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);
  createRandomMatrixOfRank(rank, rows, cols, m1);

  LU<MatrixType> lu(m1);
  typename ei_lu_kernel_impl<MatrixType>::ReturnMatrixType m1kernel = lu.kernel();
  typename ei_lu_image_impl <MatrixType>::ReturnMatrixType m1image  = lu.image();

  // std::cerr << rank << " " << lu.rank() << std::endl;
  VERIFY(rank == lu.rank());
  VERIFY(cols - lu.rank() == lu.dimensionOfKernel());
  VERIFY(!lu.isInjective());
  VERIFY(!lu.isInvertible());
  VERIFY(!lu.isSurjective());
  VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));
  VERIFY(m1image.lu().rank() == rank);
  MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());
  sidebyside << m1, m1image;
  VERIFY(sidebyside.lu().rank() == rank);
  m2 = MatrixType::Random(cols,cols2);
  m3 = m1*m2;
  m2 = MatrixType::Random(cols,cols2);
  // test that the code, which does resize(), may be applied to an xpr
  m2.block(0,0,m2.rows(),m2.cols()) = lu.solve(m3);
  VERIFY_IS_APPROX(m3, m1*m2);

  typedef Matrix<typename MatrixType::Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
  SquareMatrixType m4(rows, rows), m5(rows, rows);
  createRandomMatrixOfRank(rows/2, rows, rows, m4);
  VERIFY(!m4.computeInverseWithCheck(&m5));
}

template<typename MatrixType> void lu_invertible()
{
  /* this test covers the following files:
     LU.h
  */
  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
  int size = ei_random<int>(10,200);

  MatrixType m1(size, size), m2(size, size), m3(size, size);
  m1 = MatrixType::Random(size,size);

  if (ei_is_same_type<RealScalar,float>::ret)
  {
    // let's build a matrix more stable to inverse
    MatrixType a = MatrixType::Random(size,size*2);
    m1 += a * a.adjoint();
  }

  LU<MatrixType> lu(m1);
  VERIFY(0 == lu.dimensionOfKernel());
  VERIFY(size == lu.rank());
  VERIFY(lu.isInjective());
  VERIFY(lu.isSurjective());
  VERIFY(lu.isInvertible());
  VERIFY(lu.image().lu().isInvertible());
  m3 = MatrixType::Random(size,size);
  m2 = lu.solve(m3);
  VERIFY_IS_APPROX(m3, m1*m2);
  VERIFY_IS_APPROX(m2, lu.inverse()*m3);
}

template<typename MatrixType> void lu_verify_assert()
{
  MatrixType tmp;

  LU<MatrixType> lu;
  VERIFY_RAISES_ASSERT(lu.matrixLU())
  VERIFY_RAISES_ASSERT(lu.permutationP())
  VERIFY_RAISES_ASSERT(lu.permutationQ())
  VERIFY_RAISES_ASSERT(lu.kernel())
  VERIFY_RAISES_ASSERT(lu.image())
  VERIFY_RAISES_ASSERT(lu.solve(tmp))
  VERIFY_RAISES_ASSERT(lu.determinant())
  VERIFY_RAISES_ASSERT(lu.rank())
  VERIFY_RAISES_ASSERT(lu.dimensionOfKernel())
  VERIFY_RAISES_ASSERT(lu.isInjective())
  VERIFY_RAISES_ASSERT(lu.isSurjective())
  VERIFY_RAISES_ASSERT(lu.isInvertible())
  VERIFY_RAISES_ASSERT(lu.inverse())

  PartialLU<MatrixType> plu;
  VERIFY_RAISES_ASSERT(plu.matrixLU())
  VERIFY_RAISES_ASSERT(plu.permutationP())
  VERIFY_RAISES_ASSERT(plu.solve(tmp,&tmp))
  VERIFY_RAISES_ASSERT(plu.determinant())
  VERIFY_RAISES_ASSERT(plu.inverse())
}

void test_lu()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( lu_non_invertible<MatrixXf>() );
    CALL_SUBTEST( lu_non_invertible<MatrixXd>() );
    CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );
    CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );
    CALL_SUBTEST( lu_invertible<MatrixXf>() );
    CALL_SUBTEST( lu_invertible<MatrixXd>() );
    CALL_SUBTEST( lu_invertible<MatrixXcf>() );
    CALL_SUBTEST( lu_invertible<MatrixXcd>() );
  }

  CALL_SUBTEST( lu_verify_assert<Matrix3f>() );
  CALL_SUBTEST( lu_verify_assert<Matrix3d>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXf>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXd>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXcf>() );
  CALL_SUBTEST( lu_verify_assert<MatrixXcd>() );
}
<|endoftext|>


<commit_before>#pragma once

#include <array>
#include <glm/glm.hpp>
#include <asdf_multiplat/main/asdf_defs.h>

namespace asdf
{
namespace hexmap
{

    //big collection of util functions from
    //http://www.redblobgames.com/grids/hexagons/

    using cube_coord_t  = glm::ivec3;
    using axial_coord_t = glm::ivec2;
    using hex_coord_t   = glm::ivec2;

    /// Coord Translations
    axial_coord_t cube_to_axial(cube_coord_t cube_coords)
    {
        return axial_coord_t{ cube_coords.x
                            , cube_coords.z };
    }

    cube_coord_t axial_to_cube(axial_coord_t axial_coords)
    {
        auto x = axial_coords.x;
        auto z = axial_coords.y;
        auto y = -x - z;

        return cube_coord_t(x,y,z);
    }

    hex_coord_t cube_to_oddq(cube_coord_t cube_coords)
    {
        return hex_coord_t{ cube_coords.x
                          , cube_coords.z + (cube_coords.x - (cube_coords.x & 1)) / 2 // bitwise and checks for odd column
                          };
    }

    cube_coord_t oddq_to_cube(hex_coord_t hex_coord)
    {
        auto x = hex_coord.x;
        auto z = hex_coord.y - (hex_coord.x - (hex_coord.x & 1)) / 2;
        auto y = -x - z;

        return cube_coord_t{x, y, z};
    }

    //alias func
    inline cube_coord_t hex_to_cube(hex_coord_t hex_coord)
    {
        return oddq_to_cube(hex_coord);
    }
    inline hex_coord_t cube_to_hex(cube_coord_t cube_coord)
    {
        return cube_to_oddq(cube_coord);
    }

    /// Distance
    float cube_distance(cube_coord_t a, cube_coord_t b)
    {
        return (abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z)) / 2;
    }

    float axial_distance(axial_coord_t a, axial_coord_t b)
    {
        auto ac = hex_to_cube(a);
        auto bc = hex_to_cube(b);
        return cube_distance(ac, bc);
    }

    float hex_distance(hex_coord_t a, hex_coord_t b)
    {
        auto ac = hex_to_cube(a);
        auto bc = hex_to_cube(b);
        return cube_distance(ac, bc);
    }

    /// Direction
    enum hexagon_direction_e
    {
        hex_dir_down_right = 0
      , hex_dir_up_right
      , hex_dir_up
      , hex_dir_up_left
      , hex_dir_down_left
      , hex_dir_down
    };

    /*constexpr*/ std::array<cube_coord_t, 6> hexagon_cube_directions =
    {
        cube_coord_t{+1, -1,  0} //down right
      , cube_coord_t{+1,  0, -1} //up right
      , cube_coord_t{ 0, +1, -1} //up
      , cube_coord_t{-1, +1,  0} //up left
      , cube_coord_t{-1,  0, +1} //down left
      , cube_coord_t{ 0, -1, +1} //down
    };

    cube_coord_t cube_neighbor(cube_coord_t coord, hexagon_direction_e direction)
    {
        return coord + hexagon_cube_directions[direction];
    }

    /// Other
    std::vector<cube_coord_t> cube_ring(cube_coord_t center, int radius)
    {
        std::vector<cube_coord_t> results;
        results.reserve(radius * 6);

        auto cube = center + (hexagon_cube_directions[hex_dir_down_left] * radius);

        for(int edge_num = 0; edge_num < 6; ++edge_num) //for each hex edge
        {
            for(int edge_hex_num = 0; edge_hex_num < radius; ++edge_hex_num)
            {
                results.push_back(cube);
                cube = cube_neighbor(cube, static_cast<hexagon_direction_e>(edge_num));
            }
        }

        return results;
    }

    std::vector<cube_coord_t> cube_spiral(cube_coord_t center, int radius)
    {
        std::vector<cube_coord_t> results;

        // Fills a hex region with rings
        for(size_t cur_radius = 1; cur_radius < radius; ++cur_radius)
        {
            auto ring = cube_ring(center, cur_radius);

            results.reserve(results.size() + ring.size());
            std::move(ring.begin(), ring.end(), std::back_inserter(results));
        }

        return results;
    }

}
}<commit_msg>added func to get a range of coords in the shape of a hexagon<commit_after>#pragma once

#include <array>
#include <glm/glm.hpp>
#include <asdf_multiplat/main/asdf_defs.h>

namespace asdf
{
namespace hexmap
{

    //big collection of util functions from
    //http://www.redblobgames.com/grids/hexagons/

    using cube_coord_t  = glm::ivec3;
    using axial_coord_t = glm::ivec2;
    using hex_coord_t   = glm::ivec2;

    /// Coord Translations
    axial_coord_t cube_to_axial(cube_coord_t cube_coords)
    {
        return axial_coord_t{ cube_coords.x
                            , cube_coords.z };
    }

    cube_coord_t axial_to_cube(axial_coord_t axial_coords)
    {
        auto x = axial_coords.x;
        auto z = axial_coords.y;
        auto y = -x - z;

        return cube_coord_t(x,y,z);
    }

    hex_coord_t cube_to_oddq(cube_coord_t cube_coords)
    {
        return hex_coord_t{ cube_coords.x
                          , cube_coords.z + (cube_coords.x - (cube_coords.x & 1)) / 2 // bitwise and checks for odd column
                          };
    }

    cube_coord_t oddq_to_cube(hex_coord_t hex_coord)
    {
        auto x = hex_coord.x;
        auto z = hex_coord.y - (hex_coord.x - (hex_coord.x & 1)) / 2;
        auto y = -x - z;

        return cube_coord_t{x, y, z};
    }

    //alias func
    inline cube_coord_t hex_to_cube(hex_coord_t hex_coord)
    {
        return oddq_to_cube(hex_coord);
    }
    inline hex_coord_t cube_to_hex(cube_coord_t cube_coord)
    {
        return cube_to_oddq(cube_coord);
    }

    /// Distance
    float cube_distance(cube_coord_t a, cube_coord_t b)
    {
        return (abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z)) / 2;
    }

    float axial_distance(axial_coord_t a, axial_coord_t b)
    {
        auto ac = hex_to_cube(a);
        auto bc = hex_to_cube(b);
        return cube_distance(ac, bc);
    }

    float hex_distance(hex_coord_t a, hex_coord_t b)
    {
        auto ac = hex_to_cube(a);
        auto bc = hex_to_cube(b);
        return cube_distance(ac, bc);
    }

    /// Direction
    enum hexagon_direction_e
    {
        hex_dir_down_right = 0
      , hex_dir_up_right
      , hex_dir_up
      , hex_dir_up_left
      , hex_dir_down_left
      , hex_dir_down
    };

    /*constexpr*/ std::array<cube_coord_t, 6> hexagon_cube_directions =
    {
        cube_coord_t{+1, -1,  0} //down right
      , cube_coord_t{+1,  0, -1} //up right
      , cube_coord_t{ 0, +1, -1} //up
      , cube_coord_t{-1, +1,  0} //up left
      , cube_coord_t{-1,  0, +1} //down left
      , cube_coord_t{ 0, -1, +1} //down
    };

    cube_coord_t cube_neighbor(cube_coord_t coord, hexagon_direction_e direction)
    {
        return coord + hexagon_cube_directions[direction];
    }

    /// Ranges
    std::vector<cube_coord_t> cube_range(cube_coord_t center, int range)
    {
        std::vector<cube_coord_t> results;

        for(int dx = -range; dx <= range; ++dx)
        {
            for(int dy = glm::max(-range, -dx - range); dy <= glm::min(range, -dx + range); ++dy)
            {
                auto dz = -dx - dy;
                results.push_back(center + cube_coord_t(dx, dy, dz));
            }
        }

        return results;
    }

    /// Other
    std::vector<cube_coord_t> cube_ring(cube_coord_t center, int radius)
    {
        std::vector<cube_coord_t> results;
        results.reserve(radius * 6);

        auto cube = center + (hexagon_cube_directions[hex_dir_down_left] * radius);

        for(int edge_num = 0; edge_num < 6; ++edge_num) //for each hex edge
        {
            for(int edge_hex_num = 0; edge_hex_num < radius; ++edge_hex_num)
            {
                results.push_back(cube);
                cube = cube_neighbor(cube, static_cast<hexagon_direction_e>(edge_num));
            }
        }

        return results;
    }

    std::vector<cube_coord_t> cube_spiral(cube_coord_t center, int radius)
    {
        std::vector<cube_coord_t> results;

        // Fills a hex region with rings
        for(size_t cur_radius = 1; cur_radius < radius; ++cur_radius)
        {
            auto ring = cube_ring(center, cur_radius);

            results.reserve(results.size() + ring.size());
            std::move(ring.begin(), ring.end(), std::back_inserter(results));
        }

        return results;
    }

}
}<|endoftext|>


<commit_before>#include <async.h>
#include <aios.h>
#include <crypt.h>
#include <dbfe.h>
#include <adb_prot.h>

static char *usage = "usage: dbdump dbhome\n";

int
main (int argc, char *argv[])
{
  if (argc != 2)
    fatal << usage;

  int r;
  DB_ENV* dbe = NULL;
  DB *db = NULL;

  r = dbfe_initialize_dbenv (&dbe, argv[1], /* join = */ true);
  if (r)
    fatal << "couldn't open dbenv: " << db_strerror (r) << "\n";

  r = dbfe_opendb (dbe, &db, "metadatadb", DB_RDONLY);
  if (r)
    fatal << "couldn't open db: " << db_strerror (r) << "\n";

  DBC *cursor;
  r = db->cursor(db, NULL, &cursor, 0);
  assert (r == 0);

  DBT key, data;
  unsigned totalsz = 0;
  unsigned keys = 0;

#ifndef DB_BUFFER_SMALL
/* DB_BUFFER_SMALL is introduced in db4.3 */
#  define DB_BUFFER_SMALL ENOMEM
#endif /* DB_BUFFER_SMALL */

  adb_master_metadata_t mmd;
  bzero (&mmd, sizeof (mmd));

  for (int i = 0; ; i++) {
    bzero (&key, sizeof (key));
    bzero (&data, sizeof (data));
    int err = cursor->c_get (cursor, &key, &data, DB_NEXT);
    if (err == DB_NOTFOUND) {
      aout << "EOF.\n";
      break;
    } else if (err) {
      fatal << "err: " << err << " " << strerror (err) << "\n";
    }
    if (key.size != sha1::hashsize) {
      buf2xdr (mmd, data.data, data.size);
      continue;
    }

    chordID k;
    mpz_set_rawmag_be (&k, static_cast<char *> (key.data), key.size);

    adb_metadata_t md;
    buf2xdr (md, data.data, data.size);

    aout << "key[" << i << "] " << k << " " << md.size << " " << md.expiration << "\n";

    keys++;
    totalsz += md.size;

    aout->flush ();
  }
  cursor->c_close (cursor);

  db->close (db, 0);
  dbe->close (dbe, 0);
  aout << "total keys: " << keys << "\n";
  aout << "total bytes: " << totalsz << "\n";
  if (totalsz != mmd.size)
    fatal << "Master metadata total bytes error: " << mmd.size << "\n";
}

<commit_msg>Allow dbdump to read ordered by expire time.<commit_after>#include <async.h>
#include <aios.h>
#include <crypt.h>
#include <dbfe.h>
#include <adb_prot.h>

static char *usage = "usage: dbdump [-t] dbhome\n";

// {{{ getexpire: Secondary key extractor for metadata
static int
getexpire (DB *sdb, const DBT *pkey, const DBT *pdata, DBT *skey)
{
  u_int32_t *expire = (u_int32_t *) malloc(sizeof(u_int32_t));
  // this flag should mean that berkeley db will free this memory when it's
  // done with it.
  skey->flags = DB_DBT_APPMALLOC;
  skey->data = expire;
  skey->size = sizeof (*expire);

  if (pkey->size != sha1::hashsize)
  {
    *expire = 0;
    return 0;
  }

  adb_metadata_t md;
  if (!buf2xdr (md, pdata->data, pdata->size)) {
    hexdump hd (pdata->data, pdata->size);
    warn << "getexpire: unable to unmarshal pdata.\n" << hd << "\n";
    return -1;
  }
  // Ensure big-endian for proper BDB sorting.
  *expire = htonl (md.expiration);
  return 0;
}
// }}}

int
main (int argc, char *argv[])
{
  if (argc != 2 && argc != 3)
    fatal << usage;

  int r;
  DB_ENV* dbe = NULL;
  DB *metadatadb = NULL;
  DB *byexpiredb = NULL;

  bool bytime = false;
  char *path = argv[1];

  if (!strcmp (argv[1], "-t")) {
    path = argv[2];
    bytime = true;
  }

  r = dbfe_initialize_dbenv (&dbe, path, /* join = */ true);
  if (r)
    fatal << "couldn't open dbenv: " << db_strerror (r) << "\n";

  r = dbfe_opendb (dbe, &metadatadb, "metadatadb", DB_RDONLY);
  if (r)
    fatal << "couldn't open db: " << db_strerror (r) << "\n";

  r = dbfe_opendb (dbe, &byexpiredb, "byexpiredb", DB_RDONLY, 0, /* dups = */ true);
  if (r)
    fatal << "couldn't open expiredb: " << db_strerror (r) << "\n";
  r = metadatadb->associate (metadatadb, NULL, byexpiredb, getexpire, DB_AUTO_COMMIT);
  if (r)
    fatal << "couldn't associate expiredb: " << db_strerror (r) << "\n";

  DBC *cursor;
  if (bytime)
    r = byexpiredb->cursor (byexpiredb, NULL, &cursor, 0);
  else
    r = metadatadb->cursor (metadatadb, NULL, &cursor, 0);
  assert (r == 0);

  DBT begin_time, key, data;
  unsigned totalsz = 0;
  unsigned keys = 0;

#ifndef DB_BUFFER_SMALL
/* DB_BUFFER_SMALL is introduced in db4.3 */
#  define DB_BUFFER_SMALL ENOMEM
#endif /* DB_BUFFER_SMALL */

  adb_master_metadata_t mmd;
  bzero (&mmd, sizeof (mmd));

  for (int i = 0; ; i++) {
    bzero (&begin_time, sizeof (begin_time));
    bzero (&key, sizeof (key));
    bzero (&data, sizeof (data));
    int err = 0;
    if (bytime)
      err = cursor->c_pget (cursor, &begin_time, &key, &data, DB_NEXT);
    else
      err = cursor->c_get (cursor, &key, &data, DB_NEXT);
    if (err == DB_NOTFOUND) {
      aout << "EOF.\n";
      break;
    } else if (err) {
      fatal << "err: " << err << " " << strerror (err) << "\n";
    }
    if (key.size != sha1::hashsize) {
      buf2xdr (mmd, data.data, data.size);
      continue;
    }

    chordID k;
    mpz_set_rawmag_be (&k, static_cast<char *> (key.data), key.size);

    adb_metadata_t md;
    buf2xdr (md, data.data, data.size);

    aout << "key[" << i << "] " << k << " " << md.size << " " << md.expiration << "\n";

    keys++;
    totalsz += md.size;

    aout->flush ();
  }
  cursor->c_close (cursor);

  byexpiredb->close (byexpiredb, 0);
  metadatadb->close (metadatadb, 0);
  dbe->close (dbe, 0);
  aout << "total keys: " << keys << "\n";
  aout << "total bytes: " << totalsz << "\n";
  if (totalsz != mmd.size)
    fatal << "Master metadata total bytes error: " << mmd.size << "\n";
}

<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/10 21:16:10
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- 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} {}
  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*=(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>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll lcm(ll x, ll y) { return x * y / gcd(x, y); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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 << 0 << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  ll N, M;
  cin >> N >> M;
  vector<ll> a(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
    a[i] /= 2;
  }
  vector<int> cnt(N, 0);
  for (auto i = 0; i < N; i++)
  {
    while ((a[i] & 1) == 0)
    {
      a[i] >>= 1;
      cnt[i]++;
    }
  }
  int k{cnt[0]};
  for (auto i = 0; i < N; i++)
  {
    if (cnt[i] != k)
    {
      No();
    }
  }
  ll L{lcm(a[0], a[1])};
  if (L > M)
  {
    No();
  }
  for (auto i = 2; i < N; i++)
  {
    L = lcm(L, a[i]);
    if (L > M)
    {
      No();
    }
  }
  for (auto i = 0; i < k; i++)
  {
    L <<= 1;
    if (L > M)
    {
      No();
    }
  }
  ll X{M / L};
  cout << (X + 1) / 2 << endl;
}
<commit_msg>submit D.cpp to 'D - Semi Common Multiple' (abc150) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/10 21:16:10
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using boost::multiprecision::cpp_int;
using namespace std;
using ll = long long;
// ----- 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} {}
  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*=(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>;
cpp_int gcd(cpp_int x, cpp_int y) { return y ? gcd(y, x % y) : x; }
cpp_int lcm(cpp_int x, cpp_int y) { return x * y / gcd(x, y); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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 << 0 << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  int N;
  cpp_int M;
  cin >> N >> M;
  vector<cpp_int> a(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
    a[i] /= 2;
  }
  vector<int> cnt(N, 0);
  for (auto i = 0; i < N; i++)
  {
    while ((a[i] & 1) == 0)
    {
      a[i] >>= 1;
      cnt[i]++;
    }
  }
  int k{cnt[0]};
  for (auto i = 0; i < N; i++)
  {
    if (cnt[i] != k)
    {
      No();
    }
  }
  cpp_int L{lcm(a[0], a[1])};
  if (L > M)
  {
    No();
  }
  for (auto i = 2; i < N; i++)
  {
    L = lcm(L, a[i]);
    if (L > M)
    {
      No();
    }
  }
  for (auto i = 0; i < k; i++)
  {
    L <<= 1;
    if (L > M)
    {
      No();
    }
  }
  cpp_int X{M / L};
  cout << (X + 1) / 2 << endl;
}
<|endoftext|>


<commit_before>#include "ScriptObject.hpp"
#include "ScriptRepo.hpp"
#include "ClientRepo.hpp"
#include "MainPluginInstance.hpp"
#include "../inanity/Handler.hpp"
#include "../inanity/script/np/State.hpp"
#include "../inanity/script/np/Any.hpp"
#include "../inanity/platform/FileSystem.hpp"
#include "../inanity/FileInputStream.hpp"
#include "../inanity/StreamReader.hpp"
#include "../inanity/File.hpp"

BEGIN_INANITY_OIL

//*** class ScriptObject::CheckRepoHandler

class ScriptObject::CheckRepoHandler : public DataHandler<ptr<File> >
{
private:
	ptr<ScriptObject> scriptObject;
	ptr<Script::Any> callback;

public:
	CheckRepoHandler(ptr<ScriptObject> scriptObject, ptr<Script::Any> callback)
	: scriptObject(scriptObject), callback(callback) {}

	void OnData(ptr<File> data)
	{
		try
		{
			ptr<ClientRepo> repo = ClientRepo::CreateInMemory();
			repo->ReadServerManifest(&StreamReader(NEW(FileInputStream(data))));
			callback->Call(
				scriptObject->scriptState->NewBoolean(true),
				scriptObject->scriptState->NewString("OK"));
				//scriptObject->scriptState->NewNumber(123));
		}
		catch(Exception* exception)
		{
			OnError(exception);
		}
	}

	void OnError(ptr<Exception> exception)
	{
		std::ostringstream ss;
		exception->PrintStack(ss);
		callback->Call(
			scriptObject->scriptState->NewBoolean(false),
			scriptObject->scriptState->NewString(ss.str()));
			//scriptObject->scriptState->NewNumber(123));
	}
};

//*** class ScriptObject

ScriptObject::ScriptObject(ptr<Script::Np::State> scriptState)
: scriptState(scriptState)
{
	nativeFileSystem = Platform::FileSystem::GetNativeFileSystem();
}

ptr<Script::Any> ScriptObject::GetRootNamespace() const
{
	return scriptState->GetRootNamespace();
}

ptr<FileSystem> ScriptObject::GetNativeFileSystem() const
{
	return nativeFileSystem;
}

void ScriptObject::CheckRepo(const String& url, ptr<Script::Any> callback)
{
	MainPluginInstance::GetInstance()->GetUrl(
		url + "?manifest",
		NEW(CheckRepoHandler(this, callback)));
}

END_INANITY_OIL
<commit_msg>remove commented out lines<commit_after>#include "ScriptObject.hpp"
#include "ScriptRepo.hpp"
#include "ClientRepo.hpp"
#include "MainPluginInstance.hpp"
#include "../inanity/Handler.hpp"
#include "../inanity/script/np/State.hpp"
#include "../inanity/script/np/Any.hpp"
#include "../inanity/platform/FileSystem.hpp"
#include "../inanity/FileInputStream.hpp"
#include "../inanity/StreamReader.hpp"
#include "../inanity/File.hpp"

BEGIN_INANITY_OIL

//*** class ScriptObject::CheckRepoHandler

class ScriptObject::CheckRepoHandler : public DataHandler<ptr<File> >
{
private:
	ptr<ScriptObject> scriptObject;
	ptr<Script::Any> callback;

public:
	CheckRepoHandler(ptr<ScriptObject> scriptObject, ptr<Script::Any> callback)
	: scriptObject(scriptObject), callback(callback) {}

	void OnData(ptr<File> data)
	{
		try
		{
			ptr<ClientRepo> repo = ClientRepo::CreateInMemory();
			repo->ReadServerManifest(&StreamReader(NEW(FileInputStream(data))));
			callback->Call(
				scriptObject->scriptState->NewBoolean(true),
				scriptObject->scriptState->NewString("OK"));
		}
		catch(Exception* exception)
		{
			OnError(exception);
		}
	}

	void OnError(ptr<Exception> exception)
	{
		std::ostringstream ss;
		exception->PrintStack(ss);
		callback->Call(
			scriptObject->scriptState->NewBoolean(false),
			scriptObject->scriptState->NewString(ss.str()));
	}
};

//*** class ScriptObject

ScriptObject::ScriptObject(ptr<Script::Np::State> scriptState)
: scriptState(scriptState)
{
	nativeFileSystem = Platform::FileSystem::GetNativeFileSystem();
}

ptr<Script::Any> ScriptObject::GetRootNamespace() const
{
	return scriptState->GetRootNamespace();
}

ptr<FileSystem> ScriptObject::GetNativeFileSystem() const
{
	return nativeFileSystem;
}

void ScriptObject::CheckRepo(const String& url, ptr<Script::Any> callback)
{
	MainPluginInstance::GetInstance()->GetUrl(
		url + "?manifest",
		NEW(CheckRepoHandler(this, callback)));
}

END_INANITY_OIL
<|endoftext|>


<commit_before>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the ‘Software’), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 *****************************************************************************/
#include <rice/Module.hpp>
#include "_mapnik.h"

extern "C"

void Init_ruby_mapnik() {
  RUBY_TRY {
    register_mapnik();
  } RUBY_CATCH
}<commit_msg>enable using -fvisibility=hidden<commit_after>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the ‘Software’), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 *****************************************************************************/
#include <rice/Module.hpp>
#include "_mapnik.h"
#include <mapnik/config.hpp>

extern "C"

MAPNIK_DECL void Init_ruby_mapnik() {
  RUBY_TRY {
    register_mapnik();
  } RUBY_CATCH
}<|endoftext|>