<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 15:32:10
 * 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 <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 int infty = 1000000007;

int N, M, L, X;
int a[1010];
int DP[1010];
int DP2[1010];
int sum;

int main()
{
  cin >> N >> M >> L >> X;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  int maxi = (X - 1) * M + L;
  fill(DP, DP + M, infty);
  DP[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < M; j++)
    {
      sum = DP[j] + a[i];
      DP2[sum % M] = min(DP[sum % M], sum);
    }
    for (auto j = 0; j < M; j++)
    {
      DP[j] = DP2[j];
    }
  }
  cout << ((DP[L] <= maxi) ? "Yes" : "No") << endl;
}<commit_msg>tried D.cpp to 'D'<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 15:32:10
 * 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 <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 int infty = 1000000007;

int N, M, L, X;
int a[1010];
int DP[1010];
int DP2[1010];
int sum;

int main()
{
  cin >> N >> M >> L >> X;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  int maxi = (X - 1) * M + L;
  fill(DP, DP + M, infty);
  DP[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    fill(DP2, DP2 + M, infty);
    for (auto j = 0; j < M; j++)
    {
      if (DP[j] == infty)
        continue;
      sum = DP[j] + a[i];
      DP2[sum % M] = min(DP[sum % M], sum);
    }
    for (auto j = 0; j < M; j++)
    {
      DP[j] = DP2[j];
    }
  }
  cout << ((DP[L] <= maxi) ? "Yes" : "No") << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/6/28 20:51:44
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    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, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &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, Mint<MOD> const &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>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

#if DEBUG == 1
constexpr int D = 5;
#else
constexpr int D = 365;
#endif
constexpr int C = 26;

class Solve
{
  vector<ll> c;
  vector<vector<ll>> s;
  vector<int> t;
  vector<set<int>> contestDays;
  ll totalScore;

public:
  Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0}
  {
    for (auto i{0}; i < C; ++i)
    {
      cin >> c[i];
    }
    for (auto i{0}; i < D; ++i)
    {
      for (auto j{0}; j < C; ++j)
      {
        cin >> s[i][j];
      }
    }
    for (auto i{0}; i < C; ++i)
    {
      contestDays[i].insert(0);
      contestDays[i].insert(D + 1);
    }
  }

  void flush()
  {
    for (auto i{0}; i < D; ++i)
    {
      cin >> t[i];
      t[i]--;
    }
    calc_score();
    int M;
    cin >> M;
    for (auto i{0}; i < M; ++i)
    {
      int d, q;
      cin >> d >> q;
      --q;
      totalScore = change_score(d, q);
      cout << totalScore << endl;
    }
  }

private:
  ll change_score(int d, int q)
  {
    int p{t[d - 1]};
    t[d - 1] = q;
#if DEBUG == 1
    cerr << "p = " << p << ", q = " << q << endl;
#endif
    if (p == q)
    {
      return totalScore;
    }
    ll newScore{totalScore};
    t[d] = q;
    newScore -= s[d - 1][p];
    newScore += s[d - 1][q];
#if DEBUG == 1
    cerr << "contestDays[" << p << "] = {";
    for (auto e : contestDays[p])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
    cerr << "contestDays[" << q << "] = {";
    for (auto e : contestDays[q])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
#endif
    {
      auto it{contestDays[p].find(d)};
      --it;
      auto x{*it};
      ++it;
      ++it;
      auto y{*it};
      auto dif{(y - d) * (d - x)};
      newScore -= c[p] * dif;
#if DEBUG == 1
      cerr << "x = " << x << ", d = " << d << ", y = " << y << endl;
#endif
      --it;
      contestDays[p].erase(it);
    }
    {
      contestDays[q].insert(d);
      auto it{contestDays[q].find(d)};
      --it;
      auto x{*it};
      ++it;
      ++it;
      auto y{*it};
      auto dif{(y - d) * (d - x)};
      newScore += c[q] * dif;
#if DEBUG == 1
      cerr << "x = " << x << ", d = " << d << ", y = " << y << endl;
#endif
    }
#if DEBUG == 1
    cerr << "contestDays[" << p << "] = {";
    for (auto e : contestDays[p])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
    cerr << "contestDays[" << q << "] = {";
    for (auto e : contestDays[q])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
#endif
    return newScore;
  }

  vector<ll> calc_score()
  {
    vector<ll> ans(D);
    vector<vector<int>> last(D + 1, vector<int>(C, 0));
    ll now{0};
    for (auto d{0}; d < D; ++d)
    {
      now += s[d][t[d]];
      contestDays[t[d]].insert(d + 1);
      last[d + 1] = last[d];
      last[d + 1][t[d]] = d + 1;
      ll penalty{0};
      for (auto i{0}; i < C; ++i)
      {
        penalty += c[i] * (d + 1 - last[d + 1][i]);
      }
      now -= penalty;
      ans[d] = now;
    }
    totalScore = now;
    return ans;
  }
};

// ----- main() -----

int main()
{
  ll d;
  cin >> d;
  Solve solve;
  solve.flush();
}
<commit_msg>submit C.cpp to 'C - Incremental Scoring' (intro-heuristics) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/6/28 20:51:44
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    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, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &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, Mint<MOD> const &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>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

#if DEBUG == 1
constexpr int D = 5;
#else
constexpr int D = 365;
#endif
constexpr int C = 26;

class Solve
{
  vector<ll> c;
  vector<vector<ll>> s;
  vector<int> t;
  vector<set<int>> contestDays;
  ll totalScore;

public:
  Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0}
  {
    for (auto i{0}; i < C; ++i)
    {
      cin >> c[i];
    }
    for (auto i{0}; i < D; ++i)
    {
      for (auto j{0}; j < C; ++j)
      {
        cin >> s[i][j];
      }
    }
    for (auto i{0}; i < C; ++i)
    {
      contestDays[i].insert(0);
      contestDays[i].insert(D + 1);
    }
  }

  void flush()
  {
    for (auto i{0}; i < D; ++i)
    {
      cin >> t[i];
      t[i]--;
    }
    calc_score();
    int M;
    cin >> M;
    for (auto i{0}; i < M; ++i)
    {
      int d, q;
      cin >> d >> q;
      --q;
      totalScore = change_score(d, q);
      cout << totalScore << endl;
    }
  }

private:
  ll change_score(int d, int q)
  {
    int p{t[d - 1]};
#if DEBUG == 1
    cerr << "p = " << p << ", q = " << q << endl;
#endif
    if (p == q)
    {
      return totalScore;
    }
    ll newScore{totalScore};
    t[d - 1] = q;
    newScore -= s[d - 1][p];
    newScore += s[d - 1][q];
#if DEBUG == 1
    cerr << "contestDays[" << p << "] = {";
    for (auto e : contestDays[p])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
    cerr << "contestDays[" << q << "] = {";
    for (auto e : contestDays[q])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
#endif
    {
      auto it{contestDays[p].find(d)};
      --it;
      auto x{*it};
      ++it;
      ++it;
      auto y{*it};
      auto dif{(y - d) * (d - x)};
      newScore -= c[p] * dif;
#if DEBUG == 1
      cerr << "x = " << x << ", d = " << d << ", y = " << y << endl;
#endif
      --it;
      contestDays[p].erase(it);
    }
    {
      contestDays[q].insert(d);
      auto it{contestDays[q].find(d)};
      --it;
      auto x{*it};
      ++it;
      ++it;
      auto y{*it};
      auto dif{(y - d) * (d - x)};
      newScore += c[q] * dif;
#if DEBUG == 1
      cerr << "x = " << x << ", d = " << d << ", y = " << y << endl;
#endif
    }
#if DEBUG == 1
    cerr << "contestDays[" << p << "] = {";
    for (auto e : contestDays[p])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
    cerr << "contestDays[" << q << "] = {";
    for (auto e : contestDays[q])
    {
      cerr << e << ", ";
    }
    cerr << "}" << endl;
#endif
    return newScore;
  }

  vector<ll> calc_score()
  {
    vector<ll> ans(D);
    vector<vector<int>> last(D + 1, vector<int>(C, 0));
    ll now{0};
    for (auto d{0}; d < D; ++d)
    {
      now += s[d][t[d]];
      contestDays[t[d]].insert(d + 1);
      last[d + 1] = last[d];
      last[d + 1][t[d]] = d + 1;
      ll penalty{0};
      for (auto i{0}; i < C; ++i)
      {
        penalty += c[i] * (d + 1 - last[d + 1][i]);
      }
      now -= penalty;
      ans[d] = now;
    }
    totalScore = now;
    return ans;
  }
};

// ----- main() -----

int main()
{
  ll d;
  cin >> d;
  Solve solve;
  solve.flush();
}
<|endoftext|>


<commit_before>//
// Copyright(c) Jackal Engine. MIT License.
//
#include "MatrixTest.hpp"

#include "Math/Matrix.hpp"
#include "Math/Vector.hpp"
#include "Math/VectorMath.hpp"
#include "Math/MatrixMath.hpp"
#include "Math/Quaternion.hpp"
#include "Math/Common.hpp"
#include "glm/common.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <iostream>
#include <iomanip>
#include <chrono>

namespace coretest {

TEST_F(MatrixTestFixture, MatrixAlgebraFixture) {

}

TEST(MathTesting, MatrixTesting) {
  jkl::Mat4 jmat;
  glm::mat4 glm_mat;

  EXPECT_EQ(jmat[0][0], glm_mat[0][0]);

  jkl::Mat4 A(
    8, 1, 1, 5,
    -1, 5, 6, 7,
    8, 9, 10, 11,
    12, 5, -12, 15
  );
  jkl::Mat4 B(
    5, 6, 12, 10,
    -1, 0, -12, 12,
    9, 1, 122, 4,
    8, 4, -9, 2
  );
  A *= B;
  jkl::Mat3 D;

  // TODO(): Tests are not super accurate, seems like which ever transformation
  // from either library is done first, it will be the slowest... Both libraries
  // perform about the same optimal time, average.

  auto start = std::chrono::high_resolution_clock::now();
  glm::mat4 glmT = //glm::perspectiveLH(45.0f, 1.0f, 0.1f, 1000.0f);
  //glm::lookAtLH(glm::vec3(1.0f, 16.0f, -123.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
  glm::translate(glm::mat4(), glm::vec3(12.0f, -12.4f, 1.0f));
  glmT = glm::rotate(glmT, glm::radians(-74.0f), glm::vec3(0.0f, 1.0f, 0.0f));
  glmT = glm::rotate(glmT, glm::radians(50.0f), glm::vec3(1.0f, 0.0f, 0.0f));
  glmT = glm::scale(glmT, glm::vec3(5.0f, 5.0f, 5.0f));
  auto end = std::chrono::high_resolution_clock::now();
  long long tG = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

  start = std::chrono::high_resolution_clock::now();
  jkl::Mat4 T = //jkl::PerspectiveLH(45.0f, 1.0f, 0.1f, 1000.0f);
           //jkl::LookAtLH(jkl::Vec3(1.0f, 16.0f, -123.0f), jkl::Vec3(0.0f, 0.0f, 0.0f), jkl::Vec3(0.0f, 1.0f, 0.0f));
    jkl::Translate(jkl::Mat4(), jkl::Vec3(12.0f, -12.4f, 1.0f));
  T = jkl::Rotate(T, jkl::ToRadians(-74.0f), jkl::Vec3(0.0f, 1.0f, 0.0f));
  T = jkl::Rotate(T, jkl::ToRadians(50.0f), jkl::Vec3(1.0f, 0.0f, 0.0f));
  T = jkl::Scale(T, jkl::Vec3(5.0f, 5.0f, 5.0f));
  end = std::chrono::high_resolution_clock::now();
  long long tJ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

  std::printf("tJ=%llu tG=%llu", tJ, tG);
  jkl::Mat4 C = B;
  C = C.Inverse();
  jkl::Quat q0(1.0f, 0.0f, 0.0f, 2.0f);
  jkl::Quat q1(3.0f, -1.0f, 4.0f, 3.0f);
  jkl::Quat ans = q0 * q1;
  ans = ans.Inverse();
  std::printf("quat ans: w=>%f x=>%f y=>%f z=>%f\n",
    ans.w, ans.x, ans.y, ans.z);
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(5) << A[i][j] << " ";
    }
    std::cout << "\n";
  }
  std::cout << "\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(5) << B[i][j] << " ";
    }
    std::cout << "\n";
  }

  std::cout << "\nJackal Math library:\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(15) << T[i][j] << " ";
    }
    std::cout << "\n";
  } glm::mat4 m;
  std::cout << "\nGLM library:\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(15) << glmT[i][j] << " ";
    }
    std::cout << "\n";
  }
  std::cout << "\nDeterminant of B is: " << B.Determinant() << "\n";
  jkl::Vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);
  jkl::Vec3 a(1.0f, 2.0f, 3.0f);
  jkl::Vec3 b(4.0f, 5.0f, 6.0f);
  //a *= b;
  std::printf("Vector values: x=%f y=%f z=%f w=%f\n", vec.r, vec.g, vec.b, vec.a);
  jkl::Vec3 c = Cross(a, b);
  bool yup = A == B;
  std::printf("Vector operation: x=%f y=%f z=%f\n", c.x, c.y, c.z);
  std::printf("a < c: %d\n", yup);

}

void MatrixTesting()
{
  // ehh
}
} // coretest
<commit_msg>small add<commit_after>//
// Copyright(c) Jackal Engine. MIT License.
//
#include "MatrixTest.hpp"

#include "Math/Matrix.hpp"
#include "Math/Vector.hpp"
#include "Math/VectorMath.hpp"
#include "Math/MatrixMath.hpp"
#include "Math/Quaternion.hpp"
#include "Math/Common.hpp"
#include "glm/common.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include <iostream>
#include <iomanip>
#include <chrono>

namespace coretest {

TEST_F(MatrixTestFixture, MatrixAlgebraFixture) {

}

TEST(MathTesting, MatrixTesting) {
  jkl::Mat4 jmat;
  glm::mat4 glm_mat;

  EXPECT_EQ(jmat[0][0], glm_mat[0][0]);

  jkl::Mat4 A(
    8, 1, 1, 5,
    -1, 5, 6, 7,
    8, 9, 10, 11,
    12, 5, -12, 15
  );
  jkl::Mat4 B(
    5, 6, 12, 10,
    -1, 0, -12, 12,
    9, 1, 122, 4,
    8, 4, -9, 2
  );
  A *= B;
  jkl::Mat3 D;

  // TODO(): Tests are not super accurate, seems like which ever transformation
  // from either library is done first, it will be the slowest... Both libraries
  // perform about the same optimal time, average.

  auto start = std::chrono::high_resolution_clock::now();
  glm::mat4 glmT = //glm::perspectiveLH(45.0f, 1.0f, 0.1f, 1000.0f);
  //glm::lookAtLH(glm::vec3(1.0f, 16.0f, -123.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
  glm::translate(glm::mat4(), glm::vec3(12.0f, -12.4f, 1.0f));
  glmT = glm::rotate(glmT, glm::radians(-74.0f), glm::vec3(0.0f, 1.0f, 0.0f));
  glmT = glm::rotate(glmT, glm::radians(50.0f), glm::vec3(1.0f, 0.0f, 0.0f));
  glmT = glm::scale(glmT, glm::vec3(5.0f, 5.0f, 5.0f));
  auto end = std::chrono::high_resolution_clock::now();
  long long tG = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

  start = std::chrono::high_resolution_clock::now();
  jkl::Mat4 T = //jkl::PerspectiveLH(45.0f, 1.0f, 0.1f, 1000.0f);
           //jkl::LookAtLH(jkl::Vec3(1.0f, 16.0f, -123.0f), jkl::Vec3(0.0f, 0.0f, 0.0f), jkl::Vec3(0.0f, 1.0f, 0.0f));
    jkl::Translate(jkl::Mat4(), jkl::Vec3(12.0f, -12.4f, 1.0f));
  T = jkl::Rotate(T, jkl::ToRadians(-74.0f), jkl::Vec3(0.0f, 1.0f, 0.0f));
  T = jkl::Rotate(T, jkl::ToRadians(50.0f), jkl::Vec3(1.0f, 0.0f, 0.0f));
  T = jkl::Scale(T, jkl::Vec3(5.0f, 5.0f, 5.0f));
  end = std::chrono::high_resolution_clock::now();
  long long tJ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

  std::printf("tJackal=%llu ms tGLM=%llu ms\n", tJ, tG);
  jkl::Mat4 C = B;
  C = C.Inverse();
  jkl::Quat q0(1.0f, 0.0f, 0.0f, 2.0f);
  jkl::Quat q1(3.0f, -1.0f, 4.0f, 3.0f);
  jkl::Quat ans = q0 * q1;
  ans = ans.Inverse();
  std::printf("quat ans: w=>%f x=>%f y=>%f z=>%f\n",
    ans.w, ans.x, ans.y, ans.z);
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(5) << A[i][j] << " ";
    }
    std::cout << "\n";
  }
  std::cout << "\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(5) << B[i][j] << " ";
    }
    std::cout << "\n";
  }

  std::cout << "\nJackal Math library:\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(15) << T[i][j] << " ";
    }
    std::cout << "\n";
  } glm::mat4 m;
  std::cout << "\nGLM library:\n";
  for (jkl::uint32 i = 0; i < 4; ++i) {
    for (jkl::uint32 j = 0; j < 4; ++j) {
      std::cout << std::setw(15) << glmT[i][j] << " ";
    }
    std::cout << "\n";
  }
  std::cout << "\nDeterminant of B is: " << B.Determinant() << "\n";
  jkl::Vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);
  jkl::Vec3 a(1.0f, 2.0f, 3.0f);
  jkl::Vec3 b(4.0f, 5.0f, 6.0f);
  //a *= b;
  std::printf("Vector values: x=%f y=%f z=%f w=%f\n", vec.r, vec.g, vec.b, vec.a);
  jkl::Vec3 c = Cross(a, b);
  bool yup = A == B;
  std::printf("Vector operation: x=%f y=%f z=%f\n", c.x, c.y, c.z);
  std::printf("a < c: %d\n", yup);

}

void MatrixTesting()
{
  // ehh
}
} // coretest
<|endoftext|>


<commit_before>/*
  Q Light Controller Plus
  webaccessnetwork.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QNetworkInterface>
#include <QTextStream>
#include <QStringList>
#include <QDebug>
#include <QFile>

#include "webaccessnetwork.h"
#include "commonjscss.h"
#include "qlcconfig.h"

#define IFACES_SYSTEM_FILE "/etc/network/interfaces"

WebAccessNetwork::WebAccessNetwork(QObject *parent) :
    QObject(parent)
{
}

void WebAccessNetwork::resetInterface(InterfaceInfo *iface)
{
    iface->name = "";
    iface->isStatic = false;
    iface->isWireless = false;
    iface->address = "";
    iface->gateway = "";
    iface->gateway = "";
    iface->enabled = false;
    iface->ssid = "";
    iface->wpaPass = "";
}

void WebAccessNetwork::appendInterface(InterfaceInfo iface)
{
    m_interfaces.append(iface);
}

QString WebAccessNetwork::getInterfaceHTML(InterfaceInfo *iface)
{
    QString dhcpChk = iface->isStatic?QString():QString("checked");
    QString staticChk = iface->isStatic?QString("checked"):QString();
    QString visibility = iface->isStatic?QString("visible"):QString("hidden");
    QString html = "
\n";
    html += "
";

    html += tr("Network interface: ") + iface->name + "
\n";

    html += "<form style=\"margin: 5px 15px; color:#FFF;\">\n";
    if (iface->isWireless)
    {
        html += tr("Access point name (SSID): ") + "<input type=\"text\" id=\"" +
                iface->name + "SSID\" size=\"15\" value=\"" + iface->ssid + "\">
\n";
        html += tr("WPA-PSK Password: ") + "<input type=\"text\" id=\"" +
                iface->name + "WPAPSK\" size=\"15\" value=\"" + iface->wpaPass + "\">
\n";
    }
    /** IP mode radio buttons */
    html += "<input type=\"radio\" name=" + iface->name + "NetGroup onclick=\"showStatic('" +
            iface->name + "', false);\" value=\"dhcp\" " + dhcpChk + ">" + tr("Dynamic (DHCP)") + "
\n";
    html += "<input type=\"radio\" name=" + iface->name + "NetGroup onclick=\"showStatic('" +
            iface->name + "', true);\" value=\"static\" " + staticChk + ">" + tr("Static") + "
\n";

    /** Static IP fields */
    html += "
name + "StaticFields\" style=\"padding: 5px 30px; visibility:" + visibility + ";\">\n";
    html += tr("IP Address: ") + "<input type=\"text\" id=\"" +
            iface->name + "IPaddr\" size=\"15\" value=\"" + iface->address + "\">
\n";
    html += tr("Netmask: ") + "<input type=\"text\" id=\"" +
            iface->name + "Netmask\" size=\"15\" value=\"" + iface->netmask + "\">
\n";
    html += tr("Gateway: ") + "<input type=\"text\" size=\"15\" id=\"" +
            iface->name + "Gateway\" value=\"" + iface->gateway + "\">
\n";
    html += "
\n";
    html += "<input type=\"button\" value=\"" + tr("Apply changes") + "\" onclick=\"applyParams('" + iface->name + "');\" >\n";
    html += "</form>

";

    return html;
}

QString WebAccessNetwork::getNetworkHTML()
{
    QStringList systemDevs;
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
        systemDevs.append(interface.name());

    QFile netFile(IFACES_SYSTEM_FILE);
    if (netFile.open(QIODevice::ReadOnly | QIODevice::Text) == false)
        return "";

    m_interfaces.clear();
    InterfaceInfo currInterface;
    resetInterface(&currInterface);

    QString html = "";

    QTextStream in(&netFile);
    while ( !in.atEnd() )
    {
        QString line = in.readLine();
        line = line.simplified();
        // ignore comments
        if (line.startsWith('#'))
            continue;

        QStringList ifaceRow = line.split(" ");
        if (ifaceRow.count() == 0)
            continue;

        QString keyword = ifaceRow.at(0);
        if (keyword == "iface")
        {
            if (currInterface.isStatic == true)
            {
                html += getInterfaceHTML(&currInterface);
                appendInterface(currInterface);
                resetInterface(&currInterface);
            }

            if (ifaceRow.count() < 4)
                continue;

            currInterface.name = ifaceRow.at(1);
            // remove the interface from the system list
            // the remaining interfaces will be added at the
            // end as disabled interfaces
            systemDevs.removeOne(currInterface.name);

            if (currInterface.name.contains("wlan") || currInterface.name.contains("ra"))
                currInterface.isWireless = true;

            if (ifaceRow.at(3) == "dhcp")
            {
                html += getInterfaceHTML(&currInterface);
                appendInterface(currInterface);
                resetInterface(&currInterface);
            }
            else if (ifaceRow.at(3) == "static")
                currInterface.isStatic = true;
        }
        else if (keyword == "address")
            currInterface.address = ifaceRow.at(1);
        else if (keyword == "netmask")
            currInterface.netmask = ifaceRow.at(1);
        else if (keyword == "gateway")
            currInterface.gateway = ifaceRow.at(1);
        else if (keyword == "wpa-ssid")
            currInterface.ssid = ifaceRow.at(1);
        else if (keyword == "wpa-psk")
            currInterface.wpaPass = ifaceRow.at(1);

        currInterface.enabled = true;
    }

    netFile.close();

    if (currInterface.isStatic == true)
    {
        html += getInterfaceHTML(&currInterface);
        appendInterface(currInterface);
        resetInterface(&currInterface);
    }

    foreach(QString dev, systemDevs)
    {
        currInterface.name = dev;
        currInterface.enabled = false;
        if (currInterface.name.contains("wlan") || currInterface.name.contains("ra"))
            currInterface.isWireless = true;
        html += getInterfaceHTML(&currInterface);
        appendInterface(currInterface);
        resetInterface(&currInterface);
    }

    foreach (InterfaceInfo info, m_interfaces)
    {
        qDebug() << "Interface:" << info.name << "isstatic:" << info.isStatic;
    }

    return html;
}

QString WebAccessNetwork::getHTML()
{
    QString m_JScode = "\n";
    m_JScode += "\n";

    QString m_CSScode = "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"common.css\">\n";
    m_CSScode += "\n";

    QString bodyHTML = "
\n"
                       "" + tr("Back") + "\n"
                       "
" + QString(APPNAME) + " " + QString(APPVERSION) + "
\n"
                       "
\n";

    bodyHTML += "
";
    bodyHTML += tr("Network configuration") + "
\n";
    bodyHTML += getNetworkHTML();

    bodyHTML += "
";
    bodyHTML += tr("Project autostart") + "
\n";
    bodyHTML += "
";
    bodyHTML += "<form style=\"margin: 5px 15px; color:#FFF;\">\n";
    bodyHTML += "<input type=\"radio\" name=autostart value=\"none\">" + tr("No project") + "\n";
    bodyHTML += "<input type=\"radio\" name=autostart value=\"current\" checked>" + tr("Use current project") + "\n";
    bodyHTML += "<input type=\"button\" value=\"" + tr("Apply changes") + "\" onclick=\"setAutostart();\" >\n";
    bodyHTML += "</form>
\n";

    bodyHTML += "
\n";
    bodyHTML += "" + tr("Reboot") + "\n";
    bodyHTML += "" + tr("Shutdown") + "\n";
    bodyHTML += "
\n";

    QString str = HTML_HEADER + m_JScode + m_CSScode + "\n\n" + bodyHTML + "\n";

    return str;
}

bool WebAccessNetwork::updateNetworkFile(QStringList cmdList)
{
    for (int i = 0; i < m_interfaces.count(); i++)
    {
        if (m_interfaces.at(i).name == cmdList.at(2))
        {
            m_interfaces[i].enabled = true;
            if (cmdList.at(3) == "static")
                m_interfaces[i].isStatic = true;
            else
                m_interfaces[i].isStatic = false;
            m_interfaces[i].address = cmdList.at(4);
            m_interfaces[i].netmask = cmdList.at(5);
            m_interfaces[i].gateway = cmdList.at(6);
            if (m_interfaces[i].isWireless == true)
            {
                m_interfaces[i].ssid = cmdList.at(7);
                m_interfaces[i].wpaPass = cmdList.at(8);
            }
            return writeNetworkFile();
        }
    }
    return false;
}

bool WebAccessNetwork::writeNetworkFile()
{
    QFile netFile(IFACES_SYSTEM_FILE);
    if (netFile.open(QIODevice::WriteOnly | QIODevice::Text) == false)
        return false;

    netFile.write(QString("auto lo\n").toLatin1());
    netFile.write(QString("iface lo inet loopback\n").toLatin1());
    netFile.write(QString("allow-hotplug eth0\n").toLatin1());

    foreach (InterfaceInfo iface, m_interfaces)
    {
        if (iface.enabled == false)
            continue;

        if (iface.isWireless)
            netFile.write((QString("auto %1\n").arg(iface.name)).toLatin1());

        if (iface.isStatic == false)
            netFile.write((QString("iface %1 inet dhcp\n").arg(iface.name)).toLatin1());
        else
        {
            netFile.write((QString("iface %1 inet static\n").arg(iface.name)).toLatin1());
            netFile.write((QString("  address %1\n").arg(iface.address)).toLatin1());
            netFile.write((QString("  netmask %1\n").arg(iface.netmask)).toLatin1());
            netFile.write((QString("  gateway %1\n").arg(iface.gateway)).toLatin1());
        }
        if (iface.isWireless)
        {
            if (iface.ssid.isEmpty() == false)
                netFile.write((QString("  wpa-ssid %1\n").arg(iface.ssid)).toLatin1());
            if (iface.wpaPass.isEmpty() == false)
                netFile.write((QString("  wpa-psk %1\n").arg(iface.wpaPass)).toLatin1());
        }
    }

    netFile.close();

    return true;
}

<commit_msg>webaccess: improved interfaces file parsing<commit_after>/*
  Q Light Controller Plus
  webaccessnetwork.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QNetworkInterface>
#include <QTextStream>
#include <QStringList>
#include <QDebug>
#include <QFile>

#include "webaccessnetwork.h"
#include "commonjscss.h"
#include "qlcconfig.h"

#define IFACES_SYSTEM_FILE "/etc/network/interfaces"

WebAccessNetwork::WebAccessNetwork(QObject *parent) :
    QObject(parent)
{
}

void WebAccessNetwork::resetInterface(InterfaceInfo *iface)
{
    iface->name = "";
    iface->isStatic = false;
    iface->isWireless = false;
    iface->address = "";
    iface->gateway = "";
    iface->gateway = "";
    iface->enabled = false;
    iface->ssid = "";
    iface->wpaPass = "";
}

void WebAccessNetwork::appendInterface(InterfaceInfo iface)
{
    m_interfaces.append(iface);
}

QString WebAccessNetwork::getInterfaceHTML(InterfaceInfo *iface)
{
    QString dhcpChk = iface->isStatic?QString():QString("checked");
    QString staticChk = iface->isStatic?QString("checked"):QString();
    QString visibility = iface->isStatic?QString("visible"):QString("hidden");
    QString html = "
\n";
    html += "
";

    html += tr("Network interface: ") + iface->name + "
\n";

    html += "<form style=\"margin: 5px 15px; color:#FFF;\">\n";
    if (iface->isWireless)
    {
        html += tr("Access point name (SSID): ") + "<input type=\"text\" id=\"" +
                iface->name + "SSID\" size=\"15\" value=\"" + iface->ssid + "\">
\n";
        html += tr("WPA-PSK Password: ") + "<input type=\"text\" id=\"" +
                iface->name + "WPAPSK\" size=\"15\" value=\"" + iface->wpaPass + "\">
\n";
    }
    /** IP mode radio buttons */
    html += "<input type=\"radio\" name=" + iface->name + "NetGroup onclick=\"showStatic('" +
            iface->name + "', false);\" value=\"dhcp\" " + dhcpChk + ">" + tr("Dynamic (DHCP)") + "
\n";
    html += "<input type=\"radio\" name=" + iface->name + "NetGroup onclick=\"showStatic('" +
            iface->name + "', true);\" value=\"static\" " + staticChk + ">" + tr("Static") + "
\n";

    /** Static IP fields */
    html += "
name + "StaticFields\" style=\"padding: 5px 30px; visibility:" + visibility + ";\">\n";
    html += tr("IP Address: ") + "<input type=\"text\" id=\"" +
            iface->name + "IPaddr\" size=\"15\" value=\"" + iface->address + "\">
\n";
    html += tr("Netmask: ") + "<input type=\"text\" id=\"" +
            iface->name + "Netmask\" size=\"15\" value=\"" + iface->netmask + "\">
\n";
    html += tr("Gateway: ") + "<input type=\"text\" size=\"15\" id=\"" +
            iface->name + "Gateway\" value=\"" + iface->gateway + "\">
\n";
    html += "
\n";
    html += "<input type=\"button\" value=\"" + tr("Apply changes") + "\" onclick=\"applyParams('" + iface->name + "');\" >\n";
    html += "</form>

";

    return html;
}

QString WebAccessNetwork::getNetworkHTML()
{
    QStringList systemDevs;
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
        systemDevs.append(interface.name());

    QFile netFile(IFACES_SYSTEM_FILE);
    if (netFile.open(QIODevice::ReadOnly | QIODevice::Text) == false)
        return "";

    m_interfaces.clear();
    InterfaceInfo currInterface;
    resetInterface(&currInterface);

    QString html = "";

    QTextStream in(&netFile);
    while ( !in.atEnd() )
    {
        QString line = in.readLine();
        line = line.simplified();
        // ignore comments
        if (line.startsWith('#'))
            continue;

        QStringList ifaceRow = line.split(" ");
        if (ifaceRow.count() == 0)
            continue;

        QString keyword = ifaceRow.at(0);
        if (keyword == "iface")
        {
            if (currInterface.isStatic == true)
            {
                html += getInterfaceHTML(&currInterface);
                appendInterface(currInterface);
                resetInterface(&currInterface);
            }

            if (ifaceRow.count() < 4)
                continue;

            currInterface.name = ifaceRow.at(1);
            // remove the interface from the system list
            // the remaining interfaces will be added at the
            // end as disabled interfaces
            systemDevs.removeOne(currInterface.name);

            if (currInterface.name.contains("wlan") || currInterface.name.contains("ra"))
                currInterface.isWireless = true;

            if (ifaceRow.at(3) == "dhcp" || ifaceRow.at(3) == "manual")
            {
                html += getInterfaceHTML(&currInterface);
                appendInterface(currInterface);
                resetInterface(&currInterface);
            }
            else if (ifaceRow.at(3) == "static")
                currInterface.isStatic = true;
        }
        else if (keyword == "address")
            currInterface.address = ifaceRow.at(1);
        else if (keyword == "netmask")
            currInterface.netmask = ifaceRow.at(1);
        else if (keyword == "gateway")
            currInterface.gateway = ifaceRow.at(1);
        else if (keyword == "wpa-ssid")
            currInterface.ssid = ifaceRow.at(1);
        else if (keyword == "wpa-psk")
            currInterface.wpaPass = ifaceRow.at(1);

        currInterface.enabled = true;
    }

    netFile.close();

    if (currInterface.isStatic == true)
    {
        html += getInterfaceHTML(&currInterface);
        appendInterface(currInterface);
        resetInterface(&currInterface);
    }

    foreach(QString dev, systemDevs)
    {
        currInterface.name = dev;
        currInterface.enabled = false;
        if (currInterface.name.contains("wlan") || currInterface.name.contains("ra"))
            currInterface.isWireless = true;
        html += getInterfaceHTML(&currInterface);
        appendInterface(currInterface);
        resetInterface(&currInterface);
    }

    foreach (InterfaceInfo info, m_interfaces)
    {
        qDebug() << "Interface:" << info.name << "isstatic:" << info.isStatic;
    }

    return html;
}

QString WebAccessNetwork::getHTML()
{
    QString m_JScode = "\n";
    m_JScode += "\n";

    QString m_CSScode = "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"common.css\">\n";
    m_CSScode += "\n";

    QString bodyHTML = "
\n"
                       "" + tr("Back") + "\n"
                       "
" + QString(APPNAME) + " " + QString(APPVERSION) + "
\n"
                       "
\n";

    bodyHTML += "
";
    bodyHTML += tr("Network configuration") + "
\n";
    bodyHTML += getNetworkHTML();

    bodyHTML += "
";
    bodyHTML += tr("Project autostart") + "
\n";
    bodyHTML += "
";
    bodyHTML += "<form style=\"margin: 5px 15px; color:#FFF;\">\n";
    bodyHTML += "<input type=\"radio\" name=autostart value=\"none\">" + tr("No project") + "\n";
    bodyHTML += "<input type=\"radio\" name=autostart value=\"current\" checked>" + tr("Use current project") + "\n";
    bodyHTML += "<input type=\"button\" value=\"" + tr("Apply changes") + "\" onclick=\"setAutostart();\" >\n";
    bodyHTML += "</form>
\n";

    bodyHTML += "
\n";
    bodyHTML += "" + tr("Reboot") + "\n";
    bodyHTML += "" + tr("Shutdown") + "\n";
    bodyHTML += "
\n";

    QString str = HTML_HEADER + m_JScode + m_CSScode + "\n\n" + bodyHTML + "\n";

    return str;
}

bool WebAccessNetwork::updateNetworkFile(QStringList cmdList)
{
    for (int i = 0; i < m_interfaces.count(); i++)
    {
        if (m_interfaces.at(i).name == cmdList.at(2))
        {
            m_interfaces[i].enabled = true;
            if (cmdList.at(3) == "static")
                m_interfaces[i].isStatic = true;
            else
                m_interfaces[i].isStatic = false;
            m_interfaces[i].address = cmdList.at(4);
            m_interfaces[i].netmask = cmdList.at(5);
            m_interfaces[i].gateway = cmdList.at(6);
            if (m_interfaces[i].isWireless == true)
            {
                m_interfaces[i].ssid = cmdList.at(7);
                m_interfaces[i].wpaPass = cmdList.at(8);
            }
            return writeNetworkFile();
        }
    }
    return false;
}

bool WebAccessNetwork::writeNetworkFile()
{
    QFile netFile(IFACES_SYSTEM_FILE);
    if (netFile.open(QIODevice::WriteOnly | QIODevice::Text) == false)
        return false;

    netFile.write(QString("auto lo\n").toLatin1());
    netFile.write(QString("iface lo inet loopback\n").toLatin1());
    netFile.write(QString("allow-hotplug eth0\n").toLatin1());

    foreach (InterfaceInfo iface, m_interfaces)
    {
        if (iface.enabled == false)
            continue;

        if (iface.isWireless)
            netFile.write((QString("auto %1\n").arg(iface.name)).toLatin1());

        if (iface.isStatic == false)
            netFile.write((QString("iface %1 inet dhcp\n").arg(iface.name)).toLatin1());
        else
        {
            netFile.write((QString("iface %1 inet static\n").arg(iface.name)).toLatin1());
            netFile.write((QString("  address %1\n").arg(iface.address)).toLatin1());
            netFile.write((QString("  netmask %1\n").arg(iface.netmask)).toLatin1());
            netFile.write((QString("  gateway %1\n").arg(iface.gateway)).toLatin1());
        }
        if (iface.isWireless)
        {
            if (iface.ssid.isEmpty() == false)
                netFile.write((QString("  wpa-ssid %1\n").arg(iface.ssid)).toLatin1());
            if (iface.wpaPass.isEmpty() == false)
                netFile.write((QString("  wpa-psk %1\n").arg(iface.wpaPass)).toLatin1());
        }
    }

    netFile.close();

    return true;
}

<|endoftext|>


<commit_before><commit_msg>Properly find Frame from Node context<commit_after><|endoftext|>


<commit_before>#include "game.hpp"

void Game::sortMoves(MoveArray& result, int depth) {
	int num_attacks = result.num_attacks;

	/*if(game_board.whiteMove) {
		for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) {
			for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
				std::swap(result.moveArray[j], result.moveArray[j+1]);
			}
		}
	} else {
		for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) {
			for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
				std::swap(result.moveArray[j], result.moveArray[j+1]);
			}
		}
	}*/

	for(unsigned int i = num_attacks; i < result.count; ++i) {
		if(game_board.whiteMove) {
			if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move);

				break;
			}
		} else {
			if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move);

				break;
			}
		}
	}

	uint64_t hash = game_board.getColorHash();
	if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) {
		if(boardHash[hash & hash_cutter].key == hash) {
			for(unsigned int i = 0; i < result.count; ++i) {
				if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) {
					BitMove tmp = (BitMove)result.moveArray[i];
					result.moveArray.erase(result.moveArray.begin() + i);
					result.moveArray.emplace(result.moveArray.begin(), tmp);
					result.moveArray[0].fromHash = true;
					break;
				}
			}
		}
	}
}

void Game::sortAttacks(MoveArray& moves) {
	std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks);
}
<commit_msg>исправлены ошибки в эвристике истории<commit_after>#include "game.hpp"

void Game::sortMoves(MoveArray& result, int depth) {
	int num_attacks = result.num_attacks;

	if(result.num_attacks >= 0 && result.num_attacks < result.moveArray.size() && result.count >= 1 && result.count < result.moveArray.size()) {
		if(game_board.whiteMove) {
			for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		} else {
			for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		}
	}

	for(unsigned int i = num_attacks; i < result.count; ++i) {
		if(game_board.whiteMove) {
			if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move);

				break;
			}
		} else {
			if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move);

				break;
			}
		}
	}

	uint64_t hash = game_board.getColorHash();
	if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) {
		if(boardHash[hash & hash_cutter].key == hash) {
			for(unsigned int i = 0; i < result.count; ++i) {
				if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) {
					BitMove tmp = (BitMove)result.moveArray[i];
					result.moveArray.erase(result.moveArray.begin() + i);
					result.moveArray.emplace(result.moveArray.begin(), tmp);
					result.moveArray[0].fromHash = true;
					break;
				}
			}
		}
	}
}

void Game::sortAttacks(MoveArray& moves) {
	std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks);
}
<|endoftext|>


<commit_before><commit_msg>Disallow setting the rate to values that would cause busy loops (< 1/16x) or rendering issues (> 16x) BUG=18362 TEST=none Review URL: http://codereview.chromium.org/164032<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "TopDownViewItemModel.h"

TopDownViewItemModel::TopDownViewItemModel(std::unique_ptr<TopDownView> top_down_view,
                                           QObject* parent)
    : QAbstractItemModel{parent}, top_down_view_{std::move(top_down_view)} {}

QVariant TopDownViewItemModel::GetDisplayRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto thread_item = dynamic_cast<TopDownThread*>(item);
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (thread_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        if (thread_item->thread_id() == SamplingProfiler::kAllThreadsFakeTid) {
          return QString::fromStdString(
              thread_item->thread_name().empty()
                  ? "(all threads)"
                  : absl::StrFormat("%s (all threads)", thread_item->thread_name()));
        } else {
          return QString::fromStdString(thread_item->thread_name().empty()
                                            ? std::to_string(thread_item->thread_id())
                                            : absl::StrFormat("%s [%d]", thread_item->thread_name(),
                                                              thread_item->thread_id()));
        }
      case kInclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", thread_item->GetInclusivePercent(top_down_view_->sample_count()),
            thread_item->sample_count()));
      case kOfParent:
        return QString::fromStdString(absl::StrFormat("%.2f%%", thread_item->GetPercentOfParent()));
    }
  } else if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kInclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", function_item->GetInclusivePercent(top_down_view_->sample_count()),
            function_item->sample_count()));
      case kExclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", function_item->GetExclusivePercent(top_down_view_->sample_count()),
            function_item->GetExclusiveSampleCount()));
      case kOfParent:
        return QString::fromStdString(
            absl::StrFormat("%.2f%%", function_item->GetPercentOfParent()));
      case kModule:
        return QString::fromStdString(function_item->GetModuleName());
      case kFunctionAddress:
        return QString::fromStdString(
            absl::StrFormat("%#llx", function_item->function_absolute_address()));
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetEditRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto thread_item = dynamic_cast<TopDownThread*>(item);
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (thread_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        // Threads are sorted by tid, not by name.
        return thread_item->thread_id();
      case kInclusive:
        return thread_item->GetInclusivePercent(top_down_view_->sample_count());
      case kOfParent:
        return thread_item->GetPercentOfParent();
    }
  } else if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kInclusive:
        return function_item->GetInclusivePercent(top_down_view_->sample_count());
      case kExclusive:
        return function_item->GetExclusivePercent(top_down_view_->sample_count());
      case kOfParent:
        return function_item->GetPercentOfParent();
      case kModule:
        return QString::fromStdString(function_item->GetModuleName());
      case kFunctionAddress:
        return static_cast<qulonglong>(function_item->function_absolute_address());
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetToolTipRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kModule:
        return QString::fromStdString(function_item->module_path());
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetModulePathRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (function_item != nullptr) {
    return QString::fromStdString(function_item->module_path());
  }
  return QVariant();
}

QVariant TopDownViewItemModel::data(const QModelIndex& index, int role) const {
  if (!index.isValid()) {
    return QVariant();
  }
  switch (role) {
    case Qt::DisplayRole:
      return GetDisplayRoleData(index);
    // The value returned when role == Qt::EditRole is used for sorting.
    case Qt::EditRole:
      return GetEditRoleData(index);
    // When role == Qt::ToolTipRole more detailed information than it's shown is returned.
    case Qt::ToolTipRole:
      return GetToolTipRoleData(index);
    case kModulePathRole:
      return GetModulePathRoleData(index);
  }
  return QVariant();
}

Qt::ItemFlags TopDownViewItemModel::flags(const QModelIndex& index) const {
  if (!index.isValid()) {
    return Qt::NoItemFlags;
  }
  return QAbstractItemModel::flags(index);
}

QVariant TopDownViewItemModel::headerData(int section, Qt::Orientation orientation,
                                          int role) const {
  if (orientation != Qt::Horizontal) {
    return QVariant();
  }
  switch (role) {
    case Qt::DisplayRole: {
      switch (section) {
        case Columns::kThreadOrFunction:
          return "Thread / Function";
        case Columns::kInclusive:
          return "Inclusive";
        case Columns::kExclusive:
          return "Exclusive";
        case Columns::kOfParent:
          return "Of parent";
        case Columns::kModule:
          return "Module";
        case Columns::kFunctionAddress:
          return "Function address";
      }
    } break;
    case Qt::InitialSortOrderRole: {
      switch (section) {
        case Columns::kThreadOrFunction:
          return Qt::AscendingOrder;
        case Columns::kInclusive:
          return Qt::DescendingOrder;
        case Columns::kExclusive:
          return Qt::DescendingOrder;
        case Columns::kOfParent:
          return Qt::DescendingOrder;
        case Columns::kModule:
          return Qt::AscendingOrder;
        case Columns::kFunctionAddress:
          return Qt::AscendingOrder;
      }
    } break;
  }
  return QVariant();
}

QModelIndex TopDownViewItemModel::index(int row, int column, const QModelIndex& parent) const {
  if (!hasIndex(row, column, parent)) {
    return QModelIndex();
  }

  TopDownNode* parent_item;
  if (!parent.isValid()) {
    parent_item = top_down_view_.get();
  } else {
    parent_item = static_cast<TopDownInternalNode*>(parent.internalPointer());
  }

  const std::vector<const TopDownNode*>& siblings = parent_item->children();
  if (row < 0 || static_cast<size_t>(row) >= siblings.size()) {
    return QModelIndex();
  }
  const TopDownNode* item = siblings[row];
  return createIndex(row, column, const_cast<TopDownNode*>(item));
}

QModelIndex TopDownViewItemModel::parent(const QModelIndex& index) const {
  if (!index.isValid()) {
    return QModelIndex();
  }

  auto* child_item = static_cast<TopDownNode*>(index.internalPointer());
  const TopDownNode* item = child_item->parent();
  if (item == top_down_view_.get()) {
    return QModelIndex();
  }

  const TopDownNode* parent_item = item->parent();
  if (parent_item == nullptr) {
    return createIndex(0, 0, const_cast<TopDownNode*>(item));
  }

  const std::vector<const TopDownNode*>& siblings = parent_item->children();
  int row = static_cast<int>(
      std::distance(siblings.begin(), std::find(siblings.begin(), siblings.end(), item)));
  return createIndex(row, 0, const_cast<TopDownNode*>(item));
}

int TopDownViewItemModel::rowCount(const QModelIndex& parent) const {
  if (parent.column() > 0) {
    return 0;
  }
  if (!parent.isValid()) {
    return top_down_view_->child_count();
  }
  auto* item = static_cast<TopDownNode*>(parent.internalPointer());
  return item->child_count();
}

int TopDownViewItemModel::columnCount(const QModelIndex& /*parent*/) const { return kColumnCount; }
<commit_msg>Don't show percentage "Of parent" for a thread in the top-down view<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "TopDownViewItemModel.h"

TopDownViewItemModel::TopDownViewItemModel(std::unique_ptr<TopDownView> top_down_view,
                                           QObject* parent)
    : QAbstractItemModel{parent}, top_down_view_{std::move(top_down_view)} {}

QVariant TopDownViewItemModel::GetDisplayRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto thread_item = dynamic_cast<TopDownThread*>(item);
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (thread_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        if (thread_item->thread_id() == SamplingProfiler::kAllThreadsFakeTid) {
          return QString::fromStdString(
              thread_item->thread_name().empty()
                  ? "(all threads)"
                  : absl::StrFormat("%s (all threads)", thread_item->thread_name()));
        } else {
          return QString::fromStdString(thread_item->thread_name().empty()
                                            ? std::to_string(thread_item->thread_id())
                                            : absl::StrFormat("%s [%d]", thread_item->thread_name(),
                                                              thread_item->thread_id()));
        }
      case kInclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", thread_item->GetInclusivePercent(top_down_view_->sample_count()),
            thread_item->sample_count()));
    }
  } else if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kInclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", function_item->GetInclusivePercent(top_down_view_->sample_count()),
            function_item->sample_count()));
      case kExclusive:
        return QString::fromStdString(absl::StrFormat(
            "%.2f%% (%llu)", function_item->GetExclusivePercent(top_down_view_->sample_count()),
            function_item->GetExclusiveSampleCount()));
      case kOfParent:
        return QString::fromStdString(
            absl::StrFormat("%.2f%%", function_item->GetPercentOfParent()));
      case kModule:
        return QString::fromStdString(function_item->GetModuleName());
      case kFunctionAddress:
        return QString::fromStdString(
            absl::StrFormat("%#llx", function_item->function_absolute_address()));
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetEditRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto thread_item = dynamic_cast<TopDownThread*>(item);
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (thread_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        // Threads are sorted by tid, not by name.
        return thread_item->thread_id();
      case kInclusive:
        return thread_item->GetInclusivePercent(top_down_view_->sample_count());
    }
  } else if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kInclusive:
        return function_item->GetInclusivePercent(top_down_view_->sample_count());
      case kExclusive:
        return function_item->GetExclusivePercent(top_down_view_->sample_count());
      case kOfParent:
        return function_item->GetPercentOfParent();
      case kModule:
        return QString::fromStdString(function_item->GetModuleName());
      case kFunctionAddress:
        return static_cast<qulonglong>(function_item->function_absolute_address());
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetToolTipRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (function_item != nullptr) {
    switch (index.column()) {
      case kThreadOrFunction:
        return QString::fromStdString(function_item->function_name());
      case kModule:
        return QString::fromStdString(function_item->module_path());
    }
  }
  return QVariant();
}

QVariant TopDownViewItemModel::GetModulePathRoleData(const QModelIndex& index) const {
  CHECK(index.isValid());
  auto* item = static_cast<TopDownNode*>(index.internalPointer());
  auto function_item = dynamic_cast<TopDownFunction*>(item);
  if (function_item != nullptr) {
    return QString::fromStdString(function_item->module_path());
  }
  return QVariant();
}

QVariant TopDownViewItemModel::data(const QModelIndex& index, int role) const {
  if (!index.isValid()) {
    return QVariant();
  }
  switch (role) {
    case Qt::DisplayRole:
      return GetDisplayRoleData(index);
    // The value returned when role == Qt::EditRole is used for sorting.
    case Qt::EditRole:
      return GetEditRoleData(index);
    // When role == Qt::ToolTipRole more detailed information than it's shown is returned.
    case Qt::ToolTipRole:
      return GetToolTipRoleData(index);
    case kModulePathRole:
      return GetModulePathRoleData(index);
  }
  return QVariant();
}

Qt::ItemFlags TopDownViewItemModel::flags(const QModelIndex& index) const {
  if (!index.isValid()) {
    return Qt::NoItemFlags;
  }
  return QAbstractItemModel::flags(index);
}

QVariant TopDownViewItemModel::headerData(int section, Qt::Orientation orientation,
                                          int role) const {
  if (orientation != Qt::Horizontal) {
    return QVariant();
  }
  switch (role) {
    case Qt::DisplayRole: {
      switch (section) {
        case Columns::kThreadOrFunction:
          return "Thread / Function";
        case Columns::kInclusive:
          return "Inclusive";
        case Columns::kExclusive:
          return "Exclusive";
        case Columns::kOfParent:
          return "Of parent";
        case Columns::kModule:
          return "Module";
        case Columns::kFunctionAddress:
          return "Function address";
      }
    } break;
    case Qt::InitialSortOrderRole: {
      switch (section) {
        case Columns::kThreadOrFunction:
          return Qt::AscendingOrder;
        case Columns::kInclusive:
          return Qt::DescendingOrder;
        case Columns::kExclusive:
          return Qt::DescendingOrder;
        case Columns::kOfParent:
          return Qt::DescendingOrder;
        case Columns::kModule:
          return Qt::AscendingOrder;
        case Columns::kFunctionAddress:
          return Qt::AscendingOrder;
      }
    } break;
  }
  return QVariant();
}

QModelIndex TopDownViewItemModel::index(int row, int column, const QModelIndex& parent) const {
  if (!hasIndex(row, column, parent)) {
    return QModelIndex();
  }

  TopDownNode* parent_item;
  if (!parent.isValid()) {
    parent_item = top_down_view_.get();
  } else {
    parent_item = static_cast<TopDownInternalNode*>(parent.internalPointer());
  }

  const std::vector<const TopDownNode*>& siblings = parent_item->children();
  if (row < 0 || static_cast<size_t>(row) >= siblings.size()) {
    return QModelIndex();
  }
  const TopDownNode* item = siblings[row];
  return createIndex(row, column, const_cast<TopDownNode*>(item));
}

QModelIndex TopDownViewItemModel::parent(const QModelIndex& index) const {
  if (!index.isValid()) {
    return QModelIndex();
  }

  auto* child_item = static_cast<TopDownNode*>(index.internalPointer());
  const TopDownNode* item = child_item->parent();
  if (item == top_down_view_.get()) {
    return QModelIndex();
  }

  const TopDownNode* parent_item = item->parent();
  if (parent_item == nullptr) {
    return createIndex(0, 0, const_cast<TopDownNode*>(item));
  }

  const std::vector<const TopDownNode*>& siblings = parent_item->children();
  int row = static_cast<int>(
      std::distance(siblings.begin(), std::find(siblings.begin(), siblings.end(), item)));
  return createIndex(row, 0, const_cast<TopDownNode*>(item));
}

int TopDownViewItemModel::rowCount(const QModelIndex& parent) const {
  if (parent.column() > 0) {
    return 0;
  }
  if (!parent.isValid()) {
    return top_down_view_->child_count();
  }
  auto* item = static_cast<TopDownNode*>(parent.internalPointer());
  return item->child_count();
}

int TopDownViewItemModel::columnCount(const QModelIndex& /*parent*/) const { return kColumnCount; }
<|endoftext|>


<commit_before>/***********************************************************************************
**
** FileManager.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "FileManager.h"
#include "../Wisp/WispApplication.h"

CFileManager g_FileManager;
//----------------------------------------------------------------------------------
CFileManager::CFileManager()
: m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0)
{
}
//----------------------------------------------------------------------------------
CFileManager::~CFileManager()
{
}
//----------------------------------------------------------------------------------
bool CFileManager::Load()
{
	if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx")))
		return false;
	else if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul")))
		return false;
	else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul")))
		return false;
	else if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul")))
		return false;
	else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx")))
		return false;
	else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx")))
		return false;
	else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul")))
		return false;
	else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle")))
		return false;
	else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul")))
		return false;
	else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul")))
		return false;
	else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul")))
		return false;
	else if (!m_ArtMul.Load(g_App.FilePath("art.mul")))
		return false;
	else if (!m_HuesMul.Load(g_App.FilePath("hues.mul")))
		return false;
	else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul")))
		return false;
	else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul")))
		return false;
	else if (!m_LightMul.Load(g_App.FilePath("light.mul")))
		return false;
	else if (!m_MultiMul.Load(g_App.FilePath("multi.mul")))
		return false;
	else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul")))
		return false;
	else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul")))
		return false;
	else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul")))
		return false;
	else if (!m_SoundMul.Load(g_App.FilePath("sound.mul")))
		return false;
	else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul")))
		return false;
	else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul")))
		return false;
	m_SpeechMul.Load(g_App.FilePath("speech.mul");
	//m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));

	IFOR(i, 0, 6)
	{
		if (i)
		{
			m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i));
			m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i));
		}

		m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i));
		m_MapMul[i].Load(g_App.FilePath("map%i.mul", i));
		m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i));
		m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i));

		m_MapDifl[i].Load(g_App.FilePath("mapdifl%i.mul", i));
		m_MapDif[i].Load(g_App.FilePath("mapdif%i.mul", i));

		m_StaDifl[i].Load(g_App.FilePath("stadifl%i.mul", i));
		m_StaDifi[i].Load(g_App.FilePath("stadifi%i.mul", i));
		m_StaDif[i].Load(g_App.FilePath("stadif%i.mul", i));
	}

	IFOR(i, 0, 20)
	{
		string s;

		if (i)
			s = g_App.FilePath("unifont%i.mul", i);
		else
			s = g_App.FilePath("unifont.mul");

		if (!m_UnifontMul[i].Load(s) && i > 1)
			break;

		m_UnicodeFontsCount++;
	}

	if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul")))
		m_UseVerdata = false;

	return true;
}
//----------------------------------------------------------------------------------
void CFileManager::Unload()
{
	m_ArtIdx.Unload();
	m_GumpIdx.Unload();
	m_LightIdx.Unload();
	m_MultiIdx.Unload();
	m_SkillsIdx.Unload();
	m_SoundIdx.Unload();
	m_MultiMap.Unload();
	m_TextureIdx.Unload();
	m_SpeechMul.Unload();
	m_AnimdataMul.Unload();
	m_ArtMul.Unload();
	m_HuesMul.Unload();
	m_FontsMul.Unload();
	m_GumpMul.Unload();
	m_LightMul.Unload();
	m_MultiMul.Unload();
	m_PaletteMul.Unload();
	m_RadarcolMul.Unload();
	m_SkillsMul.Unload();
	m_SoundMul.Unload();
	m_TextureMul.Unload();
	m_TiledataMul.Unload();

	m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));

	IFOR(i, 0, 6)
	{
		m_AnimIdx[i].Unload();
		m_StaticIdx[i].Unload();
		m_AnimMul[i].Unload();
		m_MapMul[i].Unload();
		m_StaticMul[i].Unload();
		m_FacetMul[i].Unload();

		m_MapDifl[i].Unload();
		m_MapDif[i].Unload();

		m_StaDifl[i].Unload();
		m_StaDifi[i].Unload();
		m_StaDif[i].Unload();
	}

	IFOR(i, 0, 20)
		m_UnifontMul[i].Unload();

	m_VerdataMul.Unload();
}
//----------------------------------------------------------------------------------<commit_msg>Oops! Typo fix.<commit_after>/***********************************************************************************
**
** FileManager.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "FileManager.h"
#include "../Wisp/WispApplication.h"

CFileManager g_FileManager;
//----------------------------------------------------------------------------------
CFileManager::CFileManager()
: m_UseVerdata(false), m_UseUOP(false), m_UnicodeFontsCount(0)
{
}
//----------------------------------------------------------------------------------
CFileManager::~CFileManager()
{
}
//----------------------------------------------------------------------------------
bool CFileManager::Load()
{
	if (!m_AnimIdx[0].Load(g_App.FilePath("anim.idx")))
		return false;
	else if (!m_ArtIdx.Load(g_App.FilePath("artidx.mul")))
		return false;
	else if (!m_GumpIdx.Load(g_App.FilePath("gumpidx.mul")))
		return false;
	else if (!m_LightIdx.Load(g_App.FilePath("lightidx.mul")))
		return false;
	else if (!m_MultiIdx.Load(g_App.FilePath("multi.idx")))
		return false;
	else if (!m_SkillsIdx.Load(g_App.FilePath("skills.idx")))
		return false;
	else if (!m_SoundIdx.Load(g_App.FilePath("soundidx.mul")))
		return false;
	else if (!m_MultiMap.Load(g_App.FilePath("multimap.rle")))
		return false;
	else if (!m_TextureIdx.Load(g_App.FilePath("texidx.mul")))
		return false;
	else if (!m_AnimMul[0].Load(g_App.FilePath("anim.mul")))
		return false;
	else if (!m_AnimdataMul.Load(g_App.FilePath("animdata.mul")))
		return false;
	else if (!m_ArtMul.Load(g_App.FilePath("art.mul")))
		return false;
	else if (!m_HuesMul.Load(g_App.FilePath("hues.mul")))
		return false;
	else if (!m_FontsMul.Load(g_App.FilePath("fonts.mul")))
		return false;
	else if (!m_GumpMul.Load(g_App.FilePath("gumpart.mul")))
		return false;
	else if (!m_LightMul.Load(g_App.FilePath("light.mul")))
		return false;
	else if (!m_MultiMul.Load(g_App.FilePath("multi.mul")))
		return false;
	else if (!m_PaletteMul.Load(g_App.FilePath("palette.mul")))
		return false;
	else if (!m_RadarcolMul.Load(g_App.FilePath("radarcol.mul")))
		return false;
	else if (!m_SkillsMul.Load(g_App.FilePath("skills.mul")))
		return false;
	else if (!m_SoundMul.Load(g_App.FilePath("sound.mul")))
		return false;
	else if (!m_TextureMul.Load(g_App.FilePath("texmaps.mul")))
		return false;
	else if (!m_TiledataMul.Load(g_App.FilePath("tiledata.mul")))
		return false;
	m_SpeechMul.Load(g_App.FilePath("speech.mul"));
	//m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));

	IFOR(i, 0, 6)
	{
		if (i)
		{
			m_AnimIdx[i].Load(g_App.FilePath("anim%i.idx", i));
			m_AnimMul[i].Load(g_App.FilePath("anim%i.mul", i));
		}

		m_StaticIdx[i].Load(g_App.FilePath("staidx%i.mul", i));
		m_MapMul[i].Load(g_App.FilePath("map%i.mul", i));
		m_StaticMul[i].Load(g_App.FilePath("statics%i.mul", i));
		m_FacetMul[i].Load(g_App.FilePath("facet0%i.mul", i));

		m_MapDifl[i].Load(g_App.FilePath("mapdifl%i.mul", i));
		m_MapDif[i].Load(g_App.FilePath("mapdif%i.mul", i));

		m_StaDifl[i].Load(g_App.FilePath("stadifl%i.mul", i));
		m_StaDifi[i].Load(g_App.FilePath("stadifi%i.mul", i));
		m_StaDif[i].Load(g_App.FilePath("stadif%i.mul", i));
	}

	IFOR(i, 0, 20)
	{
		string s;

		if (i)
			s = g_App.FilePath("unifont%i.mul", i);
		else
			s = g_App.FilePath("unifont.mul");

		if (!m_UnifontMul[i].Load(s) && i > 1)
			break;

		m_UnicodeFontsCount++;
	}

	if (m_UseVerdata && !m_VerdataMul.Load(g_App.FilePath("verdata.mul")))
		m_UseVerdata = false;

	return true;
}
//----------------------------------------------------------------------------------
void CFileManager::Unload()
{
	m_ArtIdx.Unload();
	m_GumpIdx.Unload();
	m_LightIdx.Unload();
	m_MultiIdx.Unload();
	m_SkillsIdx.Unload();
	m_SoundIdx.Unload();
	m_MultiMap.Unload();
	m_TextureIdx.Unload();
	m_SpeechMul.Unload();
	m_AnimdataMul.Unload();
	m_ArtMul.Unload();
	m_HuesMul.Unload();
	m_FontsMul.Unload();
	m_GumpMul.Unload();
	m_LightMul.Unload();
	m_MultiMul.Unload();
	m_PaletteMul.Unload();
	m_RadarcolMul.Unload();
	m_SkillsMul.Unload();
	m_SoundMul.Unload();
	m_TextureMul.Unload();
	m_TiledataMul.Unload();

	m_LangcodeIff.Load(g_App.FilePath("Langcode.iff"));

	IFOR(i, 0, 6)
	{
		m_AnimIdx[i].Unload();
		m_StaticIdx[i].Unload();
		m_AnimMul[i].Unload();
		m_MapMul[i].Unload();
		m_StaticMul[i].Unload();
		m_FacetMul[i].Unload();

		m_MapDifl[i].Unload();
		m_MapDif[i].Unload();

		m_StaDifl[i].Unload();
		m_StaDifi[i].Unload();
		m_StaDif[i].Unload();
	}

	IFOR(i, 0, 20)
		m_UnifontMul[i].Unload();

	m_VerdataMul.Unload();
}
//----------------------------------------------------------------------------------<|endoftext|>