<commit_before>#include "ride/quickopendlg.h"

#include "ride/wx.h"
#include "ride/generated/ui.h"
#include "ride/wxutils.h"
#include <vector>
#include <set>

// based on http://docs.wholetomato.com/default.asp?W193

class QuickOpenDlg : public ui::QuickOpen {
public:
  QuickOpenDlg(wxWindow* parent);

private:
  void UpdateFilters();

protected:
  void OnCancel(wxCommandEvent& event);
  void OnOk(wxCommandEvent& event);
  void OnActivate(wxActivateEvent& event);
  void OnFilterKeyUp(wxKeyEvent& event);
  void OnFilterUpdated(wxCommandEvent& event);
  void OnFilterNameEnter(wxCommandEvent& event);

  std::vector<wxString> files_;
};

void AddIfMoreThanOne(std::vector<wxString>& ret, const std::vector<wxString>& space) {
  if (space.size() != 1) {
    ret.insert(ret.begin(), space.begin(), space.end());
  }
}

std::vector<wxString> SmartSplit(const wxString& str, const wxString& full) {
  const auto space = Split(str, ' ');
  const auto dash = Split(str, '-');
  const auto under = Split(str, '_');
  std::vector<wxString> ret;
  ret.push_back(full);

  AddIfMoreThanOne(ret, space);
  AddIfMoreThanOne(ret, dash);
  AddIfMoreThanOne(ret, under);

  return ret;
}

int StartWithCount(const wxString& base, const wxString& test) {
  for (int i = 0; i < test.length(); ++i) {
    // base is shorter than test string, abort
    if (i >= base.length() ) return i;

    // base string doesn't match, abort
    if (base[i] != test[i]) return i;
  }
  return test.length();
}

bool MatchFilter(const wxString& filter, const wxString file, int* count) {
  const wxFileName name(file);
  const auto filters = RemoveEmptyStrings(Split(filter, ' '));
  const auto parts = SmartSplit(name.GetName(), name.GetFullName());
  if (filters.empty()) return true;
  for (auto fi : filters) {
    const bool exclude = fi.StartsWith("-");
    const wxString fl = exclude ? fi.Mid(1) : fi;
    const bool check_end_of_part = fl.EndsWith(".");
    const wxString f = check_end_of_part ? fl.Left(fl.Length() - 1) : fl;
    const bool partial_matching = f.Contains(".");
    for (auto part : parts) {
      int change_match_count_by = 0;
      if (partial_matching) {
        if (part.find(f) != wxString::npos) {
          change_match_count_by = 1;
        }
      }
      else {
        if (check_end_of_part) {
          if (part.EndsWith(f)) {
            change_match_count_by = 1;
          }
        }
        else {
          change_match_count_by = StartWithCount(part, f);
        }
      }
      if (change_match_count_by > 0) {
        if (exclude) return false;
        *count += change_match_count_by;
      }
    }
  }
  return *count > 0;
}

struct FilterMatch {
  wxString path;
  int count;

  FilterMatch(const wxString& p, int c) : path(p), count(c) {}
  bool operator<(const FilterMatch& rhs) const {
    if (count == rhs.count) return path < rhs.path;
    else return count < rhs.count;
  }
};

void QuickOpenDlg::UpdateFilters() {
  const wxString filter = uiFilterName->GetValue();

  std::set<FilterMatch> matches;
  for (const wxString& file : files_) {
    int count = 0;
    if (MatchFilter(filter, file, &count)) {
      FilterMatch m(file, count);
      assert(matches.find(m) == matches.end());
      matches.insert(m);
    }
  }

  uiFileList->Freeze();
  uiFileList->DeleteAllItems();
  for (const FilterMatch& match: matches) {
    int i = uiFileList->InsertItem(0, "");
    uiFileList->SetItem(i, 0, wxFileName(match.path).GetFullName());
    uiFileList->SetItem(i, 1, match.path);
    uiFileList->SetItem(i, 2, wxString::Format("%d", match.count));
  }
  if (matches.empty() == false) {
    SetSelection(uiFileList, 0, true);
  }
  uiFileList->Thaw();
}

QuickOpenDlg::QuickOpenDlg(wxWindow* parent)
  : ui::QuickOpen(parent, wxID_ANY)
{
  const long file_index = uiFileList->InsertColumn(0, "File");
  const long path_index = uiFileList->InsertColumn(1, "Path");
  const long count_index = uiFileList->InsertColumn(2, "Hits");
  uiFileList->SetColumnWidth(file_index, 150);
  uiFileList->SetColumnWidth(path_index, 300);
  uiFileList->SetColumnWidth(count_index, 50);

  /*files_.push_back("/project/dog/src/BigCalendarCtrl.rs");
  files_.push_back("/project/dog/src/BigCalendarTask.rs");
  files_.push_back("/project/dog/src/CalendarButtonsDlg.rs");
  files_.push_back("/project/dog/src/CalendarData.rs");
  files_.push_back("/project/dog/src/CalendarDefines.rs");
  files_.push_back("/project/dog/src/CalendarExt.rs");
  files_.push_back("/project/dog/src/CalendarExt.rs");
  */

  files_.push_back("/project/dog/src/big-calendar-ctrl.rs");
  files_.push_back("/project/dog/src/big-calendar-task.rs");
  files_.push_back("/project/dog/src/calendar-buttons-dlg.rs");
  files_.push_back("/project/dog/src/calendar-data.rs");
  files_.push_back("/project/dog/src/calendar-defines.rs");
  files_.push_back("/project/dog/src/calendar-ext.rs");
  files_.push_back("/project/dog/assets/pixel-shader.glsl");
  files_.push_back("/project/dog/assets/fragment-shader.glsl");
  files_.push_back("/project/dog/assets/texture-enemy.png");

  files_.push_back("/project/dog/assets/texture-enemy.template.png");
  /*
  files_.push_back("/project/dog/src/big_calendar_ctrl.rs");
  files_.push_back("/project/dog/src/big_calendar_task.rs");
  files_.push_back("/project/dog/src/calendar_buttons_dlg.rs");
  files_.push_back("/project/dog/src/calendar_data.rs");
  files_.push_back("/project/dog/src/calendar_defines.rs");
  files_.push_back("/project/dog/src/calendar_ext.rs");
  files_.push_back("/project/dog/src/calendar_ext.rs");*/

  uiFileList->Bind(wxEVT_KEY_DOWN, &QuickOpenDlg::OnFilterKeyUp, this);
  UpdateFilters();
}

void QuickOpenDlg::OnActivate(wxActivateEvent& event) {
  uiFilterName->SelectAll();
  uiFilterName->SetFocus();
  uiFilterName->SetFocusFromKbd();
}

void QuickOpenDlg::OnFilterKeyUp(wxKeyEvent& event) {
  if (event.GetKeyCode() == wxUP) {
    auto selected = GetSelection(uiFileList);
    if (selected.empty()){
      SetSelection(uiFileList, 0, true);
    }
    else {
      long last = *selected.begin();
      if (event.ShiftDown() == false) ClearSelection(uiFileList);
      SetSelection(uiFileList, last - 1, true);
    }
  }
  else if (event.GetKeyCode() == wxDOWN) {
    auto selected = GetSelection(uiFileList);
    if (selected.empty()){
      SetSelection(uiFileList, 0, true);
    }
    else {
      long last = *selected.rbegin();
      if (event.ShiftDown() == false) ClearSelection(uiFileList);
      SetSelection(uiFileList, last + 1, true);
    }
  }
  else {
    event.Skip();
  }
}

void QuickOpenDlg::OnFilterNameEnter(wxCommandEvent& event) {
  EndModal(wxID_OK);
}

void QuickOpenDlg::OnFilterUpdated(wxCommandEvent& event) {
  UpdateFilters();
}

void QuickOpenDlg::OnCancel(wxCommandEvent& event) {
  EndModal(wxID_CANCEL);
}

void QuickOpenDlg::OnOk(wxCommandEvent& event) {
  EndModal(wxID_OK);
}

bool ShowQuickOpenDlg(wxWindow* parent) {
  QuickOpenDlg dlg(parent);
  if (wxID_OK != dlg.ShowModal()) return false;;
  // do something!
  return true;
}
<commit_msg>matching end tries to ignore typos<commit_after>#include "ride/quickopendlg.h"

#include "ride/wx.h"
#include "ride/generated/ui.h"
#include "ride/wxutils.h"
#include <vector>
#include <set>

// based on http://docs.wholetomato.com/default.asp?W193

class QuickOpenDlg : public ui::QuickOpen {
public:
  QuickOpenDlg(wxWindow* parent);

private:
  void UpdateFilters();

protected:
  void OnCancel(wxCommandEvent& event);
  void OnOk(wxCommandEvent& event);
  void OnActivate(wxActivateEvent& event);
  void OnFilterKeyUp(wxKeyEvent& event);
  void OnFilterUpdated(wxCommandEvent& event);
  void OnFilterNameEnter(wxCommandEvent& event);

  std::vector<wxString> files_;
};

void AddIfMoreThanOne(std::vector<wxString>& ret, const std::vector<wxString>& space) {
  if (space.size() != 1) {
    ret.insert(ret.begin(), space.begin(), space.end());
  }
}

std::vector<wxString> SmartSplit(const wxString& str, const wxString& full) {
  const auto space = Split(str, ' ');
  const auto dash = Split(str, '-');
  const auto under = Split(str, '_');
  std::vector<wxString> ret;
  ret.push_back(full);

  AddIfMoreThanOne(ret, space);
  AddIfMoreThanOne(ret, dash);
  AddIfMoreThanOne(ret, under);

  return ret;
}

int StartWithCount(const wxString& base, const wxString& test) {
  for (int i = 0; i < test.length(); ++i) {
    // base is shorter than test string, abort
    if (i >= base.length() ) return i;

    // base string doesn't match, abort
    if (base[i] != test[i]) return i;
  }
  return test.length();
}

int EndsWithCount(const wxString& base, const wxString& test) {
  for (int i = 0; i < test.length(); ++i) {
    // base is shorter than test string, abort
    if (i >= base.length()) return i;

    // base string doesn't match, abort
    if (base[base.length()-(i+1)] != test[test.length() - (i+1)]) return i;
  }
  return test.length();
}

bool MatchFilter(const wxString& filter, const wxString file, int* count) {
  const wxFileName name(file);
  const auto filters = RemoveEmptyStrings(Split(filter, ' '));
  const auto parts = SmartSplit(name.GetName(), name.GetFullName());
  if (filters.empty()) return true;
  for (auto fi : filters) {
    const bool exclude = fi.StartsWith("-");
    const wxString fl = exclude ? fi.Mid(1) : fi;
    const bool check_end_of_part = fl.EndsWith(".");
    const wxString f = check_end_of_part ? fl.Left(fl.Length() - 1) : fl;
    const bool partial_matching = f.Contains(".");
    for (auto part : parts) {
      int change_match_count_by = 0;
      if (partial_matching) {
        if (part.find(f) != wxString::npos) {
          change_match_count_by = 1;
        }
      }
      else {
        if (check_end_of_part) {
          change_match_count_by = EndsWithCount(part, f);
        }
        else {
          change_match_count_by = StartWithCount(part, f);
        }
      }
      if (change_match_count_by > 0) {
        if (exclude) return false;
        *count += change_match_count_by;
      }
    }
  }
  return *count > 0;
}

struct FilterMatch {
  wxString path;
  int count;

  FilterMatch(const wxString& p, int c) : path(p), count(c) {}
  bool operator<(const FilterMatch& rhs) const {
    if (count == rhs.count) return path < rhs.path;
    else return count < rhs.count;
  }
};

void QuickOpenDlg::UpdateFilters() {
  const wxString filter = uiFilterName->GetValue();

  std::set<FilterMatch> matches;
  for (const wxString& file : files_) {
    int count = 0;
    if (MatchFilter(filter, file, &count)) {
      FilterMatch m(file, count);
      assert(matches.find(m) == matches.end());
      matches.insert(m);
    }
  }

  uiFileList->Freeze();
  uiFileList->DeleteAllItems();
  for (const FilterMatch& match: matches) {
    int i = uiFileList->InsertItem(0, "");
    uiFileList->SetItem(i, 0, wxFileName(match.path).GetFullName());
    uiFileList->SetItem(i, 1, match.path);
    uiFileList->SetItem(i, 2, wxString::Format("%d", match.count));
  }
  if (matches.empty() == false) {
    SetSelection(uiFileList, 0, true);
  }
  uiFileList->Thaw();
}

QuickOpenDlg::QuickOpenDlg(wxWindow* parent)
  : ui::QuickOpen(parent, wxID_ANY)
{
  const long file_index = uiFileList->InsertColumn(0, "File");
  const long path_index = uiFileList->InsertColumn(1, "Path");
  const long count_index = uiFileList->InsertColumn(2, "Hits");
  uiFileList->SetColumnWidth(file_index, 150);
  uiFileList->SetColumnWidth(path_index, 300);
  uiFileList->SetColumnWidth(count_index, 50);

  /*files_.push_back("/project/dog/src/BigCalendarCtrl.rs");
  files_.push_back("/project/dog/src/BigCalendarTask.rs");
  files_.push_back("/project/dog/src/CalendarButtonsDlg.rs");
  files_.push_back("/project/dog/src/CalendarData.rs");
  files_.push_back("/project/dog/src/CalendarDefines.rs");
  files_.push_back("/project/dog/src/CalendarExt.rs");
  files_.push_back("/project/dog/src/CalendarExt.rs");
  */

  files_.push_back("/project/dog/src/big-calendar-ctrl.rs");
  files_.push_back("/project/dog/src/big-calendar-task.rs");
  files_.push_back("/project/dog/src/calendar-buttons-dlg.rs");
  files_.push_back("/project/dog/src/calendar-data.rs");
  files_.push_back("/project/dog/src/calendar-defines.rs");
  files_.push_back("/project/dog/src/calendar-ext.rs");
  files_.push_back("/project/dog/assets/pixel-shader.glsl");
  files_.push_back("/project/dog/assets/fragment-shader.glsl");
  files_.push_back("/project/dog/assets/texture-enemy.png");

  files_.push_back("/project/dog/assets/texture-enemy.template.png");
  /*
  files_.push_back("/project/dog/src/big_calendar_ctrl.rs");
  files_.push_back("/project/dog/src/big_calendar_task.rs");
  files_.push_back("/project/dog/src/calendar_buttons_dlg.rs");
  files_.push_back("/project/dog/src/calendar_data.rs");
  files_.push_back("/project/dog/src/calendar_defines.rs");
  files_.push_back("/project/dog/src/calendar_ext.rs");
  files_.push_back("/project/dog/src/calendar_ext.rs");*/

  uiFileList->Bind(wxEVT_KEY_DOWN, &QuickOpenDlg::OnFilterKeyUp, this);
  UpdateFilters();
}

void QuickOpenDlg::OnActivate(wxActivateEvent& event) {
  uiFilterName->SelectAll();
  uiFilterName->SetFocus();
  uiFilterName->SetFocusFromKbd();
}

void QuickOpenDlg::OnFilterKeyUp(wxKeyEvent& event) {
  if (event.GetKeyCode() == wxUP) {
    auto selected = GetSelection(uiFileList);
    if (selected.empty()){
      SetSelection(uiFileList, 0, true);
    }
    else {
      long last = *selected.begin();
      if (event.ShiftDown() == false) ClearSelection(uiFileList);
      SetSelection(uiFileList, last - 1, true);
    }
  }
  else if (event.GetKeyCode() == wxDOWN) {
    auto selected = GetSelection(uiFileList);
    if (selected.empty()){
      SetSelection(uiFileList, 0, true);
    }
    else {
      long last = *selected.rbegin();
      if (event.ShiftDown() == false) ClearSelection(uiFileList);
      SetSelection(uiFileList, last + 1, true);
    }
  }
  else {
    event.Skip();
  }
}

void QuickOpenDlg::OnFilterNameEnter(wxCommandEvent& event) {
  EndModal(wxID_OK);
}

void QuickOpenDlg::OnFilterUpdated(wxCommandEvent& event) {
  UpdateFilters();
}

void QuickOpenDlg::OnCancel(wxCommandEvent& event) {
  EndModal(wxID_CANCEL);
}

void QuickOpenDlg::OnOk(wxCommandEvent& event) {
  EndModal(wxID_OK);
}

bool ShowQuickOpenDlg(wxWindow* parent) {
  QuickOpenDlg dlg(parent);
  if (wxID_OK != dlg.ShowModal()) return false;;
  // do something!
  return true;
}
<|endoftext|>


<commit_before>// Copyright Hugh Perkins 2016

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

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

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

#include "cocl/cocl_properties.h"

#include "cocl/hostside_opencl_funcs.h"

#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <set>

// #include "EasyCL.h"

#include "CL/cl.h"

using namespace std;
using namespace cocl;

size_t cuDeviceGetAttribute(
       int *value, int attribute, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceGetAttribute redirected" << endl);
    if(CU_DEVICE_ATTRIBUTE_ECC_ENABLED == attribute) {
        *value = 0;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR == attribute) {
        *value = 65536;
    } else if(CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK == attribute) {
        *value = 65536;
    } else if(CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT == attribute) {
        *value = 16;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK == attribute) {
        *value = 64;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR == attribute) {
        *value = 128;
    } else if(CU_DEVICE_ATTRIBUTE_WARP_SIZE == attribute) {
        *value = 32;
    } else {
        cout << "attribute " << attribute << endl;
        throw runtime_error("attribute not implemented");
    }
    return 0;
}

cudaSharedMemConfig cudaSharedMemBankSizeEightByte;

size_t cuDeviceGetName(char *buf, int bufsize, void *device) {
    COCL_PRINT(cout << "cuDeviceGetName redirected" << endl);
    sprintf(buf, "an opencl device");
    return 0;
}

size_t cuDeviceGetPCIBusId(char *buf, int bufsize, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceGetPCIBusId redirected" << endl);
    sprintf(buf, "0000.0000");
    return 0;
}

size_t cuDriverGetVersion(int *driver_version) {
    COCL_PRINT(cout << "cuDriverGetVersion redirected" << endl);
    *driver_version = 1;
    return 0;
}

size_t cuDeviceComputeCapability(int *cc_major, int *cc_minor, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceComputeCapability redirected" << endl);
    *cc_major = 3;
    *cc_minor = 5;
    return 0;
}

size_t cudaGetDeviceProperties (struct cudaDeviceProp *prop, CUdevice device) {
    COCL_PRINT(cout << "cudaGetDeviceProperties stub device=" << device << endl);
    prop->totalGlobalMem = 1024 * 1024 * 1024;
    prop->sharedMemPerBlock = 65536;
    prop->regsPerBlock = 64;
    prop->warpSize = 32;
    // prop->memPitch = 4; // whats this?
    prop->maxThreadsPerBlock = 128;
    prop->maxThreadsDim[0] = 1024;
    prop->maxThreadsDim[1] = 1024;
    prop->maxThreadsDim[2] = 1024;
    prop->totalConstMem = 16 * 1024;
    prop->major = 3;
    prop->minor = 0;
    prop->clockRate = 900 * 1000 * 1000;
    // prop->textureAlignment = 128;  // whats this?
    // prop->deviceOverlap = 0; // whats this?
    prop->multiProcessorCount = 3;
    prop->kernelExecTimeoutEnabled = true;
    prop->integrated = true;
    prop->canMapHostMemory = false;
    // prop->computeMode = 0;  //whats this?
    // prop->concurrentKernels = 1;
    // prop->ECCEnabled = false;
    // prop->pciBusID = 0;
    // prop->pciDeviceID = 0;
    // prop->tccDriver = 0; // no idea
    prop->maxThreadsPerMultiProcessor = 128;
    return 0;
}

size_t cuDeviceGetProperties(struct cudaDeviceProp *device_properties, CUdevice device_ordinal) {
    //return cudaGetDeviceProperties(device_properties, device_ordinal);
    return -1;
}

size_t cudaDeviceSetSharedMemConfig(cudaSharedMemConfig config) {
    // stub
    return 0;
}
<commit_msg>added shared memory per block stub<commit_after>// Copyright Hugh Perkins 2016

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

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

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

#include "cocl/cocl_properties.h"

#include "cocl/hostside_opencl_funcs.h"

#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <set>

// #include "EasyCL.h"

#include "CL/cl.h"

using namespace std;
using namespace cocl;

size_t cuDeviceGetAttribute(
       int *value, int attribute, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceGetAttribute redirected" << endl);
    if(CU_DEVICE_ATTRIBUTE_ECC_ENABLED == attribute) {
        *value = 0;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z == attribute) {
        *value = 1024;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR == attribute) {
        *value = 65536;
    } else if(CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK == attribute) {
        *value = 65536;
    } else if(CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT == attribute) {
        *value = 16;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK == attribute) {
        *value = 64;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR == attribute) {
        *value = 128;
    } else if(CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK == attribute) {
        return 40000;
    } else if(CU_DEVICE_ATTRIBUTE_WARP_SIZE == attribute) {
        *value = 32;
    } else {
        cout << "attribute " << attribute << endl;
        throw runtime_error("attribute not implemented");
    }
    return 0;
}

cudaSharedMemConfig cudaSharedMemBankSizeEightByte;

size_t cuDeviceGetName(char *buf, int bufsize, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceGetName redirected" << endl);
    sprintf(buf, "an opencl device");
    return 0;
}

size_t cuDeviceGetPCIBusId(char *buf, int bufsize, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceGetPCIBusId redirected" << endl);
    sprintf(buf, "0000.0000");
    return 0;
}

size_t cuDriverGetVersion(int *driver_version) {
    COCL_PRINT(cout << "cuDriverGetVersion redirected" << endl);
    *driver_version = 1;
    return 0;
}

size_t cuDeviceComputeCapability(int *cc_major, int *cc_minor, CUdevice device) {
    COCL_PRINT(cout << "cuDeviceComputeCapability redirected" << endl);
    *cc_major = 3;
    *cc_minor = 5;
    return 0;
}

size_t cudaGetDeviceProperties (struct cudaDeviceProp *prop, CUdevice device) {
    COCL_PRINT(cout << "cudaGetDeviceProperties stub device=" << device << endl);
    prop->totalGlobalMem = 1024 * 1024 * 1024;
    prop->sharedMemPerBlock = 65536;
    prop->regsPerBlock = 64;
    prop->warpSize = 32;
    // prop->memPitch = 4; // whats this?
    prop->maxThreadsPerBlock = 128;
    prop->maxThreadsDim[0] = 1024;
    prop->maxThreadsDim[1] = 1024;
    prop->maxThreadsDim[2] = 1024;
    prop->totalConstMem = 16 * 1024;
    prop->major = 3;
    prop->minor = 0;
    prop->clockRate = 900 * 1000 * 1000;
    // prop->textureAlignment = 128;  // whats this?
    // prop->deviceOverlap = 0; // whats this?
    prop->multiProcessorCount = 3;
    prop->kernelExecTimeoutEnabled = true;
    prop->integrated = true;
    prop->canMapHostMemory = false;
    // prop->computeMode = 0;  //whats this?
    // prop->concurrentKernels = 1;
    // prop->ECCEnabled = false;
    // prop->pciBusID = 0;
    // prop->pciDeviceID = 0;
    // prop->tccDriver = 0; // no idea
    prop->maxThreadsPerMultiProcessor = 128;
    return 0;
}

size_t cuDeviceGetProperties(struct cudaDeviceProp *device_properties, CUdevice device_ordinal) {
    return cudaGetDeviceProperties(device_properties, device_ordinal);
    // return -1;
}

size_t cudaDeviceSetSharedMemConfig(cudaSharedMemConfig config) {
    // stub
    return 0;
}
<|endoftext|>


<commit_before>#include "xchainer/array_repr.h"

#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA

#include "xchainer/array.h"
#include "xchainer/array_node.h"
#include "xchainer/backend.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/dtype.h"
#include "xchainer/shape.h"

namespace xchainer {

namespace {

int GetNDigits(int64_t value) {
    int digits = 0;
    while (value != 0) {
        value /= 10;
        ++digits;
    }
    return digits;
}

void PrintNTimes(std::ostream& os, char c, int n) {
    while (n-- > 0) {
        os << c;
    }
}

class IntFormatter {
public:
    void Scan(int64_t value) {
        int digits = 0;
        if (value < 0) {
            ++digits;
            value = -value;
        }
        digits += GetNDigits(value);
        if (max_digits_ < digits) {
            max_digits_ = digits;
        }
    }

    void Print(std::ostream& os, int64_t value) const { os << std::setw(max_digits_) << std::right << value; }

private:
    int max_digits_ = 1;
};

class FloatFormatter {
public:
    void Scan(double value) {
        int b_digits = 0;
        if (value < 0) {
            has_minus_ = true;
            ++b_digits;
            value = -value;
        }
        if (std::isinf(value) || std::isnan(value)) {
            b_digits += 3;
            if (digits_before_point_ < b_digits) {
                digits_before_point_ = b_digits;
            }
            return;
        }
        if (value >= 100'000'000) {
            int e_digits = GetNDigits(static_cast<int64_t>(std::log10(value)));
            if (digits_after_e_ < e_digits) {
                digits_after_e_ = e_digits;
            }
        }
        if (digits_after_e_ > 0) {
            return;
        }

        const auto int_frac_parts = IntFracPartsToPrint(value);

        b_digits += GetNDigits(int_frac_parts.first);
        if (digits_before_point_ < b_digits) {
            digits_before_point_ = b_digits;
        }

        const int a_digits = GetNDigits(int_frac_parts.second) - 1;
        if (digits_after_point_ < a_digits) {
            digits_after_point_ = a_digits;
        }
    }

    void Print(std::ostream& os, double value) {
        if (digits_after_e_ > 0) {
            int width = 12 + (has_minus_ ? 1 : 0) + digits_after_e_;
            if (has_minus_ && !std::signbit(value)) {
                os << ' ';
                --width;
            }
            os << std::scientific << std::left << std::setw(width) << std::setprecision(8) << value;
        } else {
            if (std::isinf(value) || std::isnan(value)) {
                os << std::right << std::setw(digits_before_point_ + digits_after_point_ + 1) << value;
                return;
            }
            const auto int_frac_parts = IntFracPartsToPrint(value);
            const int a_digits = GetNDigits(int_frac_parts.second) - 1;
            os << std::fixed << std::right << std::setw(digits_before_point_ + a_digits + 1) << std::setprecision(a_digits)
               << std::showpoint << value;
            PrintNTimes(os, ' ', digits_after_point_ - a_digits);
        }
    }

private:
    // Returns the integral part and fractional part as integers.
    // Note that the fractional part is prefixed by 1 so that the information of preceeding zeros is not missed.
    static std::pair<int64_t, int64_t> IntFracPartsToPrint(double value) {
        double int_part;
        const double frac_part = std::modf(value, &int_part);

        auto shifted_frac_part = static_cast<int64_t>((std::abs(frac_part) + 1) * 100'000'000);
        while ((shifted_frac_part % 10) == 0) {
            shifted_frac_part /= 10;
        }

        return {static_cast<int64_t>(int_part), shifted_frac_part};
    }

    int digits_before_point_ = 1;
    int digits_after_point_ = 0;
    int digits_after_e_ = 0;
    bool has_minus_ = false;
};

class BoolFormatter {
public:
    void Scan(bool value) { (void)value; /* unused */ }

    void Print(std::ostream& os, bool value) const {
        os << (value ? " True" : "False");  // NOLINTER
    }
};

template <typename T>
using Formatter = std::conditional_t<std::is_same<T, bool>::value, BoolFormatter,
                                     std::conditional_t<std::is_floating_point<T>::value, FloatFormatter, IntFormatter>>;

struct ArrayReprImpl {
    template <typename T, typename Visitor>
    void VisitElements(const Array& array, Visitor&& visitor) const {
        // TODO(niboshi): Contiguousness is assumed.
        // TODO(niboshi): Replace with Indxer class.
        auto shape = array.shape();
        std::vector<int64_t> indexer;
        std::copy(shape.cbegin(), shape.cend(), std::back_inserter(indexer));
        std::shared_ptr<const T> data = std::static_pointer_cast<const T>(array.data());

// TODO(hvy): Only synchronize device_ids when it is really needed
#ifdef XCHAINER_ENABLE_CUDA
        cuda::CheckError(cudaDeviceSynchronize());
#endif  // XCHAINER_ENABLE_CUDA

        for (int64_t i = 0; i < array.GetTotalSize(); ++i) {
            // Increment indexer
            for (int j = shape.ndim() - 1; j >= 0; --j) {
                indexer[j]++;
                if (indexer[j] >= shape[j]) {
                    indexer[j] = 0;
                } else {
                    break;
                }
            }

            visitor(data.get()[i], &indexer[0]);
        }
    }

    template <typename T>
    void operator()(const Array& array, std::ostream& os) const {
        Formatter<T> formatter;

        // Let formatter scan all elements to print.
        VisitElements<T>(array, [&formatter](T value, const int64_t* index) {
            (void)index;  // unused
            formatter.Scan(value);
        });

        // Print values using the formatter.
        const int8_t ndim = array.ndim();
        int cur_line_size = 0;
        VisitElements<T>(array, [ndim, &cur_line_size, &formatter, &os](T value, const int64_t* index) {
            int8_t trailing_zeros = 0;
            if (ndim > 0) {
                for (auto it = index + ndim; --it >= index;) {
                    if (*it == 0) {
                        ++trailing_zeros;
                    } else {
                        break;
                    }
                }
            }
            if (trailing_zeros == ndim) {
                // This is the first iteration, so print the header
                os << "array(";
                PrintNTimes(os, '[', ndim);
            } else if (trailing_zeros > 0) {
                PrintNTimes(os, ']', trailing_zeros);
                os << ',';
                PrintNTimes(os, '\n', trailing_zeros);
                PrintNTimes(os, ' ', 6 + ndim - trailing_zeros);
                PrintNTimes(os, '[', trailing_zeros);
                cur_line_size = 0;
            } else {
                if (cur_line_size == 10) {
                    os << ",\n";
                    PrintNTimes(os, ' ', 6 + ndim);
                    cur_line_size = 0;
                } else {
                    os << ", ";
                }
            }
            formatter.Print(os, value);
            ++cur_line_size;
        });

        // In case of an empty Array, print the header here
        if (array.GetTotalSize() == 0) {
            os << "array([";
        }

        // Print the footer
        PrintNTimes(os, ']', ndim);
        os << ", dtype=" << array.dtype();
        assert(!array.device_id().is_null());
        os << ", device_id=('" << array.device_id().backend()->GetName() << "', " << array.device_id().index() << ")";
        const std::vector<std::shared_ptr<ArrayNode>>& nodes = array.nodes();
        if (!nodes.empty()) {
            os << ", graph_ids=[";
            for (size_t i = 0; i < nodes.size(); ++i) {
                if (i > 0) {
                    os << ", ";
                }
                os << '\'' << nodes[i]->graph_id() << '\'';
            }
            os << ']';
        }
        os << ')';
    }
};

}  // namespace

std::ostream& operator<<(std::ostream& os, const Array& array) {
    // TODO(hvy): We need to determine the output specification of this function, whether or not to align with Python repr specification,
    // and also whether this functionality should be defined in C++ layer or Python layer.
    VisitDtype(array.dtype(), [&](auto pt) { ArrayReprImpl{}.operator()<typename decltype(pt)::type>(array, os); });
    return os;
}

std::string ArrayRepr(const Array& array) {
    std::ostringstream os;
    os << array;
    return os.str();
}

}  // namespace xchainer
<commit_msg>trivial: revert device_ids to devices of a comment<commit_after>#include "xchainer/array_repr.h"

#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA

#include "xchainer/array.h"
#include "xchainer/array_node.h"
#include "xchainer/backend.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/dtype.h"
#include "xchainer/shape.h"

namespace xchainer {

namespace {

int GetNDigits(int64_t value) {
    int digits = 0;
    while (value != 0) {
        value /= 10;
        ++digits;
    }
    return digits;
}

void PrintNTimes(std::ostream& os, char c, int n) {
    while (n-- > 0) {
        os << c;
    }
}

class IntFormatter {
public:
    void Scan(int64_t value) {
        int digits = 0;
        if (value < 0) {
            ++digits;
            value = -value;
        }
        digits += GetNDigits(value);
        if (max_digits_ < digits) {
            max_digits_ = digits;
        }
    }

    void Print(std::ostream& os, int64_t value) const { os << std::setw(max_digits_) << std::right << value; }

private:
    int max_digits_ = 1;
};

class FloatFormatter {
public:
    void Scan(double value) {
        int b_digits = 0;
        if (value < 0) {
            has_minus_ = true;
            ++b_digits;
            value = -value;
        }
        if (std::isinf(value) || std::isnan(value)) {
            b_digits += 3;
            if (digits_before_point_ < b_digits) {
                digits_before_point_ = b_digits;
            }
            return;
        }
        if (value >= 100'000'000) {
            int e_digits = GetNDigits(static_cast<int64_t>(std::log10(value)));
            if (digits_after_e_ < e_digits) {
                digits_after_e_ = e_digits;
            }
        }
        if (digits_after_e_ > 0) {
            return;
        }

        const auto int_frac_parts = IntFracPartsToPrint(value);

        b_digits += GetNDigits(int_frac_parts.first);
        if (digits_before_point_ < b_digits) {
            digits_before_point_ = b_digits;
        }

        const int a_digits = GetNDigits(int_frac_parts.second) - 1;
        if (digits_after_point_ < a_digits) {
            digits_after_point_ = a_digits;
        }
    }

    void Print(std::ostream& os, double value) {
        if (digits_after_e_ > 0) {
            int width = 12 + (has_minus_ ? 1 : 0) + digits_after_e_;
            if (has_minus_ && !std::signbit(value)) {
                os << ' ';
                --width;
            }
            os << std::scientific << std::left << std::setw(width) << std::setprecision(8) << value;
        } else {
            if (std::isinf(value) || std::isnan(value)) {
                os << std::right << std::setw(digits_before_point_ + digits_after_point_ + 1) << value;
                return;
            }
            const auto int_frac_parts = IntFracPartsToPrint(value);
            const int a_digits = GetNDigits(int_frac_parts.second) - 1;
            os << std::fixed << std::right << std::setw(digits_before_point_ + a_digits + 1) << std::setprecision(a_digits)
               << std::showpoint << value;
            PrintNTimes(os, ' ', digits_after_point_ - a_digits);
        }
    }

private:
    // Returns the integral part and fractional part as integers.
    // Note that the fractional part is prefixed by 1 so that the information of preceeding zeros is not missed.
    static std::pair<int64_t, int64_t> IntFracPartsToPrint(double value) {
        double int_part;
        const double frac_part = std::modf(value, &int_part);

        auto shifted_frac_part = static_cast<int64_t>((std::abs(frac_part) + 1) * 100'000'000);
        while ((shifted_frac_part % 10) == 0) {
            shifted_frac_part /= 10;
        }

        return {static_cast<int64_t>(int_part), shifted_frac_part};
    }

    int digits_before_point_ = 1;
    int digits_after_point_ = 0;
    int digits_after_e_ = 0;
    bool has_minus_ = false;
};

class BoolFormatter {
public:
    void Scan(bool value) { (void)value; /* unused */ }

    void Print(std::ostream& os, bool value) const {
        os << (value ? " True" : "False");  // NOLINTER
    }
};

template <typename T>
using Formatter = std::conditional_t<std::is_same<T, bool>::value, BoolFormatter,
                                     std::conditional_t<std::is_floating_point<T>::value, FloatFormatter, IntFormatter>>;

struct ArrayReprImpl {
    template <typename T, typename Visitor>
    void VisitElements(const Array& array, Visitor&& visitor) const {
        // TODO(niboshi): Contiguousness is assumed.
        // TODO(niboshi): Replace with Indxer class.
        auto shape = array.shape();
        std::vector<int64_t> indexer;
        std::copy(shape.cbegin(), shape.cend(), std::back_inserter(indexer));
        std::shared_ptr<const T> data = std::static_pointer_cast<const T>(array.data());

// TODO(hvy): Only synchronize devices when it is really needed
#ifdef XCHAINER_ENABLE_CUDA
        cuda::CheckError(cudaDeviceSynchronize());
#endif  // XCHAINER_ENABLE_CUDA

        for (int64_t i = 0; i < array.GetTotalSize(); ++i) {
            // Increment indexer
            for (int j = shape.ndim() - 1; j >= 0; --j) {
                indexer[j]++;
                if (indexer[j] >= shape[j]) {
                    indexer[j] = 0;
                } else {
                    break;
                }
            }

            visitor(data.get()[i], &indexer[0]);
        }
    }

    template <typename T>
    void operator()(const Array& array, std::ostream& os) const {
        Formatter<T> formatter;

        // Let formatter scan all elements to print.
        VisitElements<T>(array, [&formatter](T value, const int64_t* index) {
            (void)index;  // unused
            formatter.Scan(value);
        });

        // Print values using the formatter.
        const int8_t ndim = array.ndim();
        int cur_line_size = 0;
        VisitElements<T>(array, [ndim, &cur_line_size, &formatter, &os](T value, const int64_t* index) {
            int8_t trailing_zeros = 0;
            if (ndim > 0) {
                for (auto it = index + ndim; --it >= index;) {
                    if (*it == 0) {
                        ++trailing_zeros;
                    } else {
                        break;
                    }
                }
            }
            if (trailing_zeros == ndim) {
                // This is the first iteration, so print the header
                os << "array(";
                PrintNTimes(os, '[', ndim);
            } else if (trailing_zeros > 0) {
                PrintNTimes(os, ']', trailing_zeros);
                os << ',';
                PrintNTimes(os, '\n', trailing_zeros);
                PrintNTimes(os, ' ', 6 + ndim - trailing_zeros);
                PrintNTimes(os, '[', trailing_zeros);
                cur_line_size = 0;
            } else {
                if (cur_line_size == 10) {
                    os << ",\n";
                    PrintNTimes(os, ' ', 6 + ndim);
                    cur_line_size = 0;
                } else {
                    os << ", ";
                }
            }
            formatter.Print(os, value);
            ++cur_line_size;
        });

        // In case of an empty Array, print the header here
        if (array.GetTotalSize() == 0) {
            os << "array([";
        }

        // Print the footer
        PrintNTimes(os, ']', ndim);
        os << ", dtype=" << array.dtype();
        assert(!array.device_id().is_null());
        os << ", device_id=('" << array.device_id().backend()->GetName() << "', " << array.device_id().index() << ")";
        const std::vector<std::shared_ptr<ArrayNode>>& nodes = array.nodes();
        if (!nodes.empty()) {
            os << ", graph_ids=[";
            for (size_t i = 0; i < nodes.size(); ++i) {
                if (i > 0) {
                    os << ", ";
                }
                os << '\'' << nodes[i]->graph_id() << '\'';
            }
            os << ']';
        }
        os << ')';
    }
};

}  // namespace

std::ostream& operator<<(std::ostream& os, const Array& array) {
    // TODO(hvy): We need to determine the output specification of this function, whether or not to align with Python repr specification,
    // and also whether this functionality should be defined in C++ layer or Python layer.
    VisitDtype(array.dtype(), [&](auto pt) { ArrayReprImpl{}.operator()<typename decltype(pt)::type>(array, os); });
    return os;
}

std::string ArrayRepr(const Array& array) {
    std::ostringstream os;
    os << array;
    return os.str();
}

}  // namespace xchainer
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Keith Mendoza Sr
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <WiFi.h>

#include <Adafruit_MotorShield.h>

//Hard-lined address 1
Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

//Left wheel
Adafruit_DCMotor *leftMotor = AFMS.getMotor(1);

//Right wheel
Adafruit_DCMotor *rightMotor = AFMS.getMotor(4);

void connect()
{
    static const char ssid[] = "<ENTER SSID>";
    static const char pass[] = "<ENTER PASS>";

    Serial.println("Connecting");
    pinMode(9, OUTPUT);
    digitalWrite(9, HIGH);
    uint8_t status = WiFi.begin((char *)ssid, (char *)pass);
    while(status != WL_CONNECTED)
    {
        delay(10000);
        status = WiFi.begin((char *)ssid, (char *)pass);
    }
    digitalWrite(9, LOW);
    Serial.println("Connected");
}

void setup() {
    Serial.begin(9600);

    connect();
    AFMS.begin();  // create with the default frequency 1.6KHz

    // Set the speed to start, from 0 (off) to 255 (max speed)
    leftMotor->setSpeed(100);
    rightMotor->setSpeed(100);

    rightMotor->run(FORWARD);
    leftMotor->run(FORWARD);
    delay(125);

    rightMotor->run(BACKWARD);
    leftMotor->run(BACKWARD);
    delay(125);

    rightMotor->run(RELEASE);
    leftMotor->run(RELEASE);
}

int main()
{
    init();
    setup();

    WiFiServer server(80);
    server.begin();
    bool isUp = false;
    while(1)
    {
        digitalWrite(9, isUp ? HIGH : LOW);
        WiFiClient client = server.available();
        if(client)
        {
            Serial.println("Got client");
            uint8_t dir = RELEASE;
            while(client.connected())
            {
                if(client.available())
                {
                    char c = client.read();
                    Serial.print("Got data: ");
                    Serial.println(c);
                    switch(c)
                    {
                    case 'i':
                        dir = FORWARD;
                        leftMotor->run(dir);
                        rightMotor->run(dir);
                        break;
                    case 'j':
                        leftMotor->run(RELEASE);
                        rightMotor->run(dir != RELEASE ? dir : FORWARD);
                        break;
                    case 'k':
                        leftMotor->run(dir != RELEASE ? dir : FORWARD);
                        rightMotor->run(RELEASE);
                        break;
                    case 'm':
                        dir = BACKWARD;
                        leftMotor->run(dir);
                        rightMotor->run(dir);
                        break;
                    case 's':
                        leftMotor->run(RELEASE);
                        rightMotor->run(RELEASE);
                        break;
                    }
                }
            }

            Serial.println("Lost client");
            client.stop();
            leftMotor->run(RELEASE);
            rightMotor->run(RELEASE);
        }
    }
}
<commit_msg>Added speed control<commit_after>/*
 * Copyright 2014-2015 Keith Mendoza Sr
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <WiFi.h>

#include <Adafruit_MotorShield.h>

//Hard-lined address 1
Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

//Left wheel
Adafruit_DCMotor *leftMotor = AFMS.getMotor(1);

//Right wheel
Adafruit_DCMotor *rightMotor = AFMS.getMotor(4);

void connect()
{
    static const char ssid[] = "<ENTER SSID>";
    static const char pass[] = "<ENTER PASS>";

    Serial.println("Connecting");
    pinMode(9, OUTPUT);
    digitalWrite(9, HIGH);
    uint8_t status = WiFi.begin((char *)ssid, (char *)pass);
    while(status != WL_CONNECTED)
    {
        delay(10000);
        status = WiFi.begin((char *)ssid, (char *)pass);
    }
    digitalWrite(9, LOW);
    Serial.println("Connected");
}

void setup() {
    Serial.begin(9600);

    connect();
    AFMS.begin();  // create with the default frequency 1.6KHz

    // Set the speed to start, from 0 (off) to 255 (max speed)
    leftMotor->setSpeed(100);
    rightMotor->setSpeed(100);

    rightMotor->run(FORWARD);
    leftMotor->run(FORWARD);
    delay(125);

    rightMotor->run(BACKWARD);
    leftMotor->run(BACKWARD);
    delay(125);

    rightMotor->run(RELEASE);
    leftMotor->run(RELEASE);
}

int main()
{
    init();
    setup();

    WiFiServer server(80);
    server.begin();
    while(1)
    {
        WiFiClient client = server.available();
        if(client)
        {
            Serial.println("Got client");
            uint8_t dir = RELEASE;
            uint8_t speed = 100;
            leftMotor->setSpeed(speed);
            rightMotor->setSpeed(speed);

            while(client.connected())
            {
                if(client.available())
                {
                    char c = client.read();
                    Serial.print("Got data: ");
                    Serial.println(c);
                    switch(c)
                    {
                    case 'i':
                        dir = FORWARD;
                        leftMotor->run(dir);
                        rightMotor->run(dir);
                        break;
                    case 'j':
                        leftMotor->run(RELEASE);
                        rightMotor->run(dir != RELEASE ? dir : FORWARD);
                        break;
                    case 'k':
                        leftMotor->run(dir != RELEASE ? dir : FORWARD);
                        rightMotor->run(RELEASE);
                        break;
                    case 'm':
                        dir = BACKWARD;
                        leftMotor->run(dir);
                        rightMotor->run(dir);
                        break;
                    case 's':
                        leftMotor->run(RELEASE);
                        rightMotor->run(RELEASE);
                        speed=100;
                        dir = RELEASE;
                        break;
                    case 'u':
                        if(speed<150 && dir != RELEASE)
                        {
                            speed+=10;
                            leftMotor->setSpeed(speed);
                            rightMotor->setSpeed(speed);
                        }
                        break;
                    case 'd':
                        if(speed > 100 && dir != RELEASE)
                        {
                            speed-=10;
                            leftMotor->setSpeed(speed);
                            rightMotor->setSpeed(speed);
                        }
                        break;
                    }
                }
            }

            Serial.println("Lost client");
            client.stop();
            leftMotor->run(RELEASE);
            rightMotor->run(RELEASE);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Puck Meerburg, puck@puckipedia.nl
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "BlogPositiveMainView.h"

#include <Catalog.h>
#include <GroupLayoutBuilder.h>
#include <List.h>
#include <ListView.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <Point.h>
#include <PopUpMenu.h>
#include <Rect.h>
#include <ScrollView.h>
#include <String.h>
#include <TextView.h>

#include "../API/BlogPositiveBlog.h"
#include "../API/BlogPositivePlugin.h"
#include "../API/BlogPositivePluginLoader.h"
#include "BlogPositiveBlogListItem.h"
#include "../BlogPositiveDelegate.h"
#include "../BlogPositivePostList/BlogPositivePostListWindow.h"
#include "../BlogPositiveSettings.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Main View"

const int32 kBlogSelected = 'BPBS';
const int32 kCreateNewBlog = 'BPCB';
const int32 kRemoveCurrentBlog = 'BPRC';

class BlogPositiveBlogListView : public BListView {
public:
				BlogPositiveBlogListView();
	void		Reload(BlogList* BlogItemList);
};

BlogPositiveBlogListView::BlogPositiveBlogListView()
	:
	BListView("BlogPositiveBlogListView", B_SINGLE_SELECTION_LIST)
{
}

void
BlogPositiveBlogListView::Reload(BlogList* blogItemList)
{
	for (int i = 0; i < blogItemList->CountItems(); i++)
		AddItem(new BlogPositiveBlogListItem(blogItemList->ItemAt(i)));
}

void
BlogPositiveMainView::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case kRemoveCurrentBlog:
			RemoveBlog();
			break;
		case kBlogSelected:
		{
			if (fListView->CurrentSelection() == -1)
				break;
			BlogPositiveBlog* aBlog
				= ((BlogPositiveBlogListItem*)fListView->ItemAt(
						fListView->CurrentSelection()))->Blog();
			BlogPositivePluginLoader::FindPlugin(aBlog);
			fDelegate->OpenPostList(aBlog);
			break;
		}
		case kCreateNewBlog:
		{
			int32 index = message->GetInt32("ding", 0);
			PluginList* pluginList = BlogPositivePluginLoader::List();
			BlogPositivePlugin* plugin = pluginList->ItemAt(index);
			plugin->OpenNewBlogWindow(this);
			break;
		}
		default:
			BView::MessageReceived(message);
			break;
	}
}

void
BlogPositiveMainView::RemoveBlog()
{
	int32 sel = fListView->CurrentSelection();
	if (sel == -1)
		return;
	BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");
	BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
	BlogPositiveBlogListItem* listItem
		= static_cast<BlogPositiveBlogListItem*>(fListView->ItemAt(sel));
	BlogPositiveBlog* blog = listItem->Blog();
	for (int i = 0; i < lis->CountItems(); i++) {
		if (strcmp(blog->Name(), lis->ItemAt(i)->Name()) == 0) {
			lis->RemoveItemAt(i);
			break;
		}
	}
	BlogPositiveSettings::SaveOther(BlogPositiveBlog::SerializeList(lis,
		"blogs"), "bloglist");

	Reload(lis);
}

void
BlogPositiveMainView::Reload(BlogList* lis)
{
	fListView->MakeEmpty();
	fListView->Reload(lis);
}

void
BlogPositiveMainView::AttachedToWindow()
{
	fListView->SetTarget(this);
	for (int i = 0; i < fNewMenu->CountItems(); i++) {
		fNewMenu->ItemAt(i)->SetTarget(this);
	}
	fRemoveMenuItem->SetTarget(this);
}

BlogPositiveMainView::BlogPositiveMainView(const char* name,
	BlogPositiveDelegate* del)
	:
	BView(name, 0)
{
	fDelegate = del;

	fListView = new BlogPositiveBlogListView();
	fListView->SetInvocationMessage(new BMessage(kBlogSelected));

	fMenuBar = new BMenuBar("MenuBar");

	fNewMenu = new BMenu(B_TRANSLATE("Add Blog"));
	fMenuBar->AddItem(fNewMenu);

	PluginList* pluginList = BlogPositivePluginLoader::List();
	BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");

	BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
	fListView->Reload(lis);

	for (int i = 0; i < pluginList->CountItems(); i++) {
		BlogPositivePlugin* pl = (BlogPositivePlugin* )pluginList->ItemAt(i);
		if (pl->Type() == kBlogPositiveBlogApi) {
			BMessage* msg = new BMessage(kCreateNewBlog);
			msg->SetInt32("ding", i);
			msg->SetString("sendToView", Name());
			BMenuItem* mi = new BMenuItem(pl->Name(), msg);
			fNewMenu->AddItem(mi);
		}
	}

	BMessage* aMenuItemMessage = new BMessage(kRemoveCurrentBlog);
	fRemoveMenuItem = new BMenuItem(B_TRANSLATE("Remove blog"), aMenuItemMessage);
	fMenuBar->AddItem(fRemoveMenuItem);

	SetLayout(new BGroupLayout(B_VERTICAL, 0));
	AddChild(fMenuBar);
	AddChild(new BScrollView("scroll_view", fListView, 0, false, true));
}
<commit_msg>Remove old style casts<commit_after>/*
 * Copyright 2013 Puck Meerburg, puck@puckipedia.nl
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "BlogPositiveMainView.h"

#include <Catalog.h>
#include <GroupLayoutBuilder.h>
#include <List.h>
#include <ListView.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <Point.h>
#include <PopUpMenu.h>
#include <Rect.h>
#include <ScrollView.h>
#include <String.h>
#include <TextView.h>

#include "../API/BlogPositiveBlog.h"
#include "../API/BlogPositivePlugin.h"
#include "../API/BlogPositivePluginLoader.h"
#include "BlogPositiveBlogListItem.h"
#include "../BlogPositiveDelegate.h"
#include "../BlogPositivePostList/BlogPositivePostListWindow.h"
#include "../BlogPositiveSettings.h"

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Main View"

const int32 kBlogSelected = 'BPBS';
const int32 kCreateNewBlog = 'BPCB';
const int32 kRemoveCurrentBlog = 'BPRC';

class BlogPositiveBlogListView : public BListView {
public:
				BlogPositiveBlogListView();
	void		Reload(BlogList* BlogItemList);
};

BlogPositiveBlogListView::BlogPositiveBlogListView()
	:
	BListView("BlogPositiveBlogListView", B_SINGLE_SELECTION_LIST)
{
}

void
BlogPositiveBlogListView::Reload(BlogList* blogItemList)
{
	for (int i = 0; i < blogItemList->CountItems(); i++)
		AddItem(new BlogPositiveBlogListItem(blogItemList->ItemAt(i)));
}

void
BlogPositiveMainView::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case kRemoveCurrentBlog:
			RemoveBlog();
			break;
		case kBlogSelected:
		{
			int32 current = fListView->CurrentSelection();
			if (current == -1)
				break;
			BlogPositiveBlogListItem* blit =
				static_cast<BlogPositiveBlogListItem*>(fListView->ItemAt(current));
			BlogPositiveBlog* blog = blit->Blog();
			BlogPositivePluginLoader::FindPlugin(blog);
			fDelegate->OpenPostList(blog);
			break;
		}
		case kCreateNewBlog:
		{
			int32 index = message->GetInt32("ding", 0);
			PluginList* pluginList = BlogPositivePluginLoader::List();
			BlogPositivePlugin* plugin = pluginList->ItemAt(index);
			plugin->OpenNewBlogWindow(this);
			break;
		}
		default:
			BView::MessageReceived(message);
			break;
	}
}

void
BlogPositiveMainView::RemoveBlog()
{
	int32 sel = fListView->CurrentSelection();
	if (sel == -1)
		return;
	BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");
	BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
	BlogPositiveBlogListItem* listItem
		= static_cast<BlogPositiveBlogListItem*>(fListView->ItemAt(sel));
	BlogPositiveBlog* blog = listItem->Blog();
	for (int i = 0; i < lis->CountItems(); i++) {
		if (strcmp(blog->Name(), lis->ItemAt(i)->Name()) == 0) {
			lis->RemoveItemAt(i);
			break;
		}
	}
	BlogPositiveSettings::SaveOther(BlogPositiveBlog::SerializeList(lis,
		"blogs"), "bloglist");

	Reload(lis);
}

void
BlogPositiveMainView::Reload(BlogList* lis)
{
	fListView->MakeEmpty();
	fListView->Reload(lis);
}

void
BlogPositiveMainView::AttachedToWindow()
{
	fListView->SetTarget(this);
	for (int i = 0; i < fNewMenu->CountItems(); i++) {
		fNewMenu->ItemAt(i)->SetTarget(this);
	}
	fRemoveMenuItem->SetTarget(this);
}

BlogPositiveMainView::BlogPositiveMainView(const char* name,
	BlogPositiveDelegate* del)
	:
	BView(name, 0)
{
	fDelegate = del;

	fListView = new BlogPositiveBlogListView();
	fListView->SetInvocationMessage(new BMessage(kBlogSelected));

	fMenuBar = new BMenuBar("MenuBar");

	fNewMenu = new BMenu(B_TRANSLATE("Add Blog"));
	fMenuBar->AddItem(fNewMenu);

	PluginList* pluginList = BlogPositivePluginLoader::List();
	BlogPositiveSettings* settings = new BlogPositiveSettings("bloglist");

	BlogList* lis = BlogPositiveBlog::DeserializeList(settings, "blogs");
	fListView->Reload(lis);

	for (int i = 0; i < pluginList->CountItems(); i++) {
		BlogPositivePlugin* pl = (BlogPositivePlugin* )pluginList->ItemAt(i);
		if (pl->Type() == kBlogPositiveBlogApi) {
			BMessage* msg = new BMessage(kCreateNewBlog);
			msg->SetInt32("ding", i);
			msg->SetString("sendToView", Name());
			BMenuItem* mi = new BMenuItem(pl->Name(), msg);
			fNewMenu->AddItem(mi);
		}
	}

	BMessage* aMenuItemMessage = new BMessage(kRemoveCurrentBlog);
	fRemoveMenuItem = new BMenuItem(B_TRANSLATE("Remove blog"), aMenuItemMessage);
	fMenuBar->AddItem(fRemoveMenuItem);

	SetLayout(new BGroupLayout(B_VERTICAL, 0));
	AddChild(fMenuBar);
	AddChild(new BScrollView("scroll_view", fListView, 0, false, true));
}
<|endoftext|>


<commit_before>/* ===============================================================================
 * Generation of an .fld file for the Blasius boundary layer.
 * Requirements:
 *                a) Session file with the mesh in the physical space and some
 *                   data to define the BL properly
 *
 *                b) Blasius similarity solution consistent with the dimensions
 *                   of the mesh file (in the physical space)
=============================================================================== */

/* =====================================
 * Author: Gianmarco Mengaldo
 * Generation: dd/mm/aa = 08/03/12
===================================== */

//! Loading cc libraries
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string.h>
#include <sstream>
#include <iomanip>

//! Loading Nektar++ libraries
#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <MultiRegions/ExpList.h>
#include <MultiRegions/ExpList0D.h>
#include <MultiRegions/ExpList1D.h>
#include <MultiRegions/ExpList2D.h>
#include <MultiRegions/ExpList3D.h>
#include <MultiRegions/ExpList2DHomogeneous1D.h>
#include <MultiRegions/ExpList3DHomogeneous1D.h>
#include <MultiRegions/ExpList1DHomogeneous2D.h>
#include <MultiRegions/ExpList3DHomogeneous2D.h>
#include <MultiRegions/ContField1D.h>
#include <MultiRegions/ContField2D.h>

//! Nektar++ namespace
using namespace Nektar;

//! Main
int main(int argc, char *argv[])
{
    //! Setting up the decimal precision to machine precision
    setprecision (16);

    //! Auxiliary counters for the x and y directions
    int  i, j, k, m, yLevel, xElement;
    NekDouble tmp;

    //! Auxiliary variables
    char    LocalString[1000];
    string  GlobalString[10000];
    bool    inspection = 1;

    //! Check for the command line
    if(argc != 3)
    {
        fprintf(stderr,"Usage: FldAddBlasius  meshfile fieldfile\n");
        exit(1);
    }

    std::cout<<"============================================================\n";
    std::cout<<"PROGRAM TO COMPUTE THE BLASIUS AND THE FALKNER-SKAN BLs     \n";
    std::cout<<"============================================================\n";
    std::cout<<"LIMITATIONS:\n";
    std::cout<<"1) The mesh must have a block in which is contained\n";
    std::cout<<"the entire boundary layer and part of the farfield.\n";
    std::cout<<"2) The data file must be well resolved within the BL.\n";
    std::cout<<"3) At the moment I am not reading the nummodes from \n";
    std::cout<<"the session file\n";
    std::cout<<"4) You need to manually specify the number of elements\n";
    std::cout<<"within the block of the BL.\n";
    std::cout<<"------------------------------------------------------------\n";

    //! Reading the session file
    LibUtilities::SessionReaderSharedPtr vSession = LibUtilities::SessionReader::CreateInstance(argc, argv);

    //! Loading the parameters to define the BL
    NekDouble Re;
    NekDouble L;
    NekDouble U_inf;
    NekDouble x;
    NekDouble nu;
    NekDouble C;
    int nElements_yBL;

    vSession->LoadParameter("Re",               Re,             1.0);
    vSession->LoadParameter("L",                L,              1.0);
    vSession->LoadParameter("U_inf",            U_inf,          1.0);
    vSession->LoadParameter("x",                x,              1.0);
    vSession->LoadParameter("BL_mesh_layers",   nElements_yBL,   1.0);

    std::cout<<"************************************************************\n";
    std::cout<<"PHYSICAL DATA FROM THE SESSION FILE:\n";
    std::cout << "Reynolds number                               = " << Re            << std::endl;
    std::cout << "Characteristic length [m]                     = " << L             << std::endl;
    std::cout << "U_infinity [m/s]                              = " << U_inf         << std::endl;
    std::cout << "Position x (parallel case only) [m]           = " << x             << std::endl;
    std::cout << "Number of mesh layers within the BL block [m] = " << nElements_yBL << std::endl;
    std::cout<<"************************************************************\n";
    std::cout<<"------------------------------------------------------------\n";
    std::cout<<"MESH and EXPANSION DATA:\n";

    /*  Read in mesh from input file and create an object of class
     *  MeshGraph1D to encaplusate the mesh
     */
    SpatialDomains::MeshGraphSharedPtr graphShPt;
    graphShPt = MemoryManager<SpatialDomains::MeshGraph2D>::AllocateSharedPtr(vSession);

    /*  Feed our spatial discretisation object with the information
     *  coming from the session file i.e. initialise all the memory
     */
    MultiRegions::ContField2DSharedPtr Domain;
    Domain = MemoryManager<MultiRegions::ContField2D>::AllocateSharedPtr(vSession,graphShPt,vSession->GetVariable(0));

    //! Get the total number of elements
    int nElements;
    nElements = Domain->GetExpSize();
    std::cout << "Number of elements           = " << nElements << std::endl;

    /*  Get the total number of quadrature points (depends on n. modes)
     *  For nodal expansion the number of physical points is equal
     *  to the number of coefficients
     */
    int nQuadraturePts;
    nQuadraturePts = Domain->GetTotPoints();
    std::cout << "Number of quadrature points  = " << nQuadraturePts << std::endl;

    /*  Create 3 arrays "x_QuadraturePts", "y_QuadraturePts", "z_QuadraturePts"
     *  to hold the coordinates values and fill it up with the the function GetCoords
     */
    Array<OneD,NekDouble> x_QuadraturePts;
    Array<OneD,NekDouble> y_QuadraturePts;
    Array<OneD,NekDouble> z_QuadraturePts;
    x_QuadraturePts = Array<OneD,NekDouble>(nQuadraturePts);
    y_QuadraturePts = Array<OneD,NekDouble>(nQuadraturePts);
    z_QuadraturePts = Array<OneD,NekDouble>(nQuadraturePts);
    Domain->GetCoords(x_QuadraturePts,y_QuadraturePts,z_QuadraturePts);

    //! Checking how the quadrature points are ordered
    FILE *qdpoints_data;
    qdpoints_data = fopen("qdpoints_data.txt","w+");
    for(j=0; j<=nQuadraturePts-1;j++)
    {
        fprintf(qdpoints_data,"%f %f %f\n", x_QuadraturePts[j], y_QuadraturePts[j], z_QuadraturePts[j]);
    }
    fclose(qdpoints_data);

    //! Interface points
    int nInterfacePts;
    nInterfacePts = graphShPt->GetNvertices();

    //! Coordinates of the interface points
    Array<OneD,NekDouble> x_InterfacePts;
    Array<OneD,NekDouble> y_InterfacePts;
    Array<OneD,NekDouble> z_InterfacePts;
    x_InterfacePts = Array<OneD,NekDouble>(nInterfacePts);
    y_InterfacePts = Array<OneD,NekDouble>(nInterfacePts);
    z_InterfacePts = Array<OneD,NekDouble>(nInterfacePts);

    for (int i = 0; i < nInterfacePts; i++)
    {
        graphShPt->GetVertex(i)->GetCoords(x_InterfacePts[i],y_InterfacePts[i],z_InterfacePts[i]);
    }

    /* ----------------------------------------------------------------------------------------
     * Getting the number of quadrature points and the coordinates along x and y directions
     * !!! NOTE: Valid only for structured meshes !!!
     --------------------------------------------------------------------------------------- */

    //! Number of quadrature points along x
    int nQuadraturePts_x = 0;
    for (i = 0; i < nQuadraturePts; i++)
    {
        if(y_QuadraturePts[i] == 0)
        {
            nQuadraturePts_x++;
        }
    }
    std::cout<< "Quadrature Points along x    = "<< nQuadraturePts_x <<std::endl;

    //! Coordinates of the quadrature points along x (NOTE: Valid only for structured meshes)
    Array<OneD,NekDouble> x_QuadraturePts_x(nQuadraturePts_x);
    Array<OneD,NekDouble> y_QuadraturePts_x(nQuadraturePts_x);
    Array<OneD,NekDouble> z_QuadraturePts_x(nQuadraturePts_x);
    j = 0;
    for (i = 0; i < nQuadraturePts; i++)
    {
        if(y_QuadraturePts[i] == 0)
        {
            x_QuadraturePts_x[j] = x_QuadraturePts[i];
            y_QuadraturePts_x[j] = y_QuadraturePts[i];
            z_QuadraturePts_x[j] = z_QuadraturePts[i];
            j++;
        }
    }

    //! Number of quadrature points along y
    int nQuadraturePts_y = 0;
    for (i = 0; i < nQuadraturePts; i++)
    {
        if(x_QuadraturePts[i] == 0)
        {
            nQuadraturePts_y++;
        }
    }
    std::cout<< "Quadrature Points along y    = "<< nQuadraturePts_y <<std::endl;

    //! Coordinates of the quadrature points along y (NOTE: Valid only for structured meshes)
    Array<OneD,NekDouble> x_QuadraturePts_y(nQuadraturePts_y);
    Array<OneD,NekDouble> y_QuadraturePts_y(nQuadraturePts_y);
    Array<OneD,NekDouble> z_QuadraturePts_y(nQuadraturePts_y);
    j = 0;
    for (i = 0; i < nQuadraturePts; i++)
    {
        if(x_QuadraturePts[i] == 0)
        {
            x_QuadraturePts_y[j] = x_QuadraturePts[i];
            y_QuadraturePts_y[j] = y_QuadraturePts[i];
            z_QuadraturePts_y[j] = z_QuadraturePts[i];
            j++;
        }
    }
    /* ----------------------------------------------------------------------------------------
     * ------------------------------------------------------------------------------------- */

    /*  Reading the .txt file with the similarity variable eta, and the similarity solutions:
     *  f(eta) and f'(eta)
     */
    const char *txtfile_char;
    string txtfile(argv[argc-1]);
    txtfile_char = txtfile.c_str();

    ifstream pFile(txtfile_char);
    int numLines = 120;
    NekDouble d;
    NekDouble GlobalArray[numLines][3];

    for (j = 0; j <= 2; j++)
    {
        for (i=0; i<=numLines-1; i++)
        {
            pFile >> d;
            GlobalArray[i][j] = d;
        }
    }

    //! Definition of the arrays for BL computations
    Array<OneD,NekDouble> eta;
    Array<OneD,NekDouble> f;
    Array<OneD,NekDouble> df;

    Array<OneD,NekDouble> y;
    Array<OneD,NekDouble> u;
    Array<OneD,NekDouble> v;

    eta = Array<OneD,NekDouble>(numLines);
    f   = Array<OneD,NekDouble>(numLines);
    df  = Array<OneD,NekDouble>(numLines);

    y = Array<OneD,NekDouble>(numLines);
    u = Array<OneD,NekDouble>(numLines);
    v = Array<OneD,NekDouble>(numLines);

    nu = U_inf*L/Re;
    C = sqrt(2*nu*x/U_inf);

    /*  Saving eta, f and df in separate arrays and computing the physical variables using
     *  BL data provided by the session file
     */
    for (i=0; i<=numLines-1; i++)
    {
        eta[i] = GlobalArray[i][0];
        f[i]   = GlobalArray[i][1];
        df[i]  = GlobalArray[i][2];

        y[i]   = C*eta[i];
        u[i]   = U_inf*df[i];
        v[i]   = nu*sqrt(U_inf/(2*nu*x))*(y[i]*sqrt(U_inf/(2*nu*x))*df[i] - f[i]);
    }

    //! Reordering y grid points
    for(j=0; j<=nQuadraturePts_y-1; j++)
    {
        for(i=j+1; i<=nQuadraturePts_y-1; i++)
        {
            if(y_QuadraturePts_y[j] > y_QuadraturePts_y[i])
            {
                tmp = y_QuadraturePts_y[j];
                y_QuadraturePts_y[j] = y_QuadraturePts_y[i];
                y_QuadraturePts_y[i] = tmp;
            }
        }
    }

    //! Piecewise linear interpolation of the blasius profile along y lagrangian points ------------
    k = 0;
    Array<OneD,NekDouble> uk;
    Array<OneD,NekDouble> vk;
    uk = Array<OneD,NekDouble>(nQuadraturePts_y);
    vk = Array<OneD,NekDouble>(nQuadraturePts_y);

    for(i=0; i<=numLines-1; i++)
    {
        while((y_QuadraturePts_y[k] >= y[i]) & (y_QuadraturePts_y[k] <= y[i+1]))
        {
            uk[k] = (y_QuadraturePts_y[k] - y[i])*(u[i+1] - u[i])/(y[i+1] - y[i]) + u[i];
            vk[k] = (y_QuadraturePts_y[k] - y[i])*(v[i+1] - v[i])/(y[i+1] - y[i]) + v[i];
            k = k+1;
            if (k == nQuadraturePts_y + 1) break;
        }
    }

    //! Checking the interpolation
    FILE *original_data;
    original_data = fopen("original_data.txt","w+");
    for(j=0; j<=numLines-1;j++)
    {
        fprintf(original_data,"%f %f %f\n", y[j], u[j], v[j]);
    }
    fclose(original_data);

    FILE *interpolation_data;
    interpolation_data = fopen("interpolation_data.txt","w+");
    for(j=0; j<=nQuadraturePts_y-1;j++)
    {
        fprintf(interpolation_data,"%f %f %f\n", y_QuadraturePts_y[j], uk[j], vk[j]);
    }
    fclose(interpolation_data);
    //! --------------------------------------------------------------------------------------------

    //! Definition of the 2D expansion using the mesh data specified on the session file ----------
    MultiRegions::ExpList2DSharedPtr Exp2D_uk;
    Exp2D_uk = MemoryManager<MultiRegions::ExpList2D>::AllocateSharedPtr(vSession,graphShPt);

    MultiRegions::ExpList2DSharedPtr Exp2D_vk;
    Exp2D_vk = MemoryManager<MultiRegions::ExpList2D>::AllocateSharedPtr(vSession,graphShPt);

    MultiRegions::ExpList2DSharedPtr Exp2D_pk;
    Exp2D_pk = MemoryManager<MultiRegions::ExpList2D>::AllocateSharedPtr(vSession,graphShPt);
    //! --------------------------------------------------------------------------------------------

    //! Filling the 2D expansion using a recursive algorithm based on the mesh ordering ------------
    /*  NOTE:   1) The mesh must have a specific ordering.
     *          2) The mesh must have a BL refinement block defined using a specific criterion.
     *          3) At the moment parallel BL only.
     *          4) No recursive algorithm on the farfield block (implicit assumption that the
     *             entire BL (and possibly part of the farfield) will be in the BL refinement
     *             block.
     *          5) Only field u at the moment --> v and p are coming.
     */

    m = 0;
    int numModes = 9;
    int nElement_x = nQuadraturePts_x/(numModes+1);
    int nElement_y = nQuadraturePts_y/(numModes+1);

    Array<OneD,NekDouble> ukGlobal;
    ukGlobal = Array<OneD,NekDouble>(nQuadraturePts);
    Array<OneD,NekDouble> vkGlobal;
    vkGlobal = Array<OneD,NekDouble>(nQuadraturePts);
    Array<OneD,NekDouble> pkGlobal;
    pkGlobal = Array<OneD,NekDouble>(nQuadraturePts);

    std::cout<< "Elements along x             = " << nElement_x     << std::endl;
    std::cout<< "Elements along y             = " << nElement_y     << std::endl;
    std::cout<< "Elements along within the BL = " << nElements_yBL   << std::endl;
    std::cout<< "Number of modes              = " << numModes       << std::endl;

    //! Loops on the BL refinement block
    for(xElement=0; xElement<=nElement_x-1; xElement++)
    {
        for(yLevel=0; yLevel<=(numModes+1)*nElements_yBL - 1; yLevel++)
        {
            for(j=0; j<=numModes; j++)
            {
                ukGlobal[m] = uk[yLevel];
                vkGlobal[m] = vk[yLevel];
                pkGlobal[m] = 0.0;
                m = m+1;
            }
        }
    }

    //! Loops on the farfield block
    for(i=m; i<=nQuadraturePts-1; i++)
    {
        ukGlobal[i] = uk[nQuadraturePts_y-1];
        vkGlobal[i] = vk[nQuadraturePts_y-1];
        pkGlobal[i] = 0.0;
    }

    //! Copying the ukGlobal vector (with the same pattern of m_phys) in m_phys
    Vmath::Vcopy(nQuadraturePts, ukGlobal, 1, Exp2D_uk->UpdatePhys(), 1);
    Vmath::Vcopy(nQuadraturePts, vkGlobal, 1, Exp2D_vk->UpdatePhys(), 1);
    Vmath::Vcopy(nQuadraturePts, pkGlobal, 1, Exp2D_pk->UpdatePhys(), 1);

    //! Initialisation of the ExpList Exp
    Array<OneD, MultiRegions::ExpListSharedPtr> Exp(3);
    Exp[0] = Exp2D_uk;
    Exp[1] = Exp2D_vk;
    Exp[2] = Exp2D_pk;

    //! Expansion coefficient extraction (necessary to write the .fld file)
    Exp[0]->FwdTrans(Exp2D_uk->GetPhys(),Exp[0]->UpdateCoeffs());
    Exp[1]->FwdTrans(Exp2D_vk->GetPhys(),Exp[1]->UpdateCoeffs());
    Exp[2]->FwdTrans(Exp2D_pk->GetPhys(),Exp[2]->UpdateCoeffs());
    //! --------------------------------------------------------------------------------------------

    //! Generation .FLD file with one field only (at the moment) -----------------------------------
    //! Definition of the name of the .fld file
    string blasius = "blasius.fld";

    //! Definition of the number of the fields
    int nFields = 3;

    //! Definition of the Field
    std::vector<SpatialDomains::FieldDefinitionsSharedPtr> FieldDef = Exp[0]->GetFieldDefinitions();
    std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

    for(j = 0; j < nFields; ++j)
    {
		for(i = 0; i < FieldDef.size(); ++i)
		{
            if(j == 0)
            {
                FieldDef[i]->m_fields.push_back("u");
            }
            else if(j == 1)
            {
                FieldDef[i]->m_fields.push_back("v");
            }
            else if(j == 2)
            {
                FieldDef[i]->m_fields.push_back("p");
            }
            Exp[j]->AppendFieldData(FieldDef[i], FieldData[i]);
        }
    }
    graphShPt->Write(blasius, FieldDef, FieldData);
    std::cout<<"------------------------------------------------------------\n";

    return 0;
}

<commit_msg>FldAddBlasius removed.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/validation/Validator.h"

using namespace db::rt;
using namespace db::validation;

Validator::Validator()
{
}

Validator::~Validator()
{
}

std::string Validator::stringFromPath(std::vector<const char*>* path)
{
   std::string rval;

   if(!path)
   {
      rval = "";
   }
   else
   {
      for(std::vector<const char*>::iterator i = path->begin();
         i != path->end();
         i++)
      {
         rval.append(*i);
      }
   }

   return rval;
}

DynamicObject Validator::addError(
   std::vector<const char*>* path,
   const char* type)
{
   DynamicObject errorDetail;

   ExceptionRef e;

   if(!Exception::hasLast())
   {
      e = new Exception("Object not valid.", "db.validation.ValidationError");
      Exception::setLast(e, false);
   }
   else
   {
      e = Exception::getLast();
      // Check we are adding to a ValidationError
      if(strcmp(e->getType(), "db.validation.ValidationError") != 0)
      {
         // FIXME: this is a bit bogus.  If validation checking keeps causing
         // other exceptions then a long cause chain could be generated
         // switching between ValidationError and other types.
         e = new Exception(
            "Object not valid.", "db.validation.ValidationError");
         Exception::setLast(e, true);
      }
   }

   // setup error detail
   errorDetail["type"] = type;
   // FIXME: localize message
   errorDetail["message"] = "Invalid value!";

   // add detail to "errors" section of exception details
   std::string fullpath = stringFromPath(path);
   e->getDetails()["errors"][fullpath.c_str()] = errorDetail;

   return errorDetail;
}
<commit_msg>Simplified path check/string setting.<commit_after>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/validation/Validator.h"

using namespace db::rt;
using namespace db::validation;

Validator::Validator()
{
}

Validator::~Validator()
{
}

std::string Validator::stringFromPath(std::vector<const char*>* path)
{
   std::string rval;

   if(path != NULL)
   {
      for(std::vector<const char*>::iterator i = path->begin();
         i != path->end();
         i++)
      {
         rval.append(*i);
      }
   }

   return rval;
}

DynamicObject Validator::addError(
   std::vector<const char*>* path,
   const char* type)
{
   DynamicObject errorDetail;

   ExceptionRef e;

   if(!Exception::hasLast())
   {
      e = new Exception("Object not valid.", "db.validation.ValidationError");
      Exception::setLast(e, false);
   }
   else
   {
      e = Exception::getLast();
      // Check we are adding to a ValidationError
      if(strcmp(e->getType(), "db.validation.ValidationError") != 0)
      {
         // FIXME: this is a bit bogus.  If validation checking keeps causing
         // other exceptions then a long cause chain could be generated
         // switching between ValidationError and other types.
         e = new Exception(
            "Object not valid.", "db.validation.ValidationError");
         Exception::setLast(e, true);
      }
   }

   // setup error detail
   errorDetail["type"] = type;
   // FIXME: localize message
   errorDetail["message"] = "Invalid value!";

   // add detail to "errors" section of exception details
   std::string fullpath = stringFromPath(path);
   e->getDetails()["errors"][fullpath.c_str()] = errorDetail;

   return errorDetail;
}
<|endoftext|>


<commit_before>#include "../header/vns-priv.hpp"

using namespace std;
using namespace boost;
using namespace pcp;

const string changeNode::getName() {
	return "changeNode";
}

const char changeNode::getAbbreviation() {
	return getStaticAbbreviation();
}

const char changeNode::getStaticAbbreviation() {
	return 'n';
}

Solution *changeNode::findLocalMin(Solution& best, Solution& full) {
	Solution* s = new Solution(&best);
	int maxColor = best.colorsUsed - 1;
	const int ITER_MAX = 1000;
	pair<VertexIter, VertexIter> vIter;
	VertexPart_Map vParts = get(vertex_index1_t(), *s->g);
	VertexPart_Map vPartsOrig = get(vertex_index1_t(), *full.g);
   VertexID_Map vIndex = get(vertex_index2_t(), *s->g);

   if (DEBUG_LEVEL > 2) {
		cout<<"Starting changeNode"<<endl;
	}

	/// Recolor all nodes who use maxColor with a random color < maxColor
	for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {
		if (s->partition[vParts[*vIter.first]] == maxColor) {
			int col = rand() % maxColor;
			s->partition[vParts[*vIter.first]] = col;
			if (DEBUG_LEVEL > 3) {
				cout<<"Recoloring "<<*vIter.first<<" with color ";
				cout<<col<<endl;
			}
		}
	}

	pair<AdjIter, AdjIter> ai;
	int colors[s->numParts];
	int i = 0;
	int iter = 0;
	std::vector<Vertex> conflicts;
	std::vector<Vertex> partition;

	/// Add all nodes of a conflict to vector conflict
	for (vIter = vertices(*s->g); vIter.first != vIter.second;
			  vIter.first++) {

		for (ai = adjacent_vertices(*vIter.first, *s->g);
			  ai.first != ai.second; ai.first++) {

			if (s->partition[vParts[*ai.first]] ==
				 s->partition[vParts[*vIter.first]]) {

				if (DEBUG_LEVEL > 3) {
					cout<<"Conflicting node "<<*vIter.first<< " with color ";
					cout<<s->partition[vParts[*vIter.first]]<<" added to conflicts";
					cout<<endl;
				}
				conflicts.push_back(*vIter.first);
				break;
			}
		}
	}

	/// Run until there are no more conflicts, or there were to many iterations
	while (conflicts.size() != 0 && iter < ITER_MAX) {
		iter++;

		/// Pick a random conflicting partition
		int random = rand() % conflicts.size();
		Vertex v = conflicts[random];
		partition.clear();
		int part = vParts[v];

		if (DEBUG_LEVEL > 3) {
			cout<<"Chose random Vertex "<<v<<" in partition "<<part;
			cout<<" from conflicts, this vertex is equal to vertex ";
			cout<<vIndex[v]<<" in the original graph"<<endl;
		}

		/// Find all vertices of the chosen partition
		for (vIter = vertices(*full.g); vIter.first != vIter.second;
			  vIter.first++) {
			if (vPartsOrig[*vIter.first] == part && *vIter.first != vIndex[v]) {
				if (DEBUG_LEVEL > 3) {
					cout<<"Found node "<<*vIter.first<<" in partition "<<part<<endl;
				}
				partition.push_back(*vIter.first);
			}
		}

		/// If partition contains other vertices
		if (partition.size() != 0) {

			/// Choose random replacement node
			random = rand() % partition.size();
			Vertex rep = partition[random];
			if (DEBUG_LEVEL > 3) {
				cout<<"Randomly chosen replacement is "<<rep<<endl;
			}

			/// Clear old vertex of all edges
			clear_vertex(v, *s->g);
			vIndex[v] = rep;

			fill(colors, colors + s->numParts, 0);

			/// Search matching edges for replacement vertex
			for (ai = adjacent_vertices(rep, *full.g);
				  ai.first != ai.second; ai.first++) {

				if (vIndex[s->representatives[vPartsOrig[*ai.first]]] == *ai.first
					 && vPartsOrig[*ai.first] != vParts[v]) {

					add_edge(v, s->representatives[vPartsOrig[*ai.first]], *s->g);
					colors[s->partition[vPartsOrig[*ai.first]]] = 1;
				}

			}

			bool found = false;
			for (i = 0; i < maxColor; i++) {
				if (colors[i] == 0) {
					if (DEBUG_LEVEL > 2) {
						cout<<"Found new suitable color for node "<<v<<"; the color is ";
						cout<<i<<endl;
					}

					found = true;
					s->partition[part] = i;
					break;
				}
			}

			/// No suitable color with color < maxColor found for replaced node
			if (!found) {
				if (DEBUG_LEVEL > 2) {
					cout<<"Found no new suitable color for node "<<v<<", choose random";
					cout<<" color"<<endl;
				}

				s->partition[vParts[v]] = rand() % maxColor;
			}
		}

		/// Rebuild all conflicts in vector "conflicts"
		conflicts.clear();
		for (vIter = vertices(*s->g); vIter.first != vIter.second;
				  vIter.first++) {

			for (ai = adjacent_vertices(*vIter.first, *s->g);
				  ai.first != ai.second; ai.first++) {

				if (s->partition[vParts[*ai.first]] ==
					 s->partition[vParts[*vIter.first]]) {

					if (DEBUG_LEVEL > 3) {
						cout<<"Conflicting node "<<*vIter.first<< " with color ";
						cout<<s->partition[vParts[*vIter.first]]<<" added to conflicts";
						cout<<endl;
					}
					conflicts.push_back(*vIter.first);
					break;
				}
			}
		}
	}

	/// Solution contains conlficts, revert changes
	if (conflicts.size() != 0) {
		if (DEBUG_LEVEL > 1) {
			cout<<"Conflict found"<<endl;
		}
		delete s;
		return new Solution(&best);
	}

	/// Solution is free of conflicts
	else {
		maxColor = 0;
		for (vIter = vertices(*s->g); vIter.first != vIter.second;
			  vIter.first++) {

			if (s->partition[vParts[*vIter.first]] > maxColor) {
				maxColor = s->partition[vParts[*vIter.first]];
			}
		}
		s->colorsUsed = maxColor + 1;
		if (DEBUG_LEVEL > 1) {
			cout<<"changeNode uses "<<s->colorsUsed<<" colors"<<endl;
		}
		Solution *temp = this->findLocalMin(*s, full);
		if (temp->colorsUsed < s->colorsUsed) {
			delete s;
			s = temp;
		}
	}
	return s;
}

Solution *changeNode::shuffleSolution(Solution& cur, Solution& full,
				 							  	  int numSteps) {
	Solution* ret = new Solution(&cur);

	VertexPart_Map vPartsOrig = get(vertex_index1_t(), *full.g);
	VertexID_Map vIndex = get(vertex_index2_t(), *ret->g);
	pair<AdjIter, AdjIter> ai;
	int colors[ret->numParts];
	int i = 0;

	for (int a = 0; a < numSteps; a++) {
		/// Select a random node in the original graph and replace it in the
		/// solution graph
		Vertex replacement = rand() % num_vertices(*full.g);
		int part = vPartsOrig[replacement];
		Vertex v = ret->representatives[part];

		/// If it isn't already the current chosen node
		if (vIndex[ret->representatives[part]] != replacement) {

			clear_vertex(v, *ret->g);
			vIndex[v] = replacement;

			fill(colors, colors + ret->numParts, 0);

			/// Search matching edges for replacement vertex
			for (ai = adjacent_vertices(replacement, *full.g);
				  ai.first != ai.second; ai.first++) {

				if (vIndex[ret->representatives[vPartsOrig[*ai.first]]] == *ai.first
					 && vPartsOrig[*ai.first] != part) {

					add_edge(v, ret->representatives[vPartsOrig[*ai.first]], *ret->g);
					colors[ret->partition[vPartsOrig[*ai.first]]] = 1;
				}
			}

			for (i = 0; i < ret->numParts; i++) {
				if (colors[i] == 0) {
					ret->partition[part] = i;
					break;
				}
			}
		}
	}

	for (i = 0; i < ret->numParts; i++) {
				colors[i] = 0;
	}

	int maxColor = 0;
	bool gap = false;
	for (i = 0; i < ret->numParts; i++) {
		colors[ret->partition[i]] = 1;
		if (maxColor < ret->partition[i]) {
			maxColor = ret->partition[i];
		}
	}
	int minGap = 0;
	for (i = 0; i < maxColor + 1; i++) {
		if (colors[i] == 0) {
			gap = true;
			minGap = i;
			break;
		}
	}
	while (gap) {
		gap = false;
		for (i = minGap; i < ret->numParts; i++) {
				colors[i] = 0;
		}
		maxColor = 0;
		for (i = 0; i < ret->numParts; i++) {
			if (ret->partition[i] > minGap) {
				ret->partition[i]--;
				colors[ret->partition[i]] = 1;
				if (maxColor < ret->partition[i]) {
					maxColor = ret->partition[i];
				}
			}
		}
		for (i = minGap; i < maxColor + 1; i++) {
			if (colors[i] == 0) {
				gap = true;
				minGap = i;
				break;
			}
		}
	}

	ret->colorsUsed = maxColor + 1;
	return ret;
}
<commit_msg>Added conversion between signed and unsigned integer<commit_after>#include "../header/vns-priv.hpp"

using namespace std;
using namespace boost;
using namespace pcp;

const string changeNode::getName() {
	return "changeNode";
}

const char changeNode::getAbbreviation() {
	return getStaticAbbreviation();
}

const char changeNode::getStaticAbbreviation() {
	return 'n';
}

Solution *changeNode::findLocalMin(Solution& best, Solution& full) {
	Solution* s = new Solution(&best);
	int maxColor = best.colorsUsed - 1;
	const int ITER_MAX = 1000;
	pair<VertexIter, VertexIter> vIter;
	VertexPart_Map vParts = get(vertex_index1_t(), *s->g);
	VertexPart_Map vPartsOrig = get(vertex_index1_t(), *full.g);
   VertexID_Map vIndex = get(vertex_index2_t(), *s->g);

   if (DEBUG_LEVEL > 2) {
		cout<<"Starting changeNode"<<endl;
	}

	/// Recolor all nodes who use maxColor with a random color < maxColor
	for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {
		if (s->partition[vParts[*vIter.first]] == maxColor) {
			int col = rand() % maxColor;
			s->partition[vParts[*vIter.first]] = col;
			if (DEBUG_LEVEL > 3) {
				cout<<"Recoloring "<<*vIter.first<<" with color ";
				cout<<col<<endl;
			}
		}
	}

	pair<AdjIter, AdjIter> ai;
	int colors[s->numParts];
	int i = 0;
	int iter = 0;
	std::vector<Vertex> conflicts;
	std::vector<Vertex> partition;

	/// Add all nodes of a conflict to vector conflict
	for (vIter = vertices(*s->g); vIter.first != vIter.second;
			  vIter.first++) {

		for (ai = adjacent_vertices(*vIter.first, *s->g);
			  ai.first != ai.second; ai.first++) {

			if (s->partition[vParts[*ai.first]] ==
				 s->partition[vParts[*vIter.first]]) {

				if (DEBUG_LEVEL > 3) {
					cout<<"Conflicting node "<<*vIter.first<< " with color ";
					cout<<s->partition[vParts[*vIter.first]]<<" added to conflicts";
					cout<<endl;
				}
				conflicts.push_back(*vIter.first);
				break;
			}
		}
	}

	/// Run until there are no more conflicts, or there were to many iterations
	while (conflicts.size() != 0 && iter < ITER_MAX) {
		iter++;

		/// Pick a random conflicting partition
		int random = rand() % conflicts.size();
		Vertex v = conflicts[random];
		partition.clear();
		int part = vParts[v];

		if (DEBUG_LEVEL > 3) {
			cout<<"Chose random Vertex "<<v<<" in partition "<<part;
			cout<<" from conflicts, this vertex is equal to vertex ";
			cout<<vIndex[v]<<" in the original graph"<<endl;
		}

		/// Find all vertices of the chosen partition
		for (vIter = vertices(*full.g); vIter.first != vIter.second;
			  vIter.first++) {
			if (vPartsOrig[*vIter.first] == part &&
				 (int)(*vIter.first) != vIndex[v]) {
				if (DEBUG_LEVEL > 3) {
					cout<<"Found node "<<*vIter.first<<" in partition "<<part<<endl;
				}
				partition.push_back(*vIter.first);
			}
		}

		/// If partition contains other vertices
		if (partition.size() != 0) {

			/// Choose random replacement node
			random = rand() % partition.size();
			Vertex rep = partition[random];
			if (DEBUG_LEVEL > 3) {
				cout<<"Randomly chosen replacement is "<<rep<<endl;
			}

			/// Clear old vertex of all edges
			clear_vertex(v, *s->g);
			vIndex[v] = rep;

			fill(colors, colors + s->numParts, 0);

			/// Search matching edges for replacement vertex
			for (ai = adjacent_vertices(rep, *full.g);
				  ai.first != ai.second; ai.first++) {

				if (vIndex[s->representatives[vPartsOrig[*ai.first]]] ==
					 (int)*ai.first && vPartsOrig[*ai.first] != vParts[v]) {

					add_edge(v, s->representatives[vPartsOrig[*ai.first]], *s->g);
					colors[s->partition[vPartsOrig[*ai.first]]] = 1;
				}

			}

			bool found = false;
			for (i = 0; i < maxColor; i++) {
				if (colors[i] == 0) {
					if (DEBUG_LEVEL > 2) {
						cout<<"Found new suitable color for node "<<v<<"; the color is ";
						cout<<i<<endl;
					}

					found = true;
					s->partition[part] = i;
					break;
				}
			}

			/// No suitable color with color < maxColor found for replaced node
			if (!found) {
				if (DEBUG_LEVEL > 2) {
					cout<<"Found no new suitable color for node "<<v<<", choose random";
					cout<<" color"<<endl;
				}

				s->partition[vParts[v]] = rand() % maxColor;
			}
		}

		/// Rebuild all conflicts in vector "conflicts"
		conflicts.clear();
		for (vIter = vertices(*s->g); vIter.first != vIter.second;
				  vIter.first++) {

			for (ai = adjacent_vertices(*vIter.first, *s->g);
				  ai.first != ai.second; ai.first++) {

				if (s->partition[vParts[*ai.first]] ==
					 s->partition[vParts[*vIter.first]]) {

					if (DEBUG_LEVEL > 3) {
						cout<<"Conflicting node "<<*vIter.first<< " with color ";
						cout<<s->partition[vParts[*vIter.first]]<<" added to conflicts";
						cout<<endl;
					}
					conflicts.push_back(*vIter.first);
					break;
				}
			}
		}
	}

	/// Solution contains conlficts, revert changes
	if (conflicts.size() != 0) {
		if (DEBUG_LEVEL > 1) {
			cout<<"Conflict found"<<endl;
		}
		delete s;
		return new Solution(&best);
	}

	/// Solution is free of conflicts
	else {
		maxColor = 0;
		for (vIter = vertices(*s->g); vIter.first != vIter.second;
			  vIter.first++) {

			if (s->partition[vParts[*vIter.first]] > maxColor) {
				maxColor = s->partition[vParts[*vIter.first]];
			}
		}
		s->colorsUsed = maxColor + 1;
		if (DEBUG_LEVEL > 1) {
			cout<<"changeNode uses "<<s->colorsUsed<<" colors"<<endl;
		}
		Solution *temp = this->findLocalMin(*s, full);
		if (temp->colorsUsed < s->colorsUsed) {
			delete s;
			s = temp;
		}
	}
	return s;
}

Solution *changeNode::shuffleSolution(Solution& cur, Solution& full,
				 							  	  int numSteps) {
	Solution* ret = new Solution(&cur);

	VertexPart_Map vPartsOrig = get(vertex_index1_t(), *full.g);
	VertexID_Map vIndex = get(vertex_index2_t(), *ret->g);
	pair<AdjIter, AdjIter> ai;
	int colors[ret->numParts];
	int i = 0;

	for (int a = 0; a < numSteps; a++) {
		/// Select a random node in the original graph and replace it in the
		/// solution graph
		Vertex replacement = rand() % num_vertices(*full.g);
		int part = vPartsOrig[replacement];
		Vertex v = ret->representatives[part];

		/// If it isn't already the current chosen node
		if (vIndex[ret->representatives[part]] != (int)replacement) {

			clear_vertex(v, *ret->g);
			vIndex[v] = replacement;

			fill(colors, colors + ret->numParts, 0);

			/// Search matching edges for replacement vertex
			for (ai = adjacent_vertices(replacement, *full.g);
				  ai.first != ai.second; ai.first++) {

				if (vIndex[ret->representatives[vPartsOrig[*ai.first]]] ==
					 (int)*ai.first && vPartsOrig[*ai.first] != part) {

					add_edge(v, ret->representatives[vPartsOrig[*ai.first]], *ret->g);
					colors[ret->partition[vPartsOrig[*ai.first]]] = 1;
				}
			}

			for (i = 0; i < ret->numParts; i++) {
				if (colors[i] == 0) {
					ret->partition[part] = i;
					break;
				}
			}
		}
	}

	for (i = 0; i < ret->numParts; i++) {
				colors[i] = 0;
	}

	int maxColor = 0;
	bool gap = false;
	for (i = 0; i < ret->numParts; i++) {
		colors[ret->partition[i]] = 1;
		if (maxColor < ret->partition[i]) {
			maxColor = ret->partition[i];
		}
	}
	int minGap = 0;
	for (i = 0; i < maxColor + 1; i++) {
		if (colors[i] == 0) {
			gap = true;
			minGap = i;
			break;
		}
	}
	while (gap) {
		gap = false;
		for (i = minGap; i < ret->numParts; i++) {
				colors[i] = 0;
		}
		maxColor = 0;
		for (i = 0; i < ret->numParts; i++) {
			if (ret->partition[i] > minGap) {
				ret->partition[i]--;
				colors[ret->partition[i]] = 1;
				if (maxColor < ret->partition[i]) {
					maxColor = ret->partition[i];
				}
			}
		}
		for (i = minGap; i < maxColor + 1; i++) {
			if (colors[i] == 0) {
				gap = true;
				minGap = i;
				break;
			}
		}
	}

	ret->colorsUsed = maxColor + 1;
	return ret;
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <cmath>

#include <algorithm>
#include <functional>
#include <utility>
#include <vector>

#include "../benchmark.h"

#include "testbench.h"

using namespace std;
using namespace xp;

namespace ewilliams {

	int find(int N)
	{
		int returnVal = 0;
		int first = 1;
		int second = 1;
		while (second < N)
		{
			second = first + second;
			first = second - first;

			// cout << "Second: " << second << " : first " << first << endl;
		}

		int val1 = N - first;
		int val2 = second - N;

		if (val1 < val2)
		{
			returnVal = first;
		} else
		{
			returnVal = second;
		}
		return returnVal;
	}

}

namespace slewis {

	const double FPF = pow(5, 0.5);
	const double PHI = (1 + FPF) / 2;

	int fib(int n) {
		// Binets formula
		return (int)rint((pow(PHI, n) - pow((1 - PHI), n)) / FPF);
	}

	int fibinv(int n) {
		if (n < 2) return n;
		// Inverse Binet, dropping the 1-PHi^n.
		return fib((int)rint(log(n * FPF) / log(PHI)));
	}

}
namespace vjacquet {

	template<typename T>
	T delta(const T& x, const T& y) {
		return y - x;
	}

	template<typename T>
	pair<T, T> fibonaccci_step(const T& fn_1, const T& fn_2) {
		// Fn = Fn-1 + Fn-2
		return {fn_1 + fn_2, fn_1};
	}

	template<typename T>
	pair<T, T> bounding_fibonacci(const T& x) {
		T fn_2 = {0};
		T fn_1 = {1};
		if (x > 0) {
			do
				tie(fn_1, fn_2) = fibonaccci_step(fn_1, fn_2);
			while (fn_1 < x);
		}
		return {fn_1, fn_2};
	}

	template<typename T>
	T nearest_fibonnaci(const T& x) {
		T fn_2, fn_1;
		tie(fn_1, fn_2) = bounding_fibonacci(x);
		if (delta(fn_2, x) < delta(x, fn_1))
			return fn_2;
		return fn_1;
	}
}

TESTBENCH()

TEST(generate_fibonacci_series) {
	// int32_t overflows at 48.
	// int64_t overflows at 94.
	vector<int64_t> v(93, 0);
	v[1] = 1;
	transform(begin(v), end(v) - 2, begin(v) + 1, begin(v) + 2, plus<int64_t>());
}

TEST(check_get_nearest_fibonacci_ewilliams) {
	using namespace ewilliams;

	VERIFY_EQ(46368, find(50000));
	VERIFY_EQ(75025, find(75000));
}

TEST(check_get_nearest_fibonacci_slewis) {
	using namespace slewis;

	VERIFY_EQ(46368, fibinv(50000));
	VERIFY_EQ(75025, fibinv(75000));
}

TEST(check_get_nearest_fibonacci_vjacquet) {
	using namespace vjacquet;

	VERIFY_EQ(46368, nearest_fibonnaci(50000));
	VERIFY_EQ(75025, nearest_fibonnaci(75000));
}

TEST(benchmark) {
	using namespace std::chrono;

	typedef processor_clock C;
	typedef int value_type;

	const value_type Val = 50000;
	const int Repeat = 25000000;

	auto ew = measure<processor_clock>(Repeat, bind(ewilliams::find, Val));
	cout << "  ewilliams: " << (double)Repeat / duration_cast<microseconds>(ew).count() << " executions per microseconds." << endl;
	auto sl = measure<processor_clock>(Repeat, bind(slewis::fibinv, Val));
	cout << "  slewis:    " << (double)Repeat / duration_cast<microseconds>(sl).count() << " executions per microseconds." << endl;
	auto vj = measure<processor_clock>(Repeat, bind(vjacquet::nearest_fibonnaci<value_type>, Val));
	cout << "  vjacquet:  " << (double)Repeat / duration_cast<microseconds>(vj).count() << " executions per microseconds." << endl;

}

TESTFIXTURE(fibonacci)
<commit_msg>Removed delta function.<commit_after>#include <cstdint>
#include <cmath>

#include <algorithm>
#include <functional>
#include <utility>
#include <vector>

#include "../benchmark.h"

#include "testbench.h"

using namespace std;
using namespace xp;

namespace ewilliams {

	int find(int N)
	{
		int returnVal = 0;
		int first = 1;
		int second = 1;
		while (second < N)
		{
			second = first + second;
			first = second - first;

			// cout << "Second: " << second << " : first " << first << endl;
		}

		int val1 = N - first;
		int val2 = second - N;

		if (val1 < val2)
		{
			returnVal = first;
		} else
		{
			returnVal = second;
		}
		return returnVal;
	}

}

namespace slewis {

	const double FPF = pow(5, 0.5);
	const double PHI = (1 + FPF) / 2;

	int fib(int n) {
		// Binets formula
		return (int)rint((pow(PHI, n) - pow((1 - PHI), n)) / FPF);
	}

	int fibinv(int n) {
		if (n < 2) return n;
		// Inverse Binet, dropping the 1-PHi^n.
		return fib((int)rint(log(n * FPF) / log(PHI)));
	}

}
namespace vjacquet {

	template<typename T>
	pair<T, T> fibonaccci_step(const T& fn_1, const T& fn_2) {
		// Fn = Fn-1 + Fn-2
		return {fn_1 + fn_2, fn_1};
	}

	template<typename T>
	pair<T, T> bounding_fibonacci(const T& x) {
		T fn_2 = {0};
		T fn_1 = {1};
		if (x > 1) {
			do
				tie(fn_1, fn_2) = fibonaccci_step(fn_1, fn_2);
			while (fn_1 < x);
		}
		return {fn_1, fn_2};
	}

	template<typename T>
	T nearest_fibonnaci(const T& x) {
		T fn_2, fn_1;
		tie(fn_1, fn_2) = bounding_fibonacci(x);
		if ((x - fn_2) < (fn_1 - x))
			return fn_2;
		return fn_1;
	}
}

TESTBENCH()

TEST(generate_fibonacci_series) {
	// int32_t overflows at 48.
	// int64_t overflows at 94.
	vector<int64_t> v(93, 0);
	v[1] = 1;
	transform(begin(v), end(v) - 2, begin(v) + 1, begin(v) + 2, plus<int64_t>());
}

TEST(check_get_nearest_fibonacci_ewilliams) {
	using namespace ewilliams;

	VERIFY_EQ(46368, find(50000));
	VERIFY_EQ(75025, find(75000));
}

TEST(check_get_nearest_fibonacci_slewis) {
	using namespace slewis;

	VERIFY_EQ(46368, fibinv(50000));
	VERIFY_EQ(75025, fibinv(75000));
}

TEST(check_get_nearest_fibonacci_vjacquet) {
	using namespace vjacquet;

	VERIFY_EQ(46368, nearest_fibonnaci(50000));
	VERIFY_EQ(75025, nearest_fibonnaci(75000));
}

TEST(benchmark) {
	using namespace std::chrono;

	typedef processor_clock C;
	typedef int value_type;

	const value_type Val = 50000;
	const int Repeat = 25000000;

	auto ew = measure<processor_clock>(Repeat, bind(ewilliams::find, Val));
	cout << "  ewilliams: " << (double)Repeat / duration_cast<microseconds>(ew).count() << " executions per microseconds." << endl;
	auto sl = measure<processor_clock>(Repeat, bind(slewis::fibinv, Val));
	cout << "  slewis:    " << (double)Repeat / duration_cast<microseconds>(sl).count() << " executions per microseconds." << endl;
	auto vj = measure<processor_clock>(Repeat, bind(vjacquet::nearest_fibonnaci<value_type>, Val));
	cout << "  vjacquet:  " << (double)Repeat / duration_cast<microseconds>(vj).count() << " executions per microseconds." << endl;

}

TESTFIXTURE(fibonacci)
<|endoftext|>