<commit_before>// lcskpp algoritmi

#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <functional>
#include <map>
#include <queue>
#include "utils.h"
#include "pavetic.h"

using namespace std;

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define TRACE(x) cout << #x << " = " << x << endl
#define _ << " _ " <<

typedef long long llint;

const int inf = 1e9;

// obican dp: O(nmk)
int lcskpp_dp(const string& a, const string& b, int k) {
  vector<pair<int, int>> matches_pairs;
  calc_matches(a, b, k, &matches_pairs);

  vector<vector<int>> matches(a.size());
  for (auto& p: matches_pairs) matches[p.first].push_back(p.second);
  int n = a.size();
  int m = b.size();

  vector<vector<int>> f(n, vector<int>(m, 0));

  REP(i, n) {
    REP(j, m) {
      if (i) f[i][j] = max(f[i-1][j], f[i][j]);
      if (j) f[i][j] = max(f[i][j-1], f[i][j]);

      int q = 0;
      while (i-q >= 0 && j-q >= 0 && a[i-q] == b[j-q] && q < 2*k) {
        q++;
        if (q >= k) {
          f[i][j] = max(f[i][j], (i >= q && j >= q ? f[i-q][j-q] : 0) + q);
        }
      }
    }
  }

  return f[n-1][m-1];
}

int lcskpp_better_hunt(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int j = matches[bs_ptr].second;
      int lo = lower_bound(MinYPrefix.begin(), MinYPrefix.begin() + r + 2, j-k+1) - MinYPrefix.begin();
      match_dp[bs_ptr] = lo-1;
      bs_ptr++;
    }

    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      for (int s = 1; s <= k; ++s) {
        MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
      }
      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_better_hunt2(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  if (matches.size() < n+m) {
    sort(matches.begin(), matches.end());
  } else {
    vector<vector<int>> matches_buckets(n);
    for (auto& p: matches) matches_buckets[p.first].push_back(p.second);
    int ptr = 0;
    REP(i, n) {
      sort(matches_buckets[i].begin(), matches_buckets[i].end());
      for (int j: matches_buckets[i]) {
        matches[ptr++] = {i, j};
      }
    }
  }

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int cur_lo = 0;
      int row = matches[bs_ptr].first;
      while (bs_ptr < n_matches && matches[bs_ptr].first == row) {
        int j = matches[bs_ptr].second;

        if (MinYPrefix[cur_lo] < j-k+1) {
          int lo = cur_lo, hi = r+1;
          while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (MinYPrefix[mid] < j - k + 1)
              lo = mid + 1;
            else
              hi = mid;
          }
          cur_lo = lo;
        }

        match_dp[bs_ptr] = cur_lo-1;
        bs_ptr++;
      }
    }

    int prev_l = -1;
    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      if (l > prev_l) {
        for (int s = 1; s <= k; ++s) {
          MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
        }
        prev_l = l;
      }

      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_better_kuo_cross(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  if (matches.size() < n+m) {
    sort(matches.begin(), matches.end());
  } else {
    vector<vector<int>> matches_buckets(n);
    for (auto& p: matches) matches_buckets[p.first].push_back(p.second);
    int ptr = 0;
    REP(i, n) {
      sort(matches_buckets[i].begin(), matches_buckets[i].end());
      for (int j: matches_buckets[i]) {
        matches[ptr++] = {i, j};
      }
    }
  }

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int lo = 0;
      int row = matches[bs_ptr].first;
      while (bs_ptr < n_matches && matches[bs_ptr].first == row) {
        int j = matches[bs_ptr].second;
        while (MinYPrefix[lo] < j-k+1) lo++;
        match_dp[bs_ptr] = lo-1;
        bs_ptr++;
      }
    }

    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      for (int s = 1; s <= k; ++s) {
        MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
      }
      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_pavetic(const string& A, const string& B, int k) {
  int ret;
  Pavetic::lcskpp(A, B, k, &ret, NULL);
  return ret;
}

int lcskpp_pavetic_ubrzan(const string& A, const string& B, int k) {
  vector<pair<int, int>> matches;
  calc_matches(A, B, k, &matches);
  sort(matches.begin(), matches.end());

  int n = 0;
  for (auto& p: matches) {
    n = max(n, max(p.first, p.second));
  }

  // Indexed by column, first:dp value, second:index in matches.
  FenwickMax<pair<int, int> > dp_col_max(n);
  vector<int> dp(matches.size());
  vector<int> recon(matches.size());
  vector<int> continues(matches.size(), -1);

  if (k > 1) {
    auto prev = matches.begin();
    for (auto curr = matches.begin();
         curr != matches.end(); ++curr) {
      auto G = make_pair(curr->first-1, curr->second-1);
      while (*prev < G) ++prev;
      if (*prev == G) {
	continues[curr-matches.begin()] = prev-matches.begin();
      }
    }
  }

  int best_idx = 0;
  int lcskpp_length = 0;

  for (auto event = matches.begin(), bp = matches.begin();
       event != matches.end(); ++event) {

    while (bp->first <= event->first - k) {
      int idx = bp - matches.begin(), j = bp->second;
      dp_col_max.update(j, make_pair(dp[idx], idx));
      ++bp;
    }

    int i = event->first;
    int j = event->second;
    int idx = event - matches.begin();

    dp[idx] = k;
    recon[idx] = -1;

    if (continues[idx] != -1) {
      if (dp[continues[idx]] + 1 > dp[idx]) {
	dp[idx] = dp[continues[idx]] + 1;
	recon[idx] = continues[idx];
      }
    }

    if (j >= k) {
      pair<int, int> prev_dp = dp_col_max.get(j - k);
      if (prev_dp.first > 0 && dp[idx] < prev_dp.first + k) {
	dp[idx] = prev_dp.first + k;
	recon[idx] = prev_dp.second;
      }
    }

    if (dp[idx] > lcskpp_length) {
      lcskpp_length = dp[idx];
      best_idx = idx;
    }
  }

  return lcskpp_length;
}

int lcskpp_pavetic_ubrzan_no_recon(const string& A, const string& B, int k) {
  vector<pair<int, int>> matches;
  calc_matches(A, B, k, &matches);
  sort(matches.begin(), matches.end());

  int n = 0;
  for (auto& p: matches) {
    n = max(n, max(p.first, p.second));
  }

  // Indexed by column, first:dp value, second:index in matches.
  FenwickMax<int> dp_col_max(n);
  vector<int> dp(matches.size());
  vector<int> continues(matches.size(), -1);

  if (k > 1) {
    auto prev = matches.begin();
    for (auto curr = matches.begin();
         curr != matches.end(); ++curr) {
      auto G = make_pair(curr->first-1, curr->second-1);
      while (*prev < G) ++prev;
      if (*prev == G) {
	continues[curr-matches.begin()] = prev-matches.begin();
      }
    }
  }

  int lcskpp_length = 0;

  for (auto event = matches.begin(), bp = matches.begin();
       event != matches.end(); ++event) {

    while (bp->first <= event->first - k) {
      int idx = bp - matches.begin(), j = bp->second;
      dp_col_max.update(j, dp[idx]);
      ++bp;
    }

    int i = event->first;
    int j = event->second;
    int idx = event - matches.begin();

    dp[idx] = k;

    if (continues[idx] != -1)
      dp[idx] = max(dp[idx], dp[continues[idx]] + 1);

    if (j >= k) {
      int val = dp_col_max.get(j - k);
      if (val > 0)
	dp[idx] = max(dp[idx], val + k);
    }

    lcskpp_length = max(lcskpp_length, dp[idx]);
  }

  return lcskpp_length;
}

<commit_msg> maknuo sortove<commit_after>// lcskpp algoritmi

#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <functional>
#include <map>
#include <queue>
#include "utils.h"
#include "pavetic.h"

using namespace std;

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define TRACE(x) cout << #x << " = " << x << endl
#define _ << " _ " <<

typedef long long llint;

const int inf = 1e9;

// obican dp: O(nmk)
int lcskpp_dp(const string& a, const string& b, int k) {
  vector<pair<int, int>> matches_pairs;
  calc_matches(a, b, k, &matches_pairs);

  vector<vector<int>> matches(a.size());
  for (auto& p: matches_pairs) matches[p.first].push_back(p.second);
  int n = a.size();
  int m = b.size();

  vector<vector<int>> f(n, vector<int>(m, 0));

  REP(i, n) {
    REP(j, m) {
      if (i) f[i][j] = max(f[i-1][j], f[i][j]);
      if (j) f[i][j] = max(f[i][j-1], f[i][j]);

      int q = 0;
      while (i-q >= 0 && j-q >= 0 && a[i-q] == b[j-q] && q < 2*k) {
        q++;
        if (q >= k) {
          f[i][j] = max(f[i][j], (i >= q && j >= q ? f[i-q][j-q] : 0) + q);
        }
      }
    }
  }

  return f[n-1][m-1];
}

int lcskpp_better_hunt(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int j = matches[bs_ptr].second;
      int lo = lower_bound(MinYPrefix.begin(), MinYPrefix.begin() + r + 2, j-k+1) - MinYPrefix.begin();
      match_dp[bs_ptr] = lo-1;
      bs_ptr++;
    }

    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      for (int s = 1; s <= k; ++s) {
        MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
      }
      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_better_hunt2(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int cur_lo = 0;
      int row = matches[bs_ptr].first;
      while (bs_ptr < n_matches && matches[bs_ptr].first == row) {
        int j = matches[bs_ptr].second;

        if (MinYPrefix[cur_lo] < j-k+1) {
          int lo = cur_lo, hi = r+1;
          while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (MinYPrefix[mid] < j - k + 1)
              lo = mid + 1;
            else
              hi = mid;
          }
          cur_lo = lo;
        }

        match_dp[bs_ptr] = cur_lo-1;
        bs_ptr++;
      }
    }

    int prev_l = -1;
    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      if (l > prev_l) {
        for (int s = 1; s <= k; ++s) {
          MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
        }
        prev_l = l;
      }

      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_better_kuo_cross(const string& a, const string& b, int k) {
  int n = a.size();
  int m = b.size();
  vector<pair<int, int>> matches;
  calc_matches(a, b, k, &matches);

  int n_matches = matches.size();
  vector<int> MinYPrefix(m + 1, inf);
  MinYPrefix[0] = -inf;

  int r = 0;

  vector<int> match_dp(matches.size());

  int ptr = 0;
  int bs_ptr = 0;
  int cont_ptr = 0;
  while (ptr < n_matches) {
    int i = matches[ptr].first;
    int i_ptr = ptr;

    while (cont_ptr < i_ptr && matches[cont_ptr].first < i-1) cont_ptr++;

    while (bs_ptr < n_matches && matches[bs_ptr].first < i+k) {
      int lo = 0;
      int row = matches[bs_ptr].first;
      while (bs_ptr < n_matches && matches[bs_ptr].first == row) {
        int j = matches[bs_ptr].second;
        while (MinYPrefix[lo] < j-k+1) lo++;
        match_dp[bs_ptr] = lo-1;
        bs_ptr++;
      }
    }

    while (ptr < n_matches && matches[ptr].first == i) {
      int j = matches[ptr].second;
      int l = match_dp[ptr];

      // probam popravit trenutni MinYPrefix.
      for (int s = 1; s <= k; ++s) {
        MinYPrefix[l + s] = min(MinYPrefix[l + s], j);
      }
      int my_dp = l+k;

      while (cont_ptr < i_ptr && matches[cont_ptr].second < j-1) cont_ptr++;
      if (cont_ptr < i_ptr && matches[cont_ptr].second == j-1) {
        int new_dp = match_dp[cont_ptr] + 1;
        if (new_dp > my_dp) {
          my_dp = new_dp;
          MinYPrefix[new_dp] = min(MinYPrefix[new_dp], j);
        }
      }

      r = max(r, my_dp);
      match_dp[ptr] = my_dp;

      ptr++;
    }
  }

  return r;
}

int lcskpp_pavetic(const string& A, const string& B, int k) {
  int ret;
  Pavetic::lcskpp(A, B, k, &ret, NULL);
  return ret;
}

int lcskpp_pavetic_ubrzan(const string& A, const string& B, int k) {
  vector<pair<int, int>> matches;
  calc_matches(A, B, k, &matches);

  int n = 0;
  for (auto& p: matches) {
    n = max(n, max(p.first, p.second));
  }

  // Indexed by column, first:dp value, second:index in matches.
  FenwickMax<pair<int, int> > dp_col_max(n);
  vector<int> dp(matches.size());
  vector<int> recon(matches.size());
  vector<int> continues(matches.size(), -1);

  if (k > 1) {
    auto prev = matches.begin();
    for (auto curr = matches.begin();
         curr != matches.end(); ++curr) {
      auto G = make_pair(curr->first-1, curr->second-1);
      while (*prev < G) ++prev;
      if (*prev == G) {
	continues[curr-matches.begin()] = prev-matches.begin();
      }
    }
  }

  int best_idx = 0;
  int lcskpp_length = 0;

  for (auto event = matches.begin(), bp = matches.begin();
       event != matches.end(); ++event) {

    while (bp->first <= event->first - k) {
      int idx = bp - matches.begin(), j = bp->second;
      dp_col_max.update(j, make_pair(dp[idx], idx));
      ++bp;
    }

    int i = event->first;
    int j = event->second;
    int idx = event - matches.begin();

    dp[idx] = k;
    recon[idx] = -1;

    if (continues[idx] != -1) {
      if (dp[continues[idx]] + 1 > dp[idx]) {
	dp[idx] = dp[continues[idx]] + 1;
	recon[idx] = continues[idx];
      }
    }

    if (j >= k) {
      pair<int, int> prev_dp = dp_col_max.get(j - k);
      if (prev_dp.first > 0 && dp[idx] < prev_dp.first + k) {
	dp[idx] = prev_dp.first + k;
	recon[idx] = prev_dp.second;
      }
    }

    if (dp[idx] > lcskpp_length) {
      lcskpp_length = dp[idx];
      best_idx = idx;
    }
  }

  return lcskpp_length;
}

int lcskpp_pavetic_ubrzan_no_recon(const string& A, const string& B, int k) {
  vector<pair<int, int>> matches;
  calc_matches(A, B, k, &matches);
  sort(matches.begin(), matches.end());

  int n = 0;
  for (auto& p: matches) {
    n = max(n, max(p.first, p.second));
  }

  // Indexed by column, first:dp value, second:index in matches.
  FenwickMax<int> dp_col_max(n);
  vector<int> dp(matches.size());
  vector<int> continues(matches.size(), -1);

  if (k > 1) {
    auto prev = matches.begin();
    for (auto curr = matches.begin();
         curr != matches.end(); ++curr) {
      auto G = make_pair(curr->first-1, curr->second-1);
      while (*prev < G) ++prev;
      if (*prev == G) {
	continues[curr-matches.begin()] = prev-matches.begin();
      }
    }
  }

  int lcskpp_length = 0;

  for (auto event = matches.begin(), bp = matches.begin();
       event != matches.end(); ++event) {

    while (bp->first <= event->first - k) {
      int idx = bp - matches.begin(), j = bp->second;
      dp_col_max.update(j, dp[idx]);
      ++bp;
    }

    int i = event->first;
    int j = event->second;
    int idx = event - matches.begin();

    dp[idx] = k;

    if (continues[idx] != -1)
      dp[idx] = max(dp[idx], dp[continues[idx]] + 1);

    if (j >= k) {
      int val = dp_col_max.get(j - k);
      if (val > 0)
	dp[idx] = max(dp[idx], val + k);
    }

    lcskpp_length = max(lcskpp_length, dp[idx]);
  }

  return lcskpp_length;
}

<|endoftext|>


<commit_before>#include "HAL/HAL.hpp"

#include "HAL/Port.h"
#include "HAL/Errors.hpp"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include "ChipObject.h"
#include "FRC_NetworkCommunication/FRCComm.h"
#include "FRC_NetworkCommunication/UsageReporting.h"
#include "FRC_NetworkCommunication/LoadOut.h"
#include "FRC_NetworkCommunication/CANSessionMux.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;

static tGlobal *global = nullptr;
static tSysWatchdog *watchdog = nullptr;

void* getPort(uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = 1;
	return port;
}

/**
 * @deprecated Uses module numbers
 */
void* getPortWithModule(uint8_t module, uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = module;
	return port;
}

void freePort(void* port_pointer)
{
	Port* port = (Port*) port_pointer;
	delete port;
}

const char* getHALErrorMessage(int32_t code)
{
	switch(code) {
		case 0:
			return "";
		case CTR_RxTimeout:
			return CTR_RxTimeout_MESSAGE;
		case CTR_TxTimeout:
			return CTR_TxTimeout_MESSAGE;
		case CTR_InvalidParamValue:
			return CTR_InvalidParamValue_MESSAGE;
		case CTR_UnexpectedArbId:
			return CTR_UnexpectedArbId_MESSAGE;
                case CTR_TxFailed:
			return CTR_TxFailed_MESSAGE;
                case CTR_SigNotUpdated:
			return CTR_SigNotUpdated_MESSAGE;
		case NiFpga_Status_FifoTimeout:
			return NiFpga_Status_FifoTimeout_MESSAGE;
		case NiFpga_Status_TransferAborted:
			return NiFpga_Status_TransferAborted_MESSAGE;
		case NiFpga_Status_MemoryFull:
			return NiFpga_Status_MemoryFull_MESSAGE;
		case NiFpga_Status_SoftwareFault:
			return NiFpga_Status_SoftwareFault_MESSAGE;
		case NiFpga_Status_InvalidParameter:
			return NiFpga_Status_InvalidParameter_MESSAGE;
		case NiFpga_Status_ResourceNotFound:
			return NiFpga_Status_ResourceNotFound_MESSAGE;
		case NiFpga_Status_ResourceNotInitialized:
			return NiFpga_Status_ResourceNotInitialized_MESSAGE;
		case NiFpga_Status_HardwareFault:
			return NiFpga_Status_HardwareFault_MESSAGE;
		case NiFpga_Status_IrqTimeout:
			return NiFpga_Status_IrqTimeout_MESSAGE;
		case SAMPLE_RATE_TOO_HIGH:
			return SAMPLE_RATE_TOO_HIGH_MESSAGE;
		case VOLTAGE_OUT_OF_RANGE:
			return VOLTAGE_OUT_OF_RANGE_MESSAGE;
		case LOOP_TIMING_ERROR:
			return LOOP_TIMING_ERROR_MESSAGE;
		case SPI_WRITE_NO_MOSI:
			return SPI_WRITE_NO_MOSI_MESSAGE;
		case SPI_READ_NO_MISO:
			return SPI_READ_NO_MISO_MESSAGE;
		case SPI_READ_NO_DATA:
			return SPI_READ_NO_DATA_MESSAGE;
		case INCOMPATIBLE_STATE:
			return INCOMPATIBLE_STATE_MESSAGE;
		case NO_AVAILABLE_RESOURCES:
			return NO_AVAILABLE_RESOURCES_MESSAGE;
		case NULL_PARAMETER:
			return NULL_PARAMETER_MESSAGE;
		case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
			return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
		case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
			return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
		case PARAMETER_OUT_OF_RANGE:
			return PARAMETER_OUT_OF_RANGE_MESSAGE;
		case ERR_CANSessionMux_InvalidBuffer:
			return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
		case ERR_CANSessionMux_MessageNotFound:
			return ERR_CANSessionMux_MessageNotFound_MESSAGE;
		case WARN_CANSessionMux_NoToken:
			return WARN_CANSessionMux_NoToken_MESSAGE;
		case ERR_CANSessionMux_NotAllowed:
			return ERR_CANSessionMux_NotAllowed_MESSAGE;
		case ERR_CANSessionMux_NotInitialized:
			return ERR_CANSessionMux_NotInitialized_MESSAGE;
		case VI_ERROR_SYSTEM_ERROR:
			return VI_ERROR_SYSTEM_ERROR_MESSAGE;
		case VI_ERROR_INV_OBJECT:
			return VI_ERROR_INV_OBJECT_MESSAGE;
		case VI_ERROR_RSRC_LOCKED:
			return VI_ERROR_RSRC_LOCKED_MESSAGE;
		case VI_ERROR_RSRC_NFOUND:
			return VI_ERROR_RSRC_NFOUND_MESSAGE;
		case VI_ERROR_INV_RSRC_NAME:
			return VI_ERROR_INV_RSRC_NAME_MESSAGE;
		case VI_ERROR_QUEUE_OVERFLOW:
			return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
		case VI_ERROR_IO:
			return VI_ERROR_IO_MESSAGE;
		case VI_ERROR_ASRL_PARITY:
			return VI_ERROR_ASRL_PARITY_MESSAGE;
		case VI_ERROR_ASRL_FRAMING:
			return VI_ERROR_ASRL_FRAMING_MESSAGE;
		case VI_ERROR_ASRL_OVERRUN:
			return VI_ERROR_ASRL_OVERRUN_MESSAGE;
		case VI_ERROR_RSRC_BUSY:
			return VI_ERROR_RSRC_BUSY_MESSAGE;
		case VI_ERROR_INV_PARAMETER:
			return VI_ERROR_INV_PARAMETER_MESSAGE;
		default:
			return "Unknown error status";
	}
}

/**
 * Return the FPGA Version number.
 * For now, expect this to be competition year.
 * @return FPGA Version number.
 */
uint16_t getFPGAVersion(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readVersion(status);
}

/**
 * Return the FPGA Revision number.
 * The format of the revision is 3 numbers.
 * The 12 most significant bits are the Major Revision.
 * the next 8 bits are the Minor Revision.
 * The 12 least significant bits are the Build Number.
 * @return FPGA Revision number.
 */
uint32_t getFPGARevision(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readRevision(status);
}

/**
 * Read the microsecond-resolution timer on the FPGA.
 *
 * @return The current time in microseconds according to the FPGA (since FPGA reset).
 */
uint32_t getFPGATime(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readLocalTime(status);
}

/**
 * Get the state of the "USER" button on the RoboRIO
 * @return true if the button is currently pressed down
 */
bool getFPGAButton(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return global->readUserButton(status);
}

int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
	return setErrorData(errors, errorsLength, wait_ms);
}

bool HALGetSystemActive(int32_t *status)
{
	if (!watchdog) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return watchdog->readStatus_SystemActive(status);
}

bool HALGetBrownedOut(int32_t *status)
{
	if (!watchdog) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return !(watchdog->readStatus_PowerAlive(status));
}

static void HALCleanupAtExit() {
	global = nullptr;
	watchdog = nullptr;
}

/**
 * Call this to start up HAL. This is required for robot programs.
 */
int HALInitialize(int mode)
{
    setlinebuf(stdin);
    setlinebuf(stdout);

    prctl(PR_SET_PDEATHSIG, SIGTERM);

	FRC_NetworkCommunication_Reserve(nullptr);
	// image 4; Fixes errors caused by multiple processes. Talk to NI about this
	nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
			nLoadOut::kTargetClass_RoboRIO;

	int32_t status = 0;
	global = tGlobal::create(&status);
	watchdog = tSysWatchdog::create(&status);

	std::atexit(HALCleanupAtExit);

	// Kill any previous robot programs
	std::fstream fs;
	// By making this both in/out, it won't give us an error if it doesnt exist
	fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
	if (fs.bad())
		return 0;

	pid_t pid = 0;
	if (!fs.eof() && !fs.fail())
	{
		fs >> pid;
		//see if the pid is around, but we don't want to mess with init id=1, or ourselves
		if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
		{
			std::cout << "Killing previously running FRC program..."
					<< std::endl;
			kill(pid, SIGTERM); // try to kill it
			delayMillis(100);
			if (kill(pid, 0) == 0)
			{
				// still not successfull
				if (mode == 0)
				{
					std::cout << "FRC pid " << pid
							<< " did not die within 110ms. Aborting"
							<< std::endl;
					return 0; // just fail
				}
				else if (mode == 1) // kill -9 it
					kill(pid, SIGKILL);
				else
				{
					std::cout << "WARNING: FRC pid " << pid
							<< " did not die within 110ms." << std::endl;
				}
			}

		}
	}
	fs.close();
	// we will re-open it write only to truncate the file
	fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
	fs.seekp(0);
	pid = getpid();
	fs << pid << std::endl;
	fs.close();
	return 1;
}

uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
		const char *feature)
{
	if(feature == NULL)
	{
		feature = "";
	}

	return FRC_NetworkCommunication_nUsageReporting_report(resource, instanceNumber, context, feature);
}

// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}

void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}
<commit_msg>Artf4774 Fixes HAL getHALErrorMessage missing error<commit_after>#include "HAL/HAL.hpp"

#include "HAL/Port.h"
#include "HAL/Errors.hpp"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include "ChipObject.h"
#include "FRC_NetworkCommunication/FRCComm.h"
#include "FRC_NetworkCommunication/UsageReporting.h"
#include "FRC_NetworkCommunication/LoadOut.h"
#include "FRC_NetworkCommunication/CANSessionMux.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <sys/prctl.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;

static tGlobal *global = nullptr;
static tSysWatchdog *watchdog = nullptr;

void* getPort(uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = 1;
	return port;
}

/**
 * @deprecated Uses module numbers
 */
void* getPortWithModule(uint8_t module, uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = module;
	return port;
}

void freePort(void* port_pointer)
{
	Port* port = (Port*) port_pointer;
	delete port;
}

const char* getHALErrorMessage(int32_t code)
{
	switch(code) {
		case 0:
			return "";
		case CTR_RxTimeout:
			return CTR_RxTimeout_MESSAGE;
		case CTR_TxTimeout:
			return CTR_TxTimeout_MESSAGE;
		case CTR_InvalidParamValue:
			return CTR_InvalidParamValue_MESSAGE;
		case CTR_UnexpectedArbId:
			return CTR_UnexpectedArbId_MESSAGE;
                case CTR_TxFailed:
			return CTR_TxFailed_MESSAGE;
                case CTR_SigNotUpdated:
			return CTR_SigNotUpdated_MESSAGE;
		case NiFpga_Status_FifoTimeout:
			return NiFpga_Status_FifoTimeout_MESSAGE;
		case NiFpga_Status_TransferAborted:
			return NiFpga_Status_TransferAborted_MESSAGE;
		case NiFpga_Status_MemoryFull:
			return NiFpga_Status_MemoryFull_MESSAGE;
		case NiFpga_Status_SoftwareFault:
			return NiFpga_Status_SoftwareFault_MESSAGE;
		case NiFpga_Status_InvalidParameter:
			return NiFpga_Status_InvalidParameter_MESSAGE;
		case NiFpga_Status_ResourceNotFound:
			return NiFpga_Status_ResourceNotFound_MESSAGE;
		case NiFpga_Status_ResourceNotInitialized:
			return NiFpga_Status_ResourceNotInitialized_MESSAGE;
		case NiFpga_Status_HardwareFault:
			return NiFpga_Status_HardwareFault_MESSAGE;
		case NiFpga_Status_IrqTimeout:
			return NiFpga_Status_IrqTimeout_MESSAGE;
		case SAMPLE_RATE_TOO_HIGH:
			return SAMPLE_RATE_TOO_HIGH_MESSAGE;
		case VOLTAGE_OUT_OF_RANGE:
			return VOLTAGE_OUT_OF_RANGE_MESSAGE;
		case LOOP_TIMING_ERROR:
			return LOOP_TIMING_ERROR_MESSAGE;
		case SPI_WRITE_NO_MOSI:
			return SPI_WRITE_NO_MOSI_MESSAGE;
		case SPI_READ_NO_MISO:
			return SPI_READ_NO_MISO_MESSAGE;
		case SPI_READ_NO_DATA:
			return SPI_READ_NO_DATA_MESSAGE;
		case INCOMPATIBLE_STATE:
			return INCOMPATIBLE_STATE_MESSAGE;
		case NO_AVAILABLE_RESOURCES:
			return NO_AVAILABLE_RESOURCES_MESSAGE;
		case RESOURCE_IS_ALLOCATED:
			return RESOURCE_IS_ALLOCATED_MESSAGE;
		case NULL_PARAMETER:
			return NULL_PARAMETER_MESSAGE;
		case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
			return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
		case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
			return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
		case PARAMETER_OUT_OF_RANGE:
			return PARAMETER_OUT_OF_RANGE_MESSAGE;
		case ERR_CANSessionMux_InvalidBuffer:
			return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
		case ERR_CANSessionMux_MessageNotFound:
			return ERR_CANSessionMux_MessageNotFound_MESSAGE;
		case WARN_CANSessionMux_NoToken:
			return WARN_CANSessionMux_NoToken_MESSAGE;
		case ERR_CANSessionMux_NotAllowed:
			return ERR_CANSessionMux_NotAllowed_MESSAGE;
		case ERR_CANSessionMux_NotInitialized:
			return ERR_CANSessionMux_NotInitialized_MESSAGE;
		case VI_ERROR_SYSTEM_ERROR:
			return VI_ERROR_SYSTEM_ERROR_MESSAGE;
		case VI_ERROR_INV_OBJECT:
			return VI_ERROR_INV_OBJECT_MESSAGE;
		case VI_ERROR_RSRC_LOCKED:
			return VI_ERROR_RSRC_LOCKED_MESSAGE;
		case VI_ERROR_RSRC_NFOUND:
			return VI_ERROR_RSRC_NFOUND_MESSAGE;
		case VI_ERROR_INV_RSRC_NAME:
			return VI_ERROR_INV_RSRC_NAME_MESSAGE;
		case VI_ERROR_QUEUE_OVERFLOW:
			return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
		case VI_ERROR_IO:
			return VI_ERROR_IO_MESSAGE;
		case VI_ERROR_ASRL_PARITY:
			return VI_ERROR_ASRL_PARITY_MESSAGE;
		case VI_ERROR_ASRL_FRAMING:
			return VI_ERROR_ASRL_FRAMING_MESSAGE;
		case VI_ERROR_ASRL_OVERRUN:
			return VI_ERROR_ASRL_OVERRUN_MESSAGE;
		case VI_ERROR_RSRC_BUSY:
			return VI_ERROR_RSRC_BUSY_MESSAGE;
		case VI_ERROR_INV_PARAMETER:
			return VI_ERROR_INV_PARAMETER_MESSAGE;
		default:
			return "Unknown error status";
	}
}

/**
 * Return the FPGA Version number.
 * For now, expect this to be competition year.
 * @return FPGA Version number.
 */
uint16_t getFPGAVersion(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readVersion(status);
}

/**
 * Return the FPGA Revision number.
 * The format of the revision is 3 numbers.
 * The 12 most significant bits are the Major Revision.
 * the next 8 bits are the Minor Revision.
 * The 12 least significant bits are the Build Number.
 * @return FPGA Revision number.
 */
uint32_t getFPGARevision(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readRevision(status);
}

/**
 * Read the microsecond-resolution timer on the FPGA.
 *
 * @return The current time in microseconds according to the FPGA (since FPGA reset).
 */
uint32_t getFPGATime(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return 0;
	}
	return global->readLocalTime(status);
}

/**
 * Get the state of the "USER" button on the RoboRIO
 * @return true if the button is currently pressed down
 */
bool getFPGAButton(int32_t *status)
{
	if (!global) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return global->readUserButton(status);
}

int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
	return setErrorData(errors, errorsLength, wait_ms);
}

bool HALGetSystemActive(int32_t *status)
{
	if (!watchdog) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return watchdog->readStatus_SystemActive(status);
}

bool HALGetBrownedOut(int32_t *status)
{
	if (!watchdog) {
		*status = NiFpga_Status_ResourceNotInitialized;
		return false;
	}
	return !(watchdog->readStatus_PowerAlive(status));
}

static void HALCleanupAtExit() {
	global = nullptr;
	watchdog = nullptr;
}

/**
 * Call this to start up HAL. This is required for robot programs.
 */
int HALInitialize(int mode)
{
    setlinebuf(stdin);
    setlinebuf(stdout);

    prctl(PR_SET_PDEATHSIG, SIGTERM);

	FRC_NetworkCommunication_Reserve(nullptr);
	// image 4; Fixes errors caused by multiple processes. Talk to NI about this
	nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
			nLoadOut::kTargetClass_RoboRIO;

	int32_t status = 0;
	global = tGlobal::create(&status);
	watchdog = tSysWatchdog::create(&status);

	std::atexit(HALCleanupAtExit);

	// Kill any previous robot programs
	std::fstream fs;
	// By making this both in/out, it won't give us an error if it doesnt exist
	fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
	if (fs.bad())
		return 0;

	pid_t pid = 0;
	if (!fs.eof() && !fs.fail())
	{
		fs >> pid;
		//see if the pid is around, but we don't want to mess with init id=1, or ourselves
		if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
		{
			std::cout << "Killing previously running FRC program..."
					<< std::endl;
			kill(pid, SIGTERM); // try to kill it
			delayMillis(100);
			if (kill(pid, 0) == 0)
			{
				// still not successfull
				if (mode == 0)
				{
					std::cout << "FRC pid " << pid
							<< " did not die within 110ms. Aborting"
							<< std::endl;
					return 0; // just fail
				}
				else if (mode == 1) // kill -9 it
					kill(pid, SIGKILL);
				else
				{
					std::cout << "WARNING: FRC pid " << pid
							<< " did not die within 110ms." << std::endl;
				}
			}

		}
	}
	fs.close();
	// we will re-open it write only to truncate the file
	fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
	fs.seekp(0);
	pid = getpid();
	fs << pid << std::endl;
	fs.close();
	return 1;
}

uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
		const char *feature)
{
	if(feature == NULL)
	{
		feature = "";
	}

	return FRC_NetworkCommunication_nUsageReporting_report(resource, instanceNumber, context, feature);
}

// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}

void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include "paramedir.h"
#include "cfg.h"
#include "trace.h"
#include "kwindow.h"
#include "cube.h"

using namespace std;

bool multipleFiles = false;
Trace *trace;
UINT32 outputPrecision = 2;

int main( int argc, char *argv[] )
{
  // Cube< TSemanticValue > cube( 10, 10, 10 );

  readParaverConfigFile();

  if ( argc == 1 )
    printHelp();
  else
  {
    INT32 currentArg = 1;
    // Read options ( Deberia ser un while si hay mas opciones. De momento solo hay esta)
    if ( argv[ currentArg ][ 0 ] == '-' )
    {
      if ( argv[ currentArg ][ 1 ] == 'm' )
      {
        multipleFiles = true;
      }
      currentArg++;
    }

    // Read the trace
    string strTrace( argv[ currentArg ] );
    try
    {
      trace = new Trace( strTrace );
    }
    catch ( ParaverKernelException& ex )
    {
      ex.printMessage();
      cout << "Cannot load " << strTrace << endl;
      exit( 0 );
    }
    currentArg++;

    //Read the cfgs list and create the output files for each one
    while ( currentArg < argc )
    {
      string strCfg( argv[ currentArg ] );
      vector<KWindow *> windows;
      TRecordTime beginTime;
      TRecordTime endTime;
      string strOutputFile;

      if ( CFGLoader::isCFGFile( strCfg ) )
      {
        string strOut;
        if ( argc > currentArg + 1 )
        {
          strOut = argv[ currentArg + 1 ];
          if ( !CFGLoader::isCFGFile( strOut ) )
          {
            strOutputFile = strOut;
            currentArg++;
          }
          else
          {
            strOutputFile = strCfg.substr( 0, strCfg.length() - 4 );
          }

        }
        else
        {
          strOutputFile = strCfg.substr( 0, strCfg.length() - 4 );
        }
        currentArg++;
      }

      if ( CFGLoader::loadCFG( strCfg, trace, windows, beginTime, endTime ) )
      {
        ofstream outputFile;
        KWindow *tmpWindow = windows[ windows.size() - 1 ];

        tmpWindow->init( beginTime, NOCREATE );

        if ( endTime > trace->getEndTime() )
          endTime = trace->getEndTime();

        if ( !multipleFiles )
          outputFile.open( strOutputFile.c_str() );

        for ( TObjectOrder i = 0; i < tmpWindow->getWindowLevelObjects(); i++ )
        {
          if ( multipleFiles )
          {
            ostringstream tmpName;
            tmpName << strOutputFile  << "_" << setw( 5 ) << setfill( '0' ) << i + 1;
            outputFile.open( tmpName.str().c_str() );
          }

          outputFile << fixed;
        outputFile << showpoint;

        while ( tmpWindow->getEndTime( i ) < endTime )
          {
            outputFile << setprecision( outputPrecision );
            if ( !multipleFiles )
              outputFile << i + 1 << "\t";
            outputFile << tmpWindow->traceUnitsToWindowUnits(
              tmpWindow->getBeginTime( i ) ) << "\t";
            outputFile << tmpWindow->traceUnitsToWindowUnits(
              tmpWindow->getEndTime( i ) - tmpWindow->getBeginTime( i ) ) << "\t";
            outputFile << tmpWindow->getValue( i ) << endl;
            tmpWindow->calcNext( i );
          }
          outputFile << setprecision( outputPrecision );
          if ( !multipleFiles )
            outputFile << i + 1 << "\t";
          outputFile << tmpWindow->traceUnitsToWindowUnits(
            tmpWindow->getBeginTime( i ) ) << "\t";
          outputFile << tmpWindow->traceUnitsToWindowUnits(
            tmpWindow->getEndTime( i ) - tmpWindow->getBeginTime( i ) ) << "\t";
          outputFile << tmpWindow->getValue( i ) << endl;

          if ( multipleFiles )
            outputFile.close();
        }

        if ( multipleFiles )
          cout << strOutputFile << "_* files wrote." << endl;
        else
          cout << strOutputFile << " file wrote." << endl;
      }
      else
        cout << "Cannot load '" << strCfg << "' file." << endl;

      for ( UINT32 i = 0; i < windows.size(); i++ )
      {
        if ( windows[ i ] != NULL )
          delete windows[ i ];
      }
      windows.clear();
    }

    delete trace;
  }

  return 1;
}

void printHelp()
{
  cout << "USAGE" << endl;
  cout << "  paramedir [OPTION] trc cfg {out | cfg}*" << endl;
  cout << endl;
  cout << "  Options:" << endl;
  cout << "  -m: Prints on multiple files." << endl;
  cout << endl;
  cout << "  Parameters:" << endl;
  cout << "  trc: Paraver trace filename (ASCII: *.prv)." << endl;
  cout << "  cfg: Paraver configuration filename (*.cfg)." << endl;
  cout << "  out: Filename for output (default name is cfg filename without .cfg)." << endl;
}

void readParaverConfigFile()
{
  ifstream file;
  string strLine;
  string strTag;
  string strFile;

  strFile.append( getenv( "HOME" ) );
  strFile.append( "/.paraver/paraver" );

  file.open( strFile.c_str() );

  if ( !file )
    return;

  while ( !file.eof() )
  {
    getline( file, strLine );
    if ( strLine.length() == 0 )
      continue;
    else if ( strLine[ 0 ] == '#' || strLine[ 0 ] == '<' )
      continue;

    istringstream auxStream( strLine );
    getline( auxStream, strTag, ' ' );

    if ( strTag.compare( "WhatWhere.num_decimals:" ) == 0 )
    {
      string strNumDecimals;

      getline( auxStream, strNumDecimals );
      istringstream streamNumDecimals( strNumDecimals );

      streamNumDecimals >> outputPrecision;
    }
  }
  file.close();
}
<commit_msg>*** empty log message ***<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include "paramedir.h"
#include "cfg.h"
#include "trace.h"
#include "kwindow.h"
#include "cube.h"

using namespace std;

bool multipleFiles = false;
Trace *trace;
UINT32 outputPrecision = 2;

int main( int argc, char *argv[] )
{
  // Cube< TSemanticValue > cube( 10, 10, 10 );

  readParaverConfigFile();

  if ( argc == 1 )
    printHelp();
  else
  {
    INT32 currentArg = 1;
    // Read options ( Deberia ser un while si hay mas opciones. De momento solo hay esta)
    if ( argv[ currentArg ][ 0 ] == '-' )
    {
      if ( argv[ currentArg ][ 1 ] == 'm' )
      {
        multipleFiles = true;
      }
      currentArg++;
    }

    // Read the trace
    string strTrace( argv[ currentArg ] );
    try
    {
      trace = new Trace( strTrace );
    }
    catch ( ParaverKernelException& ex )
    {
      ex.printMessage();
      cout << "Cannot load " << strTrace << endl;
      exit( 0 );
    }
    currentArg++;

    //Read the cfgs list and create the output files for each one
    while ( currentArg < argc )
    {
      string strCfg( argv[ currentArg ] );
      vector<KWindow *> windows;
      TRecordTime beginTime;
      TRecordTime endTime;
      string strOutputFile;

      if ( CFGLoader::isCFGFile( strCfg ) )
      {
        string strOut;
        if ( argc > currentArg + 1 )
        {
          strOut = argv[ currentArg + 1 ];
          if ( !CFGLoader::isCFGFile( strOut ) )
          {
            strOutputFile = strOut;
            currentArg++;
          }
          else
          {
            strOutputFile = strCfg.substr( 0, strCfg.length() - 4 );
          }

        }
        else
        {
          strOutputFile = strCfg.substr( 0, strCfg.length() - 4 );
        }
        currentArg++;
      }

      if ( CFGLoader::loadCFG( strCfg, trace, windows, beginTime, endTime ) )
      {
        ofstream outputFile;
        KWindow *tmpWindow = windows[ windows.size() - 1 ];

        tmpWindow->init( beginTime, NOCREATE );

        if ( endTime > trace->getEndTime() )
          endTime = trace->getEndTime();

        if ( !multipleFiles )
          outputFile.open( strOutputFile.c_str() );

        for ( TObjectOrder i = 0; i < tmpWindow->getWindowLevelObjects(); i++ )
        {
          if ( multipleFiles )
          {
            ostringstream tmpName;
            tmpName << strOutputFile  << "_" << setw( 5 ) << setfill( '0' ) << i + 1;
            outputFile.open( tmpName.str().c_str() );
          }

          outputFile << fixed;
          outputFile << showpoint;

          while ( tmpWindow->getEndTime( i ) < endTime )
          {
            outputFile << setprecision( outputPrecision );
            if ( !multipleFiles )
              outputFile << i + 1 << "\t";
            outputFile << tmpWindow->traceUnitsToWindowUnits(
              tmpWindow->getBeginTime( i ) ) << "\t";
            outputFile << tmpWindow->traceUnitsToWindowUnits(
              tmpWindow->getEndTime( i ) - tmpWindow->getBeginTime( i ) ) << "\t";
            outputFile << tmpWindow->getValue( i ) << endl;
            tmpWindow->calcNext( i );
          }
          outputFile << setprecision( outputPrecision );
          if ( !multipleFiles )
            outputFile << i + 1 << "\t";
          outputFile << tmpWindow->traceUnitsToWindowUnits(
            tmpWindow->getBeginTime( i ) ) << "\t";
          outputFile << tmpWindow->traceUnitsToWindowUnits(
            tmpWindow->getEndTime( i ) - tmpWindow->getBeginTime( i ) ) << "\t";
          outputFile << tmpWindow->getValue( i ) << endl;

          if ( multipleFiles )
            outputFile.close();
        }

        if ( multipleFiles )
          cout << strOutputFile << "_* files wrote." << endl;
        else
        {
          outputFile.close();
          cout << strOutputFile << " file wrote." << endl;
        }
      }
      else
        cout << "Cannot load '" << strCfg << "' file." << endl;

      for ( UINT32 i = 0; i < windows.size(); i++ )
      {
        if ( windows[ i ] != NULL )
          delete windows[ i ];
      }
      windows.clear();
    }

    delete trace;
  }

  return 1;
}

void printHelp()
{
  cout << "USAGE" << endl;
  cout << "  paramedir [OPTION] trc cfg {out | cfg}*" << endl;
  cout << endl;
  cout << "  Options:" << endl;
  cout << "  -m: Prints on multiple files." << endl;
  cout << endl;
  cout << "  Parameters:" << endl;
  cout << "  trc: Paraver trace filename (ASCII: *.prv)." << endl;
  cout << "  cfg: Paraver configuration filename (*.cfg)." << endl;
  cout << "  out: Filename for output (default name is cfg filename without .cfg)." << endl;
}

void readParaverConfigFile()
{
  ifstream file;
  string strLine;
  string strTag;
  string strFile;

  strFile.append( getenv( "HOME" ) );
  strFile.append( "/.paraver/paraver" );

  file.open( strFile.c_str() );

  if ( !file )
    return;

  while ( !file.eof() )
  {
    getline( file, strLine );
    if ( strLine.length() == 0 )
      continue;
    else if ( strLine[ 0 ] == '#' || strLine[ 0 ] == '<' )
      continue;

    istringstream auxStream( strLine );
    getline( auxStream, strTag, ' ' );

    if ( strTag.compare( "WhatWhere.num_decimals:" ) == 0 )
    {
      string strNumDecimals;

      getline( auxStream, strNumDecimals );
      istringstream streamNumDecimals( strNumDecimals );

      streamNumDecimals >> outputPrecision;
    }
  }
  file.close();
}
<|endoftext|>


<commit_before>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBTUP_C
#include "Dbtup.hpp"
#include <RefConvert.hpp>
#include <ndb_limits.h>
#include <pc.hpp>
#include <signaldata/TransIdAI.hpp>

#define ljam() { jamLine(2000 + __LINE__); }
#define ljamEntry() { jamEntryLine(2000 + __LINE__); }

void Dbtup::execSEND_PACKED(Signal* signal)
{
  Uint16 hostId;
  Uint32 i;
  Uint32 TpackedListIndex = cpackedListIndex;
  ljamEntry();
  for (i = 0; i < TpackedListIndex; i++) {
    ljam();
    hostId = cpackedList[i];
    ndbrequire((hostId - 1) < (MAX_NODES - 1)); // Also check not zero
    Uint32 TpacketTA = hostBuffer[hostId].noOfPacketsTA;
    if (TpacketTA != 0) {
      ljam();
      BlockReference TBref = numberToRef(API_PACKED, hostId);
      Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
      MEMCOPY_NO_WORDS(&signal->theData[0],
                       &hostBuffer[hostId].packetBufferTA[0],
                       TpacketLen);
      sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
      hostBuffer[hostId].noOfPacketsTA = 0;
      hostBuffer[hostId].packetLenTA = 0;
    }//if
    hostBuffer[hostId].inPackedList = false;
  }//for
  cpackedListIndex = 0;
}//Dbtup::execSEND_PACKED()

void Dbtup::bufferTRANSID_AI(Signal* signal, BlockReference aRef,
                             Uint32 Tlen)
{
  if(Tlen == 3)
    return;

  Uint32 hostId = refToNode(aRef);
  Uint32 Theader = ((refToBlock(aRef) << 16)+(Tlen-3));

  ndbrequire(hostId < MAX_NODES);
  Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
  Uint32 TnoOfPackets = hostBuffer[hostId].noOfPacketsTA;
  Uint32 sig0 = signal->theData[0];
  Uint32 sig1 = signal->theData[1];
  Uint32 sig2 = signal->theData[2];

  BlockReference TBref = numberToRef(API_PACKED, hostId);

  if ((Tlen + TpacketLen + 1) <= 25) {
// ----------------------------------------------------------------
// There is still space in the buffer. We will copy it into the
// buffer.
// ----------------------------------------------------------------
    ljam();
    updatePackedList(signal, hostId);
  } else if (false && TnoOfPackets == 1) {
// ----------------------------------------------------------------
// The buffer is full and there was only one packet buffered. We
// will send this as a normal signal.
// ----------------------------------------------------------------
    Uint32 TnewRef = numberToRef((hostBuffer[hostId].packetBufferTA[0] >> 16),
                                 hostId);
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[1],
                     TpacketLen - 1);
    sendSignal(TnewRef, GSN_TRANSID_AI, signal, (TpacketLen - 1), JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  } else {
// ----------------------------------------------------------------
// The buffer is full but at least two packets. Send those in
// packed form.
// ----------------------------------------------------------------
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[0],
                     TpacketLen);
    sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  }//if
// ----------------------------------------------------------------
// Copy the signal into the buffer
// ----------------------------------------------------------------
  hostBuffer[hostId].packetBufferTA[TpacketLen + 0] = Theader;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 1] = sig0;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 2] = sig1;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 3] = sig2;
  hostBuffer[hostId].noOfPacketsTA = TnoOfPackets + 1;
  hostBuffer[hostId].packetLenTA = Tlen + TpacketLen + 1;
  MEMCOPY_NO_WORDS(&hostBuffer[hostId].packetBufferTA[TpacketLen + 4],
                   &signal->theData[25],
                   Tlen - 3);
}//Dbtup::bufferTRANSID_AI()

void Dbtup::updatePackedList(Signal* signal, Uint16 hostId)
{
  if (hostBuffer[hostId].inPackedList == false) {
    Uint32 TpackedListIndex = cpackedListIndex;
    ljam();
    hostBuffer[hostId].inPackedList = true;
    cpackedList[TpackedListIndex] = hostId;
    cpackedListIndex = TpackedListIndex + 1;
  }//if
}//Dbtup::updatePackedList()

/* ---------------------------------------------------------------- */
/* ----------------------- SEND READ ATTRINFO --------------------- */
/* ---------------------------------------------------------------- */
void Dbtup::sendReadAttrinfo(Signal* signal,
                             Uint32 ToutBufIndex,
                             const Operationrec * const regOperPtr)
{
  const BlockReference recBlockref = regOperPtr->recBlockref;
  const Uint32 block = refToBlock(recBlockref);
  const Uint32 nodeId = refToNode(recBlockref);

  bool connectedToNode = getNodeInfo(nodeId).m_connected;
  const Uint32 type = getNodeInfo(nodeId).m_type;
  bool is_api = (type >= NodeInfo::API && type <= NodeInfo::REP);
  bool old_dest = (getNodeInfo(nodeId).m_version < MAKE_VERSION(3,5,0));
  Uint32 TpacketTA = hostBuffer[nodeId].noOfPacketsTA;
  Uint32 TpacketLen = hostBuffer[nodeId].packetLenTA;

  if (ERROR_INSERTED(4006) && (nodeId != getOwnNodeId())){
    // Use error insert to turn routing on
    ljam();
    connectedToNode = false;
  }

  Uint32 sig0 = regOperPtr->tcOperationPtr;
  Uint32 sig1 = regOperPtr->transid1;
  Uint32 sig2 = regOperPtr->transid2;

  TransIdAI * transIdAI =  (TransIdAI *)signal->getDataPtrSend();
  transIdAI->connectPtr = sig0;
  transIdAI->transId[0] = sig1;
  transIdAI->transId[1] = sig2;

  if (connectedToNode){
    /**
     * Own node -> execute direct
     */
    if(nodeId != getOwnNodeId()){
      ljam();

      /**
       * Send long sig
       */
      if(ToutBufIndex >= 22 && is_api && !old_dest) {
	ljam();
	/**
	 * Flush buffer so that order is maintained
	 */
	if (TpacketTA != 0) {
	  ljam();
	  BlockReference TBref = numberToRef(API_PACKED, nodeId);
	  MEMCOPY_NO_WORDS(&signal->theData[0],
			   &hostBuffer[nodeId].packetBufferTA[0],
			   TpacketLen);
	  sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
	  hostBuffer[nodeId].noOfPacketsTA = 0;
	  hostBuffer[nodeId].packetLenTA = 0;
	}//if
	LinearSectionPtr ptr[3];
	ptr[0].p = &signal->theData[25];
	ptr[0].sz = ToutBufIndex;
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3, JBB, ptr, 1);
	return;
      }

      /**
       * short sig + api -> buffer
       */
#ifndef NDB_NO_DROPPED_SIGNAL
      if (ToutBufIndex < 22 && is_api){
	ljam();
	bufferTRANSID_AI(signal, recBlockref, 3+ToutBufIndex);
	return;
      }//if
#endif

      /**
       * rest -> old send sig
       */
      Uint32 * src = signal->theData+25;
      if(ToutBufIndex >= 22){
	do {
	  ljam();
	  MEMCOPY_NO_WORDS(&signal->theData[3], src, 22);
	  sendSignal(recBlockref, GSN_TRANSID_AI, signal, 25, JBB);
	  ToutBufIndex -= 22;
	  src += 22;
	} while(ToutBufIndex >= 22);
      }

      if(ToutBufIndex > 0){
	ljam();
	MEMCOPY_NO_WORDS(&signal->theData[3], src, ToutBufIndex);
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3+ToutBufIndex, JBB);
      }
      return;
    }
    EXECUTE_DIRECT(block, GSN_TRANSID_AI, signal, 3 + ToutBufIndex);
    ljamEntry();
    return;
  }

  /**
   * If this node does not have a direct connection
   * to the receiving node we want to send the signals
   * routed via the node that controls this read
   */
  Uint32 routeBlockref = regOperPtr->coordinatorTC;

  if(true){ // TODO is_api && !old_dest){
    ljam();
    transIdAI->attrData[0] = recBlockref;
    LinearSectionPtr ptr[3];
    ptr[0].p = &signal->theData[25];
    ptr[0].sz = ToutBufIndex;
    sendSignal(routeBlockref, GSN_TRANSID_AI_R, signal, 4, JBB, ptr, 1);
    return;
  }

  /**
   * Fill in a TRANSID_AI signal, use last word to store
   * final destination and send it to route node
   * as signal TRANSID_AI_R (R as in Routed)
   */
  Uint32 tot = ToutBufIndex;
  Uint32 sent = 0;
  Uint32 maxLen = TransIdAI::DataLength - 1;
  while (sent < tot) {
    ljam();
    Uint32 dataLen = (tot - sent > maxLen) ? maxLen : tot - sent;
    Uint32 sigLen = dataLen + TransIdAI::HeaderLength + 1;
    MEMCOPY_NO_WORDS(&transIdAI->attrData,
		     &signal->theData[25+sent],
		     dataLen);
    // Set final destination in last word
    transIdAI->attrData[dataLen] = recBlockref;

    sendSignal(routeBlockref, GSN_TRANSID_AI_R,
	       signal, sigLen, JBB);
    sent += dataLen;
  }
}//Dbtup::sendReadAttrinfo()
<commit_msg>Restore transid when flushing<commit_after>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBTUP_C
#include "Dbtup.hpp"
#include <RefConvert.hpp>
#include <ndb_limits.h>
#include <pc.hpp>
#include <signaldata/TransIdAI.hpp>

#define ljam() { jamLine(2000 + __LINE__); }
#define ljamEntry() { jamEntryLine(2000 + __LINE__); }

void Dbtup::execSEND_PACKED(Signal* signal)
{
  Uint16 hostId;
  Uint32 i;
  Uint32 TpackedListIndex = cpackedListIndex;
  ljamEntry();
  for (i = 0; i < TpackedListIndex; i++) {
    ljam();
    hostId = cpackedList[i];
    ndbrequire((hostId - 1) < (MAX_NODES - 1)); // Also check not zero
    Uint32 TpacketTA = hostBuffer[hostId].noOfPacketsTA;
    if (TpacketTA != 0) {
      ljam();
      BlockReference TBref = numberToRef(API_PACKED, hostId);
      Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
      MEMCOPY_NO_WORDS(&signal->theData[0],
                       &hostBuffer[hostId].packetBufferTA[0],
                       TpacketLen);
      sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
      hostBuffer[hostId].noOfPacketsTA = 0;
      hostBuffer[hostId].packetLenTA = 0;
    }//if
    hostBuffer[hostId].inPackedList = false;
  }//for
  cpackedListIndex = 0;
}//Dbtup::execSEND_PACKED()

void Dbtup::bufferTRANSID_AI(Signal* signal, BlockReference aRef,
                             Uint32 Tlen)
{
  if(Tlen == 3)
    return;

  Uint32 hostId = refToNode(aRef);
  Uint32 Theader = ((refToBlock(aRef) << 16)+(Tlen-3));

  ndbrequire(hostId < MAX_NODES);
  Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
  Uint32 TnoOfPackets = hostBuffer[hostId].noOfPacketsTA;
  Uint32 sig0 = signal->theData[0];
  Uint32 sig1 = signal->theData[1];
  Uint32 sig2 = signal->theData[2];

  BlockReference TBref = numberToRef(API_PACKED, hostId);

  if ((Tlen + TpacketLen + 1) <= 25) {
// ----------------------------------------------------------------
// There is still space in the buffer. We will copy it into the
// buffer.
// ----------------------------------------------------------------
    ljam();
    updatePackedList(signal, hostId);
  } else if (false && TnoOfPackets == 1) {
// ----------------------------------------------------------------
// The buffer is full and there was only one packet buffered. We
// will send this as a normal signal.
// ----------------------------------------------------------------
    Uint32 TnewRef = numberToRef((hostBuffer[hostId].packetBufferTA[0] >> 16),
                                 hostId);
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[1],
                     TpacketLen - 1);
    sendSignal(TnewRef, GSN_TRANSID_AI, signal, (TpacketLen - 1), JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  } else {
// ----------------------------------------------------------------
// The buffer is full but at least two packets. Send those in
// packed form.
// ----------------------------------------------------------------
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[0],
                     TpacketLen);
    sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  }//if
// ----------------------------------------------------------------
// Copy the signal into the buffer
// ----------------------------------------------------------------
  hostBuffer[hostId].packetBufferTA[TpacketLen + 0] = Theader;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 1] = sig0;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 2] = sig1;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 3] = sig2;
  hostBuffer[hostId].noOfPacketsTA = TnoOfPackets + 1;
  hostBuffer[hostId].packetLenTA = Tlen + TpacketLen + 1;
  MEMCOPY_NO_WORDS(&hostBuffer[hostId].packetBufferTA[TpacketLen + 4],
                   &signal->theData[25],
                   Tlen - 3);
}//Dbtup::bufferTRANSID_AI()

void Dbtup::updatePackedList(Signal* signal, Uint16 hostId)
{
  if (hostBuffer[hostId].inPackedList == false) {
    Uint32 TpackedListIndex = cpackedListIndex;
    ljam();
    hostBuffer[hostId].inPackedList = true;
    cpackedList[TpackedListIndex] = hostId;
    cpackedListIndex = TpackedListIndex + 1;
  }//if
}//Dbtup::updatePackedList()

/* ---------------------------------------------------------------- */
/* ----------------------- SEND READ ATTRINFO --------------------- */
/* ---------------------------------------------------------------- */
void Dbtup::sendReadAttrinfo(Signal* signal,
                             Uint32 ToutBufIndex,
                             const Operationrec * const regOperPtr)
{
  const BlockReference recBlockref = regOperPtr->recBlockref;
  const Uint32 sig0 = regOperPtr->tcOperationPtr;
  const Uint32 sig1 = regOperPtr->transid1;
  const Uint32 sig2 = regOperPtr->transid2;

  const Uint32 block = refToBlock(recBlockref);
  const Uint32 nodeId = refToNode(recBlockref);

  bool connectedToNode = getNodeInfo(nodeId).m_connected;
  const Uint32 type = getNodeInfo(nodeId).m_type;
  bool is_api = (type >= NodeInfo::API && type <= NodeInfo::REP);
  bool old_dest = (getNodeInfo(nodeId).m_version < MAKE_VERSION(3,5,0));
  const Uint32 TpacketTA = hostBuffer[nodeId].noOfPacketsTA;
  const Uint32 TpacketLen = hostBuffer[nodeId].packetLenTA;

  if (ERROR_INSERTED(4006) && (nodeId != getOwnNodeId())){
    // Use error insert to turn routing on
    ljam();
    connectedToNode = false;
  }

  TransIdAI * transIdAI =  (TransIdAI *)signal->getDataPtrSend();
  transIdAI->connectPtr = sig0;
  transIdAI->transId[0] = sig1;
  transIdAI->transId[1] = sig2;

  if (connectedToNode){
    /**
     * Own node -> execute direct
     */
    if(nodeId != getOwnNodeId()){
      ljam();

      /**
       * Send long sig
       */
      if(ToutBufIndex >= 22 && is_api && !old_dest) {
	ljam();
	/**
	 * Flush buffer so that order is maintained
	 */
	if (TpacketTA != 0) {
	  ljam();
	  BlockReference TBref = numberToRef(API_PACKED, nodeId);
	  MEMCOPY_NO_WORDS(&signal->theData[0],
			   &hostBuffer[nodeId].packetBufferTA[0],
			   TpacketLen);
	  sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
	  hostBuffer[nodeId].noOfPacketsTA = 0;
	  hostBuffer[nodeId].packetLenTA = 0;
	  transIdAI->connectPtr = sig0;
	  transIdAI->transId[0] = sig1;
	  transIdAI->transId[1] = sig2;
	}//if
	LinearSectionPtr ptr[3];
	ptr[0].p = &signal->theData[25];
	ptr[0].sz = ToutBufIndex;
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3, JBB, ptr, 1);
	return;
      }

      /**
       * short sig + api -> buffer
       */
#ifndef NDB_NO_DROPPED_SIGNAL
      if (ToutBufIndex < 22 && is_api){
	ljam();
	bufferTRANSID_AI(signal, recBlockref, 3+ToutBufIndex);
	return;
      }//if
#endif

      /**
       * rest -> old send sig
       */
      Uint32 * src = signal->theData+25;
      if(ToutBufIndex >= 22){
	do {
	  ljam();
	  MEMCOPY_NO_WORDS(&signal->theData[3], src, 22);
	  sendSignal(recBlockref, GSN_TRANSID_AI, signal, 25, JBB);
	  ToutBufIndex -= 22;
	  src += 22;
	} while(ToutBufIndex >= 22);
      }

      if(ToutBufIndex > 0){
	ljam();
	MEMCOPY_NO_WORDS(&signal->theData[3], src, ToutBufIndex);
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3+ToutBufIndex, JBB);
      }
      return;
    }
    EXECUTE_DIRECT(block, GSN_TRANSID_AI, signal, 3 + ToutBufIndex);
    ljamEntry();
    return;
  }

  /**
   * If this node does not have a direct connection
   * to the receiving node we want to send the signals
   * routed via the node that controls this read
   */
  Uint32 routeBlockref = regOperPtr->coordinatorTC;

  if(true){ // TODO is_api && !old_dest){
    ljam();
    transIdAI->attrData[0] = recBlockref;
    LinearSectionPtr ptr[3];
    ptr[0].p = &signal->theData[25];
    ptr[0].sz = ToutBufIndex;
    sendSignal(routeBlockref, GSN_TRANSID_AI_R, signal, 4, JBB, ptr, 1);
    return;
  }

  /**
   * Fill in a TRANSID_AI signal, use last word to store
   * final destination and send it to route node
   * as signal TRANSID_AI_R (R as in Routed)
   */
  Uint32 tot = ToutBufIndex;
  Uint32 sent = 0;
  Uint32 maxLen = TransIdAI::DataLength - 1;
  while (sent < tot) {
    ljam();
    Uint32 dataLen = (tot - sent > maxLen) ? maxLen : tot - sent;
    Uint32 sigLen = dataLen + TransIdAI::HeaderLength + 1;
    MEMCOPY_NO_WORDS(&transIdAI->attrData,
		     &signal->theData[25+sent],
		     dataLen);
    // Set final destination in last word
    transIdAI->attrData[dataLen] = recBlockref;

    sendSignal(routeBlockref, GSN_TRANSID_AI_R,
	       signal, sigLen, JBB);
    sent += dataLen;
  }
}//Dbtup::sendReadAttrinfo()
<|endoftext|>


<commit_before>/*
Description:
This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module.
You can get one of those products on
http://sandboxelectronics.com

Version:
V0.1

Release Date:
2014-02-16

Author:
Tiequan Shao          info@sandboxelectronics.com

Lisence:
CC BY-NC-SA 3.0

Please keep the above information when you use this code in your project.
*/
#pragma once
#ifndef _SC16IS750_H_
#define _SC16IS750_H_

#include "SC16IS750-library.h"
#include "application.h"

#ifdef ARDUINO
  #if (ARDUINO >= 100)
   #include <Arduino.h>
  #else
   #include <WProgram.h>
   #include <pins_arduino.h>
  #endif
#elif USE_SPARK_CORE_V02
  #include <spark_related_stuff_v2.h>
#elif USE_SPARK_CORE_V01
  #include <spark_related_stuff_v1.h>
#endif

/*
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif
*/

//Device Address

//A:VDD
//B:GND
//C:SCL
//D:SDA
#define     SC16IS750_ADDRESS_AA     (0X90)
#define     SC16IS750_ADDRESS_AB     (0X92)
#define     SC16IS750_ADDRESS_AC     (0X94)
#define     SC16IS750_ADDRESS_AD     (0X96)
#define     SC16IS750_ADDRESS_BA     (0X98)
#define     SC16IS750_ADDRESS_BB     (0X9A)
#define     SC16IS750_ADDRESS_BC     (0X9C)
#define     SC16IS750_ADDRESS_BD     (0X9E)
#define     SC16IS750_ADDRESS_CA     (0XA0)
#define     SC16IS750_ADDRESS_CB     (0XA2)
#define     SC16IS750_ADDRESS_CC     (0XA4)
#define     SC16IS750_ADDRESS_CD     (0XA6)
#define     SC16IS750_ADDRESS_DA     (0XA8)
#define     SC16IS750_ADDRESS_DB     (0XAA)
#define     SC16IS750_ADDRESS_DC     (0XAC)
#define     SC16IS750_ADDRESS_DD     (0XAE)

//General Registers
#define     SC16IS750_REG_RHR        (0x00)
#define     SC16IS750_REG_THR        (0X00)
#define     SC16IS750_REG_IER        (0X01)
#define     SC16IS750_REG_FCR        (0X02)
#define     SC16IS750_REG_IIR        (0X02)
#define     SC16IS750_REG_LCR        (0X03)
#define     SC16IS750_REG_MCR        (0X04)
#define     SC16IS750_REG_LSR        (0X05)
#define     SC16IS750_REG_MSR        (0X06)
#define     SC16IS750_REG_SPR        (0X07)
#define     SC16IS750_REG_TCR        (0X06)
#define     SC16IS750_REG_TLR        (0X07)
#define     SC16IS750_REG_TXLVL      (0X08)
#define     SC16IS750_REG_RXLVL      (0X09)
#define     SC16IS750_REG_IODIR      (0X0A)
#define     SC16IS750_REG_IOSTATE    (0X0B)
#define     SC16IS750_REG_IOINTENA   (0X0C)
#define     SC16IS750_REG_IOCONTROL  (0X0E)
#define     SC16IS750_REG_EFCR       (0X0F)

//Special Registers
#define     SC16IS750_REG_DLL        (0x00)
#define     SC16IS750_REG_DLH        (0X01)

//Enhanced Registers
#define     SC16IS750_REG_EFR        (0X02)
#define     SC16IS750_REG_XON1       (0X04)
#define     SC16IS750_REG_XON2       (0X05)
#define     SC16IS750_REG_XOFF1      (0X06)
#define     SC16IS750_REG_XOFF2      (0X07)

//
#define     SC16IS750_INT_CTS        (0X80)
#define     SC16IS750_INT_RTS        (0X40)
#define     SC16IS750_INT_XOFF       (0X20)
#define     SC16IS750_INT_SLEEP      (0X10)
#define     SC16IS750_INT_MODEM      (0X08)
#define     SC16IS750_INT_LINE       (0X04)
#define     SC16IS750_INT_THR        (0X02)
#define     SC16IS750_INT_RHR        (0X01)

//Application Related

#define     SC16IS750_CRYSTCAL_FREQ (14745600UL)
//#define 	SC16IS750_CRYSTCAL_FREQ (1843200UL)
//#define     SC16IS750_CRYSTCAL_FREQ (16000000UL)
//#define     SC16IS750_DEBUG_PRINT   (0)
#define     SC16IS750_PROTOCOL_I2C  (0)
#define     SC16IS750_PROTOCOL_SPI  (1)

class SC16IS750 // : public Stream
{
    public:
        SC16IS750(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD);
        void begin(uint32_t baud);
        int read();
        size_t write(uint8_t val);
        int available();
        void pinMode(uint8_t pin, uint8_t io);
        void digitalWrite(uint8_t pin, uint8_t value);
        uint8_t digitalRead(uint8_t pin);
		uint8_t ping();
	//	void setTimeout(uint32_t);
	//	size_t readBytes(char *buffer, size_t length);
		int peek();
		void flush();
		uint8_t GPIOGetPortState(void);
		uint8_t InterruptPendingTest(void);
		void    SetPinInterrupt(uint8_t io_int_ena);
		void    InterruptControl(uint8_t int_ena);
		void    ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios
		void    GPIOLatch(uint8_t latch);

    private:
        uint8_t device_address_sspin;
        uint8_t protocol;
	//	uint32_t timeout;
        int16_t SetBaudrate(uint32_t baudrate);
        uint8_t ReadRegister(uint8_t reg_addr);
        void    WriteRegister(uint8_t reg_addr, uint8_t val);
        void    SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length );
        void    GPIOSetPinMode(uint8_t pin_number, uint8_t i_o);
        void    GPIOSetPinState(uint8_t pin_number, uint8_t pin_state);

        uint8_t GPIOGetPinState(uint8_t pin_number);
        void    GPIOSetPortMode(uint8_t port_io);
        void    GPIOSetPortState(uint8_t port_state);
        void    ResetDevice(void);

        void    __isr(void);
        void    FIFOEnable(uint8_t fifo_enable);
        void    FIFOReset(uint8_t rx_fifo);
        void    FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length);
        uint8_t FIFOAvailableData(void);
        uint8_t FIFOAvailableSpace(void);
        void    WriteByte(uint8_t val);
        int     ReadByte(void);
        void    EnableTransmit(uint8_t tx_enable);
	//	int16_t readwithtimeout();
		int 	peek_buf;
		uint8_t peek_flag;

};

#endif
<commit_msg>Update SC16IS750-library.cpp<commit_after>/*
Description:
This is a example code for Sandbox Electronics' I2C/SPI to UART bridge module.
You can get one of those products on
http://sandboxelectronics.com

Version:
V0.1

Release Date:
2014-02-16

Author:
Tiequan Shao          info@sandboxelectronics.com

Lisence:
CC BY-NC-SA 3.0

Please keep the above information when you use this code in your project.
*/
#ifndef _SC16IS750_H_
#define _SC16IS750_H_

#include "SC16IS750-library.h"
#include "application.h"

#ifdef ARDUINO
  #if (ARDUINO >= 100)
   #include <Arduino.h>
  #else
   #include <WProgram.h>
   #include <pins_arduino.h>
  #endif
#elif USE_SPARK_CORE_V02
  #include <spark_related_stuff_v2.h>
#elif USE_SPARK_CORE_V01
  #include <spark_related_stuff_v1.h>
#endif

/*
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif
*/

//Device Address

//A:VDD
//B:GND
//C:SCL
//D:SDA
#define     SC16IS750_ADDRESS_AA     (0X90)
#define     SC16IS750_ADDRESS_AB     (0X92)
#define     SC16IS750_ADDRESS_AC     (0X94)
#define     SC16IS750_ADDRESS_AD     (0X96)
#define     SC16IS750_ADDRESS_BA     (0X98)
#define     SC16IS750_ADDRESS_BB     (0X9A)
#define     SC16IS750_ADDRESS_BC     (0X9C)
#define     SC16IS750_ADDRESS_BD     (0X9E)
#define     SC16IS750_ADDRESS_CA     (0XA0)
#define     SC16IS750_ADDRESS_CB     (0XA2)
#define     SC16IS750_ADDRESS_CC     (0XA4)
#define     SC16IS750_ADDRESS_CD     (0XA6)
#define     SC16IS750_ADDRESS_DA     (0XA8)
#define     SC16IS750_ADDRESS_DB     (0XAA)
#define     SC16IS750_ADDRESS_DC     (0XAC)
#define     SC16IS750_ADDRESS_DD     (0XAE)

//General Registers
#define     SC16IS750_REG_RHR        (0x00)
#define     SC16IS750_REG_THR        (0X00)
#define     SC16IS750_REG_IER        (0X01)
#define     SC16IS750_REG_FCR        (0X02)
#define     SC16IS750_REG_IIR        (0X02)
#define     SC16IS750_REG_LCR        (0X03)
#define     SC16IS750_REG_MCR        (0X04)
#define     SC16IS750_REG_LSR        (0X05)
#define     SC16IS750_REG_MSR        (0X06)
#define     SC16IS750_REG_SPR        (0X07)
#define     SC16IS750_REG_TCR        (0X06)
#define     SC16IS750_REG_TLR        (0X07)
#define     SC16IS750_REG_TXLVL      (0X08)
#define     SC16IS750_REG_RXLVL      (0X09)
#define     SC16IS750_REG_IODIR      (0X0A)
#define     SC16IS750_REG_IOSTATE    (0X0B)
#define     SC16IS750_REG_IOINTENA   (0X0C)
#define     SC16IS750_REG_IOCONTROL  (0X0E)
#define     SC16IS750_REG_EFCR       (0X0F)

//Special Registers
#define     SC16IS750_REG_DLL        (0x00)
#define     SC16IS750_REG_DLH        (0X01)

//Enhanced Registers
#define     SC16IS750_REG_EFR        (0X02)
#define     SC16IS750_REG_XON1       (0X04)
#define     SC16IS750_REG_XON2       (0X05)
#define     SC16IS750_REG_XOFF1      (0X06)
#define     SC16IS750_REG_XOFF2      (0X07)

//
#define     SC16IS750_INT_CTS        (0X80)
#define     SC16IS750_INT_RTS        (0X40)
#define     SC16IS750_INT_XOFF       (0X20)
#define     SC16IS750_INT_SLEEP      (0X10)
#define     SC16IS750_INT_MODEM      (0X08)
#define     SC16IS750_INT_LINE       (0X04)
#define     SC16IS750_INT_THR        (0X02)
#define     SC16IS750_INT_RHR        (0X01)

//Application Related

#define     SC16IS750_CRYSTCAL_FREQ (14745600UL)
//#define 	SC16IS750_CRYSTCAL_FREQ (1843200UL)
//#define     SC16IS750_CRYSTCAL_FREQ (16000000UL)
//#define     SC16IS750_DEBUG_PRINT   (0)
#define     SC16IS750_PROTOCOL_I2C  (0)
#define     SC16IS750_PROTOCOL_SPI  (1)

class SC16IS750 // : public Stream
{
    public:
        SC16IS750(uint8_t prtcl = SC16IS750_PROTOCOL_I2C, uint8_t addr = SC16IS750_ADDRESS_AD);
        void begin(uint32_t baud);
        int read();
        size_t write(uint8_t val);
        int available();
        void pinMode(uint8_t pin, uint8_t io);
        void digitalWrite(uint8_t pin, uint8_t value);
        uint8_t digitalRead(uint8_t pin);
		uint8_t ping();
	//	void setTimeout(uint32_t);
	//	size_t readBytes(char *buffer, size_t length);
		int peek();
		void flush();
		uint8_t GPIOGetPortState(void);
		uint8_t InterruptPendingTest(void);
		void    SetPinInterrupt(uint8_t io_int_ena);
		void    InterruptControl(uint8_t int_ena);
		void    ModemPin(uint8_t gpio); //gpio == 0, gpio[7:4] are modem pins, gpio == 1 gpio[7:4] are gpios
		void    GPIOLatch(uint8_t latch);

    private:
        uint8_t device_address_sspin;
        uint8_t protocol;
	//	uint32_t timeout;
        int16_t SetBaudrate(uint32_t baudrate);
        uint8_t ReadRegister(uint8_t reg_addr);
        void    WriteRegister(uint8_t reg_addr, uint8_t val);
        void    SetLine(uint8_t data_length, uint8_t parity_select, uint8_t stop_length );
        void    GPIOSetPinMode(uint8_t pin_number, uint8_t i_o);
        void    GPIOSetPinState(uint8_t pin_number, uint8_t pin_state);

        uint8_t GPIOGetPinState(uint8_t pin_number);
        void    GPIOSetPortMode(uint8_t port_io);
        void    GPIOSetPortState(uint8_t port_state);
        void    ResetDevice(void);

        void    __isr(void);
        void    FIFOEnable(uint8_t fifo_enable);
        void    FIFOReset(uint8_t rx_fifo);
        void    FIFOSetTriggerLevel(uint8_t rx_fifo, uint8_t length);
        uint8_t FIFOAvailableData(void);
        uint8_t FIFOAvailableSpace(void);
        void    WriteByte(uint8_t val);
        int     ReadByte(void);
        void    EnableTransmit(uint8_t tx_enable);
	//	int16_t readwithtimeout();
		int 	peek_buf;
		uint8_t peek_flag;

};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium 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 "net/base/host_resolver.h"
#include "net/base/address_list.h"
#include "testing/gtest/include/gtest/gtest.h"

#ifdef OS_WIN
#include <ws2tcpip.h>
#include <wspiapi.h>
#endif
#ifdef OS_POSIX
#include <netdb.h>
#endif

namespace {

class HostResolverTest : public testing::Test {
};

TEST(HostResolverTest, NumericAddresses) {
  // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.

  net::HostResolver host_resolver;
  net::AddressList adrlist;
  const int kPortnum = 5555;
  int err = host_resolver.Resolve("127.0.0.1", kPortnum, &adrlist, NULL);
  EXPECT_EQ(0, err);

  const struct addrinfo* ainfo = adrlist.head();
  EXPECT_EQ(NULL, ainfo->ai_next);
  EXPECT_EQ(sizeof(struct sockaddr_in), ainfo->ai_addrlen);

  const struct sockaddr* sa = ainfo->ai_addr;
  const struct sockaddr_in* sa_in = (const struct sockaddr_in*) sa;
  EXPECT_EQ(htons(kPortnum), sa_in->sin_port);
  EXPECT_EQ(htonl(0x7f000001), sa_in->sin_addr.s_addr);
}

} // namespace
<commit_msg>This fixes the "passing NULL to non-pointer argument" warning when compiling with gcc 4.1, and is consistent with the way EXPECT_EQ uses NULL elsewhere in Chrome.<commit_after>// Copyright (c) 2006-2008 The Chromium 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 "net/base/host_resolver.h"
#include "net/base/address_list.h"
#include "testing/gtest/include/gtest/gtest.h"

#ifdef OS_WIN
#include <ws2tcpip.h>
#include <wspiapi.h>
#endif
#ifdef OS_POSIX
#include <netdb.h>
#endif

namespace {

class HostResolverTest : public testing::Test {
};

TEST(HostResolverTest, NumericAddresses) {
  // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.

  net::HostResolver host_resolver;
  net::AddressList adrlist;
  const int kPortnum = 5555;
  int err = host_resolver.Resolve("127.0.0.1", kPortnum, &adrlist, NULL);
  EXPECT_EQ(0, err);

  const struct addrinfo* ainfo = adrlist.head();
  EXPECT_EQ(static_cast<addrinfo*>(NULL), ainfo->ai_next);
  EXPECT_EQ(sizeof(struct sockaddr_in), ainfo->ai_addrlen);

  const struct sockaddr* sa = ainfo->ai_addr;
  const struct sockaddr_in* sa_in = (const struct sockaddr_in*) sa;
  EXPECT_EQ(htons(kPortnum), sa_in->sin_port);
  EXPECT_EQ(htonl(0x7f000001), sa_in->sin_addr.s_addr);
}

} // namespace
<|endoftext|>


<commit_before>#include "writer/verilog/axi/slave_controller.h"

#include "writer/verilog/axi/slave_port.h"
#include "writer/verilog/module.h"
#include "writer/verilog/ports.h"

namespace iroha {
namespace writer {
namespace verilog {
namespace axi {

SlaveController::SlaveController(const IResource &res,
				 bool reset_polarity)
  : AxiController(res, reset_polarity) {
  ports_.reset(new Ports);
}

SlaveController::~SlaveController() {
}

void SlaveController::Write(ostream &os) {
  string name = SlavePort::ControllerName(res_, reset_polarity_);
  os << "// slave controller: "
     << name << "\n";
  AddSramPorts();
  string initials;
  GenReadChannel(cfg_, false, nullptr, ports_.get(), &initials);
  GenWriteChannel(cfg_, false, nullptr, ports_.get(), &initials);
  os << "module " << name << "(";
  ports_->Output(Ports::PORT_NAME, os);
  os << ");\n";
  ports_->Output(Ports::PORT_TYPE, os);

  os << "  `define S_IDLE 0\n"
     << "  `define S_READ 1\n"
     << "  `define S_WRITE 2\n";
  os << "  reg [1:0] st;\n\n";
  os << "  reg [" << sram_addr_width_ << ":0] idx;\n\n";
  os << "  reg first_addr;\n"
     << "  reg [7:0] rlen;\n\n";

  os << "  always @(posedge clk) begin\n"
     << "    if (" << (reset_polarity_ ? "" : "!")
     << ResetName(reset_polarity_) << ") begin\n"
     << "      st <= `S_IDLE;\n"
     << "      first_addr <= 0;\n"
     << "      rlen <= 0;\n";
  os << initials
     << "    end else begin\n";
  OutputFSM(os);
  os << "    end\n"
     << "  end\n"
     << "endmodule\n";
}

void SlaveController::AddPorts(const PortConfig &cfg, Module *mod, string *s) {
  Ports *ports = mod->GetPorts();
  GenWriteChannel(cfg, false, mod, ports, s);
  GenReadChannel(cfg, false, mod, ports, s);
}

void SlaveController::OutputFSM(ostream &os) {
  os << "      sram_wen <= (st == `S_WRITE && WVALID);\n"
     << "      RLAST <= (st == `S_READ && rlen == 0);\n";
  os << "      case (st)\n"
     << "        `S_IDLE: begin\n"
     << "          if (ARVALID) begin\n"
     << "            if (ARREADY) begin\n"
     << "              ARREADY <= 0;\n"
     << "              sram_addr <= ARADDR[" << (sram_addr_width_ - 1) << ":0];\n"
     << "              rlen <= ARLEN;\n"
     << "              st <= `S_READ;\n"
     << "            end else begin\n"
     << "              ARREADY <= 1;\n"
     << "            end\n"
     << "          end else if (AWVALID) begin\n"
     << "            if (AWREADY) begin\n"
     << "              AWREADY <= 0;\n"
     << "              first_addr <= 1;\n"
     << "              sram_addr <= AWADDR[" << (sram_addr_width_ - 1) << ":0];\n"
     << "              st <= `S_WRITE;\n"
     << "              WREADY <= 1;\n"
     << "            end else begin\n"
     << "              AWREADY <= 1;\n"
     << "            end\n"
     << "          end\n"
     << "        end\n"
     << "        `S_READ: begin\n"
     << "          if (RREADY && RVALID) begin\n"
     << "            sram_addr <= sram_addr + 1;\n"
     << "            rlen <= rlen - 1;\n"
     << "            if (rlen == 0) begin\n"
     << "              st <= `S_IDLE;\n"
     << "              RVALID <= 0;\n"
     << "            end\n"
     << "          end else begin\n"
     << "            RVALID <= 1;\n"
     << "          end\n"
     << "          RDATA <= sram_rdata;\n"
     << "        end\n"
     << "        `S_WRITE: begin\n"
     << "          if (WVALID) begin\n"
     << "            sram_wdata <= WDATA;\n"
     << "            if (first_addr) begin\n"
     << "              first_addr <= 0;\n"
     << "            end else begin\n"
     << "              sram_addr <= sram_addr + 1;\n"
     << "            end\n"
     << "          end\n"
     << "          if (WLAST && WVALID) begin\n"
     << "            st <= `S_IDLE;\n"
     << "            WREADY <= 0;\n"
     << "          end\n"
     << "        end\n";
  os << "      endcase\n";
}

}  // namespace axi
}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<commit_msg>Fix RLAST logic.<commit_after>#include "writer/verilog/axi/slave_controller.h"

#include "writer/verilog/axi/slave_port.h"
#include "writer/verilog/module.h"
#include "writer/verilog/ports.h"

namespace iroha {
namespace writer {
namespace verilog {
namespace axi {

SlaveController::SlaveController(const IResource &res,
				 bool reset_polarity)
  : AxiController(res, reset_polarity) {
  ports_.reset(new Ports);
}

SlaveController::~SlaveController() {
}

void SlaveController::Write(ostream &os) {
  string name = SlavePort::ControllerName(res_, reset_polarity_);
  os << "// slave controller: "
     << name << "\n";
  AddSramPorts();
  string initials;
  GenReadChannel(cfg_, false, nullptr, ports_.get(), &initials);
  GenWriteChannel(cfg_, false, nullptr, ports_.get(), &initials);
  os << "module " << name << "(";
  ports_->Output(Ports::PORT_NAME, os);
  os << ");\n";
  ports_->Output(Ports::PORT_TYPE, os);

  os << "  `define S_IDLE 0\n"
     << "  `define S_READ 1\n"
     << "  `define S_WRITE 2\n";
  os << "  reg [1:0] st;\n\n";
  os << "  reg [" << sram_addr_width_ << ":0] idx;\n\n";
  os << "  reg first_addr;\n"
     << "  reg [7:0] rlen;\n\n";

  os << "  always @(posedge clk) begin\n"
     << "    if (" << (reset_polarity_ ? "" : "!")
     << ResetName(reset_polarity_) << ") begin\n"
     << "      st <= `S_IDLE;\n"
     << "      first_addr <= 0;\n"
     << "      rlen <= 0;\n";
  os << initials
     << "    end else begin\n";
  OutputFSM(os);
  os << "    end\n"
     << "  end\n"
     << "endmodule\n";
}

void SlaveController::AddPorts(const PortConfig &cfg, Module *mod, string *s) {
  Ports *ports = mod->GetPorts();
  GenWriteChannel(cfg, false, mod, ports, s);
  GenReadChannel(cfg, false, mod, ports, s);
}

void SlaveController::OutputFSM(ostream &os) {
  os << "      sram_wen <= (st == `S_WRITE && WVALID);\n"
     << "      case (st)\n"
     << "        `S_IDLE: begin\n"
     << "          if (ARVALID) begin\n"
     << "            if (ARREADY) begin\n"
     << "              ARREADY <= 0;\n"
     << "              sram_addr <= ARADDR[" << (sram_addr_width_ - 1) << ":0];\n"
     << "              rlen <= ARLEN;\n"
     << "              st <= `S_READ;\n"
     << "            end else begin\n"
     << "              ARREADY <= 1;\n"
     << "            end\n"
     << "          end else if (AWVALID) begin\n"
     << "            if (AWREADY) begin\n"
     << "              AWREADY <= 0;\n"
     << "              first_addr <= 1;\n"
     << "              sram_addr <= AWADDR[" << (sram_addr_width_ - 1) << ":0];\n"
     << "              st <= `S_WRITE;\n"
     << "              WREADY <= 1;\n"
     << "            end else begin\n"
     << "              AWREADY <= 1;\n"
     << "            end\n"
     << "          end\n"
     << "        end\n"
     << "        `S_READ: begin\n"
     << "          if (RREADY && RVALID) begin\n"
     << "            sram_addr <= sram_addr + 1;\n"
     << "            rlen <= rlen - 1;\n"
     << "            if (rlen == 0) begin\n"
     << "              st <= `S_IDLE;\n"
     << "              RLAST <= 0;\n"
     << "              RVALID <= 0;\n"
     << "            end\n"
     << "          end else begin\n"
     << "            RVALID <= 1;\n"
     << "            if (rlen == 0) begin\n"
     << "              RLAST <= 1;\n"
     << "            end\n"
     << "          end\n"
     << "          RDATA <= sram_rdata;\n"
     << "        end\n"
     << "        `S_WRITE: begin\n"
     << "          if (WVALID) begin\n"
     << "            sram_wdata <= WDATA;\n"
     << "            if (first_addr) begin\n"
     << "              first_addr <= 0;\n"
     << "            end else begin\n"
     << "              sram_addr <= sram_addr + 1;\n"
     << "            end\n"
     << "          end\n"
     << "          if (WLAST && WVALID) begin\n"
     << "            st <= `S_IDLE;\n"
     << "            WREADY <= 0;\n"
     << "          end\n"
     << "        end\n";
  os << "      endcase\n";
}

}  // namespace axi
}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<|endoftext|>


<commit_before>#include <fmo/algorithm.hpp>
#include <map>

namespace fmo {
    Algorithm::Config::Config()
        : name("explorer-v2"),
          diff(),
          //
          maxGapX(0.025f),
          minGapY(0.050f),
          maxImageHeight(300),
          minStripHeight(2),
          minStripsInObject(6),
          minStripArea(0.6f),
          minAspect(1.5f),
          matchAspectMax(2.f),
          matchAreaMax(2.f),
          matchDistanceMax(20.f),
          matchAngleMax(0.5f),
          matchAspectWeight(1.f),
          matchAreaWeight(1.f),
          matchDistanceWeight(1.f),
          matchAngleWeight(1.f),
          //
          minStripsInComponent(2),
          minStripsInCluster(12),
          minClusterLength(2.f),
          heightRatioWeight(1.f),
          distanceWeight(0.f),
          gapsWeight(1.f),
          maxHeightRatioStrips(1.75001f),
          maxHeightRatioInternal(1.75001f),
          maxHeightRatioExternal(1.99999f),
          maxDistance(20.f),
          maxGapsLength(0.75f),
          minMotion(0.25f),
          maxMotion(0.50f),
          pointSetSourceResolution(false) {}

    using AlgorithmRegistry = std::map<std::string, Algorithm::Factory>;

    AlgorithmRegistry& getRegistry() {
        static AlgorithmRegistry registry;
        return registry;
    }

    void registerExplorerV1();
    void registerExplorerV2();
    void registerExplorerV3();
    void registerMedianV1();

    void registerBuiltInFactories() {
        static bool registered = false;
        if (registered) return;
        registered = true;

        registerExplorerV1();
        registerExplorerV2();
        registerExplorerV3();
        registerMedianV1();
    }

    std::unique_ptr<Algorithm> fmo::Algorithm::make(const Config& config, Format format,
                                                    Dims dims) {
        registerBuiltInFactories();
        auto& registry = getRegistry();
        auto it = registry.find(config.name);
        if (it == registry.end()) { throw std::runtime_error("unknown algorithm name"); }
        return it->second(config, format, dims);
    }

    void Algorithm::registerFactory(const std::string& name, const Factory& factory) {
        auto& registry = getRegistry();
        auto it = registry.find(name);
        if (it != registry.end()) { throw std::runtime_error("duplicate algorithm name"); }
        registry.emplace(name, factory);
    }

    std::vector<std::string> Algorithm::listFactories() {
        registerBuiltInFactories();
        const auto& registry = getRegistry();
        std::vector<std::string> result;

        for (auto& entry : registry) { result.push_back(entry.first); }

        return result;
    }
}
<commit_msg>Tune parameters<commit_after>#include <fmo/algorithm.hpp>
#include <map>

namespace fmo {
    Algorithm::Config::Config()
        : name("explorer-v2"),
          diff(),
          //
          maxGapX(0.025f),
          minGapY(0.050f),
          maxImageHeight(300),
          minStripHeight(2),
          minStripsInObject(6),
          minStripArea(0.6f),
          minAspect(1.0f),
          matchAspectMax(2.f),
          matchAreaMax(2.f),
          matchDistanceMax(5.f),
          matchAngleMax(0.5f),
          matchAspectWeight(1.f),
          matchAreaWeight(1.f),
          matchDistanceWeight(1.f),
          matchAngleWeight(1.f),
          //
          minStripsInComponent(2),
          minStripsInCluster(12),
          minClusterLength(2.f),
          heightRatioWeight(1.f),
          distanceWeight(0.f),
          gapsWeight(1.f),
          maxHeightRatioStrips(1.75001f),
          maxHeightRatioInternal(1.75001f),
          maxHeightRatioExternal(1.99999f),
          maxDistance(20.f),
          maxGapsLength(0.75f),
          minMotion(0.25f),
          maxMotion(0.50f),
          pointSetSourceResolution(false) {}

    using AlgorithmRegistry = std::map<std::string, Algorithm::Factory>;

    AlgorithmRegistry& getRegistry() {
        static AlgorithmRegistry registry;
        return registry;
    }

    void registerExplorerV1();
    void registerExplorerV2();
    void registerExplorerV3();
    void registerMedianV1();

    void registerBuiltInFactories() {
        static bool registered = false;
        if (registered) return;
        registered = true;

        registerExplorerV1();
        registerExplorerV2();
        registerExplorerV3();
        registerMedianV1();
    }

    std::unique_ptr<Algorithm> fmo::Algorithm::make(const Config& config, Format format,
                                                    Dims dims) {
        registerBuiltInFactories();
        auto& registry = getRegistry();
        auto it = registry.find(config.name);
        if (it == registry.end()) { throw std::runtime_error("unknown algorithm name"); }
        return it->second(config, format, dims);
    }

    void Algorithm::registerFactory(const std::string& name, const Factory& factory) {
        auto& registry = getRegistry();
        auto it = registry.find(name);
        if (it != registry.end()) { throw std::runtime_error("duplicate algorithm name"); }
        registry.emplace(name, factory);
    }

    std::vector<std::string> Algorithm::listFactories() {
        registerBuiltInFactories();
        const auto& registry = getRegistry();
        std::vector<std::string> result;

        for (auto& entry : registry) { result.push_back(entry.first); }

        return result;
    }
}
<|endoftext|>