<commit_before>#include "compiler.h"
#include "mswin.h"
#include <windowsx.h>
#include "polymorph.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "aligned-arrays.h"
#include "print.h"

#define WC_MAIN TEXT ("M")

ALIGN_STACK LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  LRESULT result = 0;
  bool call_def_window_proc = false, close_window = false;

  // Retrieve the window-struct pointer from the window userdata.
  window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));

  switch (msg) {
  case WM_CREATE: {
    // Store the window-struct pointer in the window userdata.
    CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
    ws = (window_struct_t *) cs->lpCreateParams;
    ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
    ws->hglrc = install_rendering_context (hwnd);
    result = ! ws->hglrc; // Allow window creation to continue if and only if context creation succeed.
    break;
  }

  case WM_WINDOWPOSCHANGING: {
    WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
    if (windowpos->flags & SWP_SHOWWINDOW) {
      if (ws->mode == parented) {
        RECT rect;
        ::GetClientRect (::GetParent (hwnd), & rect);
        windowpos->cx = rect.right;
        windowpos->cy = rect.bottom;
      }
      else {
        windowpos->x  = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
        windowpos->y  = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
        windowpos->cx = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
        windowpos->cy = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
      }
      windowpos->flags &= ~ (SWP_NOSIZE | SWP_NOMOVE);
    }
    break;
  }

  case WM_WINDOWPOSCHANGED: {
    WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
    if (windowpos->flags & SWP_SHOWWINDOW) {
      // Remember initial cursor position to detect mouse movement.
      ::GetCursorPos (& ws->initial_cursor_position);
      // (Re-)start the simulation.
      ws->model.start (windowpos->cx, windowpos->cy, ws->settings);
      ::PostMessage (hwnd, WM_APP, 0, 0);
    }
    break;
  }

  case WM_APP:
    ws->model.draw_next ();
    ::InvalidateRect (hwnd, NULL, FALSE);
    break;

  case WM_PAINT: {
    PAINTSTRUCT ps;
    ::BeginPaint (hwnd, & ps);
    ::SwapBuffers (ps.hdc);
    ::EndPaint (hwnd, & ps);
    ::PostMessage (hwnd, WM_APP, 0, 0);
    break;
  }

  case WM_SETCURSOR:
    ::SetCursor (ws->mode == screensaver || ws->mode == configure ? NULL : ::LoadCursor (NULL, IDC_ARROW));
    break;

  case WM_MOUSEMOVE:
    if (ws->mode == screensaver || ws->mode == configure) {
      // Compare the current mouse position with the one stored in the window struct.
      DWORD pos = ::GetMessagePos ();
      int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
      int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
      close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
    }
    break;

  case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
    close_window = ws->mode != parented;
    break;

  case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
    close_window = (ws->mode == screensaver || ws->mode == configure) && LOWORD (wParam) == WA_INACTIVE;
    call_def_window_proc = true;
    break;

  case WM_SYSCOMMAND:
    call_def_window_proc = ! ((ws->mode == screensaver || ws->mode == configure) && wParam == SC_SCREENSAVE);
    break;

  case WM_CLOSE:
    if (ws->mode == configure) {
      if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
        // Workaround for bug observed on Windows 8.1 where hiding
        // a full-monitor OpenGL window does not remove it from the display:
        // resize the window before hiding it.
        ::SetWindowPos (hwnd, NULL, 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
        ::ShowWindow (hwnd, SW_HIDE);
      }
    }
    else
      ::DestroyWindow (hwnd);
    break;

  case WM_DESTROY:
    ::wglMakeCurrent (NULL, NULL);
    if (ws->hglrc) ::wglDeleteContext (ws->hglrc);
    ::PostQuitMessage (0);
    break;

  default:
    call_def_window_proc = true;
    break;
  }

  if (close_window) ::PostMessage (hwnd, WM_CLOSE, 0, 0);
  if (call_def_window_proc) result = ::DefWindowProc (hwnd, msg, wParam, lParam);

  return result;
}

void register_class (HINSTANCE hInstance)
{
  // The screensaver window has no taskbar button or system menu, but the small
  // icon is inherited by the (owned) configure dialog and used for the taskbar button.
  // We could set the dialog's small icon directly, but then it would appear in
  // the dialog's system menu, which is not the desired effect.
  HICON icon = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 0, 0, LR_LOADTRANSPARENT);
  HICON icon_small = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 16, 16, LR_LOADTRANSPARENT);
  WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, WC_MAIN, icon_small };
  ::RegisterClassEx (& wndclass);
}

HWND create_window (HINSTANCE hInstance, HWND parent, LPCTSTR display_name, window_struct_t * ws)
{
  // Create the main window. See MainWndProc for details.
  DWORD style = (ws->mode == parented ? WS_CHILD : WS_POPUP);
  DWORD ex_style =
    (ws->mode == screensaver || ws->mode == configure ? WS_EX_TOPMOST : 0) |
    (ws->mode == persistent ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW);
  return ::CreateWindowEx (ex_style, WC_MAIN, display_name, style,
                           0, 0, 0, 0,
                           parent, NULL, hInstance, ws);
}
<commit_msg>polymorph.cpp: fix return value from WM_CREATE.<commit_after>#include "compiler.h"
#include "mswin.h"
#include <windowsx.h>
#include "polymorph.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "aligned-arrays.h"
#include "print.h"

#define WC_MAIN TEXT ("M")

ALIGN_STACK LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  LRESULT result = 0;
  bool call_def_window_proc = false, close_window = false;

  // Retrieve the window-struct pointer from the window userdata.
  window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));

  switch (msg) {
  case WM_CREATE: {
    // Store the window-struct pointer in the window userdata.
    CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
    ws = (window_struct_t *) cs->lpCreateParams;
    ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
    ws->hglrc = install_rendering_context (hwnd);
    result = ws->hglrc ? 0 : -1; // Allow window creation to continue if and only if context creation succeed.
    break;
  }

  case WM_WINDOWPOSCHANGING: {
    WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
    if (windowpos->flags & SWP_SHOWWINDOW) {
      if (ws->mode == parented) {
        RECT rect;
        ::GetClientRect (::GetParent (hwnd), & rect);
        windowpos->cx = rect.right;
        windowpos->cy = rect.bottom;
      }
      else {
        windowpos->x  = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
        windowpos->y  = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
        windowpos->cx = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
        windowpos->cy = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
      }
      windowpos->flags &= ~ (SWP_NOSIZE | SWP_NOMOVE);
    }
    break;
  }

  case WM_WINDOWPOSCHANGED: {
    WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
    if (windowpos->flags & SWP_SHOWWINDOW) {
      // Remember initial cursor position to detect mouse movement.
      ::GetCursorPos (& ws->initial_cursor_position);
      // (Re-)start the simulation.
      ws->model.start (windowpos->cx, windowpos->cy, ws->settings);
      ::PostMessage (hwnd, WM_APP, 0, 0);
    }
    break;
  }

  case WM_APP:
    ws->model.draw_next ();
    ::InvalidateRect (hwnd, NULL, FALSE);
    break;

  case WM_PAINT: {
    PAINTSTRUCT ps;
    ::BeginPaint (hwnd, & ps);
    ::SwapBuffers (ps.hdc);
    ::EndPaint (hwnd, & ps);
    ::PostMessage (hwnd, WM_APP, 0, 0);
    break;
  }

  case WM_SETCURSOR:
    ::SetCursor (ws->mode == screensaver || ws->mode == configure ? NULL : ::LoadCursor (NULL, IDC_ARROW));
    break;

  case WM_MOUSEMOVE:
    if (ws->mode == screensaver || ws->mode == configure) {
      // Compare the current mouse position with the one stored in the window struct.
      DWORD pos = ::GetMessagePos ();
      int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
      int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
      close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
    }
    break;

  case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
    close_window = ws->mode != parented;
    break;

  case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
    close_window = (ws->mode == screensaver || ws->mode == configure) && LOWORD (wParam) == WA_INACTIVE;
    call_def_window_proc = true;
    break;

  case WM_SYSCOMMAND:
    call_def_window_proc = ! ((ws->mode == screensaver || ws->mode == configure) && wParam == SC_SCREENSAVE);
    break;

  case WM_CLOSE:
    if (ws->mode == configure) {
      if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
        // Workaround for bug observed on Windows 8.1 where hiding
        // a full-monitor OpenGL window does not remove it from the display:
        // resize the window before hiding it.
        ::SetWindowPos (hwnd, NULL, 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
        ::ShowWindow (hwnd, SW_HIDE);
      }
    }
    else
      ::DestroyWindow (hwnd);
    break;

  case WM_DESTROY:
    ::wglMakeCurrent (NULL, NULL);
    if (ws->hglrc) ::wglDeleteContext (ws->hglrc);
    ::PostQuitMessage (0);
    break;

  default:
    call_def_window_proc = true;
    break;
  }

  if (close_window) ::PostMessage (hwnd, WM_CLOSE, 0, 0);
  if (call_def_window_proc) result = ::DefWindowProc (hwnd, msg, wParam, lParam);

  return result;
}

void register_class (HINSTANCE hInstance)
{
  // The screensaver window has no taskbar button or system menu, but the small
  // icon is inherited by the (owned) configure dialog and used for the taskbar button.
  // We could set the dialog's small icon directly, but then it would appear in
  // the dialog's system menu, which is not the desired effect.
  HICON icon = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 0, 0, LR_LOADTRANSPARENT);
  HICON icon_small = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 16, 16, LR_LOADTRANSPARENT);
  WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, WC_MAIN, icon_small };
  ::RegisterClassEx (& wndclass);
}

HWND create_window (HINSTANCE hInstance, HWND parent, LPCTSTR display_name, window_struct_t * ws)
{
  // Create the main window. See MainWndProc for details.
  DWORD style = (ws->mode == parented ? WS_CHILD : WS_POPUP);
  DWORD ex_style =
    (ws->mode == screensaver || ws->mode == configure ? WS_EX_TOPMOST : 0) |
    (ws->mode == persistent ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW);
  return ::CreateWindowEx (ex_style, WC_MAIN, display_name, style,
                           0, 0, 0, 0,
                           parent, NULL, hInstance, ws);
}
<|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <utils.hpp>
#include <Folding.hpp>

int main(int argc, char *argv[]) {
  unsigned int vector = 0;
  unsigned int nrDMsPerBlock = 0;
  unsigned int nrPeriodsPerBlock = 0;
  unsigned int nrBinsPerBlock = 0;
  unsigned int nrDMsPerThread = 0;
  unsigned int nrPeriodsPerThread = 0;
  unsigned int nrBinsPerThread = 0;
  std::string typeName;
	AstroData::Observation observation;

	try {
    isa::utils::ArgumentList args(argc, argv);
    typeName = args.getSwitchArgument< std::string >("-type");
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    vector = args.getSwitchArgument< unsigned int >("-vector");
    nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
    nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb");
    nrBinsPerBlock = args.getSwitchArgument< unsigned int >("-bb");
    nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");
    nrPeriodsPerThread = args.getSwitchArgument< unsigned int >("-pt");
    nrBinsPerThread = args.getSwitchArgument< unsigned int >("-bt");
    observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
    observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), args.getSwitchArgument< unsigned int >("-first_period"), args.getSwitchArgument< unsigned int >("-period_step"));
    observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
	} catch  ( isa::utils::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " -type ... -padding ... -vector ... -db ... -pb ... -bb ... -dt ... -pt ... -bt ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ..." << std::endl;
		return 1;
	}

  // Generate kernel
  std::string * code = PulsarSearch::getFoldingOpenCL(nrDMsPerBlock, nrPeriodsPerBlock, nrBinsPerBlock, nrDMsPerThread, nrPeriodsPerThread, nrBinsPerThread, vector, typeName, observation);
  std::cout << *code << std::endl;

	return 0;
}

<commit_msg>Refactored printCode.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <utils.hpp>
#include <Folding.hpp>

int main(int argc, char *argv[]) {
  std::string typeName;
  PulsarSearch::FoldingConf conf;
	AstroData::Observation observation;

	try {
    isa::utils::ArgumentList args(argc, argv);
    typeName = args.getSwitchArgument< std::string >("-type");
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    conf.setVector(args.getSwitchArgument< unsigned int >("-vector"));
    conf.setNrDMsPerBlock(args.getSwitchArgument< unsigned int >("-db"));
    conf.setNrPeriodsPerBlock(args.getSwitchArgument< unsigned int >("-pb"));
    conf.setNrBinsPerBlock(args.getSwitchArgument< unsigned int >("-bb"));
    conf.setNrDMsPerThread(args.getSwitchArgument< unsigned int >("-dt"));
    conf.setNrPeriodsPerThread(args.getSwitchArgument< unsigned int >("-pt"));
    conf.setNrBinsPerThread(args.getSwitchArgument< unsigned int >("-bt"));
    observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
    observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), args.getSwitchArgument< unsigned int >("-first_period"), args.getSwitchArgument< unsigned int >("-period_step"));
    observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
	} catch  ( isa::utils::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " -type ... -padding ... -vector ... -db ... -pb ... -bb ... -dt ... -pt ... -bt ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ..." << std::endl;
		return 1;
	}

  // Generate kernel
  std::string * code = PulsarSearch::getFoldingOpenCL(conf, typeName, observation);
  std::cout << *code << std::endl;

	return 0;
}

<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2010 Sam Day
 * Copyright (c) 2012 Xavier Mendez
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "repository.h"

#include "common.h"
#include "error.h"

using v8u::Int;
using v8u::Symbol;
using v8u::Bool;
using v8u::Func;
using v8::Local;
using v8::Persistent;
using v8::Function;

namespace gitteh {

Repository::Repository(git_repository* ptr): repo(ptr) {}
Repository::~Repository() {
  git_repository_free(repo);
}

V8_ESCTOR(Repository) { V8_CTOR_NO_JS }

// A FEW ACCESSORS

V8_ESGET(Repository, GetWorkdir) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Str(git_repository_workdir(inst->repo));
}

V8_ESGET(Repository, GetPath) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Str(git_repository_path(inst->repo));
}

V8_ESGET(Repository, IsBare) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Bool(git_repository_is_bare(inst->repo));
}

// STATIC / FACTORY METHODS

//// Repository.discover(...)

GITTEH_WORK_PRE(repo_discover) {
  bool across_fs;
  v8::String::Utf8Value* start;
  char* ceiling_dirs;
  char* output;
  error_info err;

  Persistent<Function> cb;
  uv_work_t req;
};

V8_SCB(Repository::Discover) {
  int len = args.Length()-1; // don't count the callback
  if (len < 1) V8_STHROW(v8u::RangeErr("Not enough arguments!"));
  if (len > 3) len = 3;
  if (!args[len]->IsFunction()) V8_STHROW(v8u::TypeErr("A Function is needed as callback!"));

  repo_discover_req* r = new repo_discover_req;
  r->start = new v8::String::Utf8Value(args[0]);

  r->across_fs = len>=2 ? v8u::Bool(args[1]) : false;
  r->ceiling_dirs = NULL; //FIXME:ceiling

  r->cb = v8u::Persist<Function>(v8u::Cast<Function>(args[len]));
  GITTEH_WORK_QUEUE(repo_discover);
} GITTEH_WORK(repo_discover) { //FIXME: error vs null
  GITTEH_ASYNC_CSTR(r->start, cstart);
  len += 7; //one for \0, more for "/.git/"
  char* out = new char[len];

  int status = git_repository_discover(out, len, cstart, r->across_fs, r->ceiling_dirs);
  delete [] cstart;
  if (status==GIT_OK) r->output = out;
  else {
    collectErr(status, r->err);
    delete [] out;
    r->output = NULL;
  }
} GITTEH_WORK_AFTER(repo_discover) {
  v8::Handle<v8::Value> argv [2];
  if (r->output) {
    argv[0] = v8::Null();
    argv[1] = v8u::Str(r->output);
    delete [] r->output;
  } else {
    argv[0] = composeErr(r->err);
    argv[1] = v8::Null();
  }
  GITTEH_WORK_CALL(2);
} GITTEH_END

V8_SCB(Repository::DiscoverSync) {
  v8::String::Utf8Value start (args[0]);
  GITTEH_SYNC_CSTR(start, cstart);
  len += 7; //one for \0, more for "/.git/"
  char* out = new char[len];

  error_info info;
  int status = git_repository_discover(out, len, cstart, v8u::Bool(args[1]), NULL); //FIXME:ceiling

  delete [] out;
  delete [] cstart;
  if (status == GIT_OK) return v8u::Str(out);
  collectErr(status, info);
  V8_STHROW(composeErr(info));
}

//// Repository.open(...)

GITTEH_WORK_PRE(repo_open) {
  git_repository* out;
  v8::String::Utf8Value* path;
  int flags;
  bool ext;
  char* ceiling_dirs;
  error_info err;

  Persistent<Function> cb;
  uv_work_t req;
};

//TODO: make an exists(...) pair
V8_SCB(Repository::Open) {
  int len = args.Length()-1; // don't count the callback
  if (len < 1) V8_STHROW(v8u::RangeErr("Not enough arguments!"));
  if (len > 3) len = 3;
  if (!args[len]->IsFunction()) V8_STHROW(v8u::TypeErr("A Function is needed as callback!"));

  repo_open_req* r = new repo_open_req;
  r->path = new v8::String::Utf8Value(args[0]);
  if ((r->ext = len > 1)) {
    // enter extended mode if not only the path is given
    r->flags = Int(args[1]);
    /**if (len > 2) r->ceiling_dirs = TODO;
    else**/ r->ceiling_dirs = NULL;
  }

  r->cb = v8u::Persist<Function>(v8u::Cast<Function>(args[len]));
  GITTEH_WORK_QUEUE(repo_open);
} GITTEH_WORK(repo_open) {
  GITTEH_ASYNC_CSTR(r->path, cpath);

  int status;
  if (r->ext) status = git_repository_open_ext(&r->out, cpath, r->flags, r->ceiling_dirs);
  else        status = git_repository_open    (&r->out, cpath);

  if (status == GIT_OK) {
    delete [] cpath;
  } else {
    collectErr(status, r->err);
    delete [] cpath;
    r->out = NULL;
  }
} GITTEH_WORK_AFTER(repo_open) {
  v8::Handle<v8::Value> argv [2];
  if (r->out) {
    argv[0] = v8::Null();
    argv[1] = (new Repository(r->out))->Wrapped();
  } else {
    argv[0] = composeErr(r->err);
    argv[1] = v8::Null();
  }
  GITTEH_WORK_CALL(2);
} GITTEH_END

V8_SCB(Repository::OpenSync) {
  v8::String::Utf8Value path (args[0]);
  GITTEH_SYNC_CSTR(path, cpath);

  int status;
  git_repository* out;
  error_info err;
  if (args.Length() > 1) {
    // enter extended mode if not only the path is given
    int flags = Int(args[1]);
    char* ceiling_dirs;
    /**if (len > 2) ceiling_dirs = TODO;
    else**/ ceiling_dirs = NULL;

    status = git_repository_open_ext(&out, cpath, flags, ceiling_dirs);
    //if (ceiling_dirs) delete [] ceiling_dirs;
  } else status = git_repository_open(&out, cpath);

  delete [] cpath;
  if (status == GIT_OK) return (new Repository(out))->Wrapped();
  collectErr(status, err);
  V8_STHROW(composeErr(err));
}

NODE_ETYPE(Repository, "Repository") {
  V8_DEF_GET("workdir", GetWorkdir);
  V8_DEF_GET("path", GetPath);
  V8_DEF_GET("bare", IsBare);

  Local<Function> func = templ->GetFunction();

  func->Set(Symbol("discover"), Func(Discover)->GetFunction());
  func->Set(Symbol("discoverSync"), Func(DiscoverSync)->GetFunction());

  func->Set(Symbol("open"), Func(Open)->GetFunction());
  func->Set(Symbol("openSync"), Func(OpenSync)->GetFunction());

  //ENUM: repository states -- STATE
  Local<v8::Object> stateHash = v8u::Obj();
  stateHash->Set(Symbol("NONE"), Int(GIT_REPOSITORY_STATE_NONE));
  stateHash->Set(Symbol("MERGE"), Int(GIT_REPOSITORY_STATE_MERGE));
  stateHash->Set(Symbol("REVERT"), Int(GIT_REPOSITORY_STATE_REVERT));
  stateHash->Set(Symbol("CHERRY_PICK"), Int(GIT_REPOSITORY_STATE_CHERRY_PICK));
  stateHash->Set(Symbol("BISECT"), Int(GIT_REPOSITORY_STATE_BISECT));
  stateHash->Set(Symbol("REBASE"), Int(GIT_REPOSITORY_STATE_REBASE));
  stateHash->Set(Symbol("REBASE_INTERACTIVE"), Int(GIT_REPOSITORY_STATE_REBASE_INTERACTIVE));
  stateHash->Set(Symbol("REBASE_MERGE"), Int(GIT_REPOSITORY_STATE_REBASE_MERGE));
  stateHash->Set(Symbol("APPLY_MAILBOX"), Int(GIT_REPOSITORY_STATE_APPLY_MAILBOX));
  stateHash->Set(Symbol("APPLY_MAILBOX_OR_REBASE"), Int(GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE));
  func->Set(Symbol("State"), stateHash);

  //FLAG: init() options -- INIT
  Local<v8::Object> initFlagHash = v8u::Obj();
  initFlagHash->Set(Symbol("BARE"), Int(GIT_REPOSITORY_INIT_BARE));
  initFlagHash->Set(Symbol("NO_REINIT"), Int(GIT_REPOSITORY_INIT_NO_REINIT));
  initFlagHash->Set(Symbol("NO_DOTGIT_DIR"), Int(GIT_REPOSITORY_INIT_NO_DOTGIT_DIR));
  initFlagHash->Set(Symbol("MKDIR"), Int(GIT_REPOSITORY_INIT_MKDIR));
  initFlagHash->Set(Symbol("MKPATH"), Int(GIT_REPOSITORY_INIT_MKPATH));
  initFlagHash->Set(Symbol("EXTERNAL_TEMPLATE"), Int(GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE));
  func->Set(Symbol("InitFlag"), initFlagHash);

  //FLAG: init() mode options -- INIT_SHARED
  Local<v8::Object> initModeHash = v8u::Obj();
  initModeHash->Set(Symbol("SHARED_UMASK"), Int(GIT_REPOSITORY_INIT_SHARED_UMASK));
  initModeHash->Set(Symbol("SHARED_GROUP"), Int(GIT_REPOSITORY_INIT_SHARED_GROUP));
  initModeHash->Set(Symbol("SHARED_ALL"), Int(GIT_REPOSITORY_INIT_SHARED_ALL));
  func->Set(Symbol("InitMode"), initModeHash);

  //FLAG: open() options -- OPEN
  Local<v8::Object> openFlagHash = v8u::Obj();
  openFlagHash->Set(Symbol("NO_SEARCH"), Int(GIT_REPOSITORY_OPEN_NO_SEARCH));
  openFlagHash->Set(Symbol("CROSS_FS"), Int(GIT_REPOSITORY_OPEN_CROSS_FS));
  func->Set(Symbol("OpenFlag"), openFlagHash);

} NODE_TYPE_END()
V8_POST_TYPE(Repository)

};

<commit_msg>Repository:: improve discover(...) code<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2010 Sam Day
 * Copyright (c) 2012 Xavier Mendez
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "repository.h"

#include "common.h"
#include "error.h"

using v8u::Int;
using v8u::Symbol;
using v8u::Bool;
using v8u::Func;
using v8::Local;
using v8::Persistent;
using v8::Function;

namespace gitteh {

Repository::Repository(git_repository* ptr): repo(ptr) {}
Repository::~Repository() {
  git_repository_free(repo);
}

V8_ESCTOR(Repository) { V8_CTOR_NO_JS }

// A FEW ACCESSORS

V8_ESGET(Repository, GetWorkdir) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Str(git_repository_workdir(inst->repo));
}

V8_ESGET(Repository, GetPath) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Str(git_repository_path(inst->repo));
}

V8_ESGET(Repository, IsBare) {
  V8_M_UNWRAP(Repository, info.Holder());
  return v8u::Bool(git_repository_is_bare(inst->repo));
}

// STATIC / FACTORY METHODS

//// Repository.discover(...)

GITTEH_WORK_PRE(repo_discover) {
  bool across_fs;
  v8::String::Utf8Value* start;
  char* ceiling_dirs;
  char* out;
  error_info err;

  Persistent<Function> cb;
  uv_work_t req;
};

V8_SCB(Repository::Discover) {
  int len = args.Length()-1; // don't count the callback
  if (len < 1) V8_STHROW(v8u::RangeErr("Not enough arguments!"));
  if (len > 3) len = 3;
  if (!args[len]->IsFunction()) V8_STHROW(v8u::TypeErr("A Function is needed as callback!"));

  repo_discover_req* r = new repo_discover_req;
  r->start = new v8::String::Utf8Value(args[0]);

  r->across_fs = len>=2 ? v8u::Bool(args[1]) : false;
  r->ceiling_dirs = NULL; //FIXME:ceiling

  r->cb = v8u::Persist<Function>(v8u::Cast<Function>(args[len]));
  GITTEH_WORK_QUEUE(repo_discover);
} GITTEH_WORK(repo_discover) { //FIXME: error vs null
  GITTEH_ASYNC_CSTR(r->start, cstart);
  len += 7; //one for \0, more for "/.git/"
  r->out = new char[len];

  int status = git_repository_discover(r->out, len, cstart, r->across_fs, r->ceiling_dirs);
  delete [] cstart;
  if (status==GIT_OK) return;
  collectErr(status, r->err);
  delete [] r->out;
  r->out = NULL;
} GITTEH_WORK_AFTER(repo_discover) {
  v8::Handle<v8::Value> argv [2];
  if (r->out) {
    argv[0] = v8::Null();
    argv[1] = v8u::Str(r->out);
    delete [] r->out;
  } else {
    argv[0] = composeErr(r->err);
    argv[1] = v8::Null();
  }
  GITTEH_WORK_CALL(2);
} GITTEH_END

V8_SCB(Repository::DiscoverSync) {
  v8::String::Utf8Value start (args[0]);
  GITTEH_SYNC_CSTR(start, cstart);
  len += 7; //one for \0, more for "/.git/"
  char* out = new char[len];

  error_info info;
  int status = git_repository_discover(out, len, cstart, v8u::Bool(args[1]), NULL); //FIXME:ceiling

  delete [] out;
  delete [] cstart;
  if (status == GIT_OK) return v8u::Str(out);
  collectErr(status, info);
  V8_STHROW(composeErr(info));
}

//// Repository.open(...)

GITTEH_WORK_PRE(repo_open) {
  git_repository* out;
  v8::String::Utf8Value* path;
  int flags;
  bool ext;
  char* ceiling_dirs;
  error_info err;

  Persistent<Function> cb;
  uv_work_t req;
};

//TODO: make an exists(...) pair
V8_SCB(Repository::Open) {
  int len = args.Length()-1; // don't count the callback
  if (len < 1) V8_STHROW(v8u::RangeErr("Not enough arguments!"));
  if (len > 3) len = 3;
  if (!args[len]->IsFunction()) V8_STHROW(v8u::TypeErr("A Function is needed as callback!"));

  repo_open_req* r = new repo_open_req;
  r->path = new v8::String::Utf8Value(args[0]);
  if ((r->ext = len > 1)) {
    // enter extended mode if not only the path is given
    r->flags = Int(args[1]);
    /**if (len > 2) r->ceiling_dirs = TODO;
    else**/ r->ceiling_dirs = NULL;
  }

  r->cb = v8u::Persist<Function>(v8u::Cast<Function>(args[len]));
  GITTEH_WORK_QUEUE(repo_open);
} GITTEH_WORK(repo_open) {
  GITTEH_ASYNC_CSTR(r->path, cpath);

  int status;
  if (r->ext) status = git_repository_open_ext(&r->out, cpath, r->flags, r->ceiling_dirs);
  else        status = git_repository_open    (&r->out, cpath);

  if (status == GIT_OK) {
    delete [] cpath;
  } else {
    collectErr(status, r->err);
    delete [] cpath;
    r->out = NULL;
  }
} GITTEH_WORK_AFTER(repo_open) {
  v8::Handle<v8::Value> argv [2];
  if (r->out) {
    argv[0] = v8::Null();
    argv[1] = (new Repository(r->out))->Wrapped();
  } else {
    argv[0] = composeErr(r->err);
    argv[1] = v8::Null();
  }
  GITTEH_WORK_CALL(2);
} GITTEH_END

V8_SCB(Repository::OpenSync) {
  v8::String::Utf8Value path (args[0]);
  GITTEH_SYNC_CSTR(path, cpath);

  int status;
  git_repository* out;
  error_info err;
  if (args.Length() > 1) {
    // enter extended mode if not only the path is given
    int flags = Int(args[1]);
    char* ceiling_dirs;
    /**if (len > 2) ceiling_dirs = TODO;
    else**/ ceiling_dirs = NULL;

    status = git_repository_open_ext(&out, cpath, flags, ceiling_dirs);
    //if (ceiling_dirs) delete [] ceiling_dirs;
  } else status = git_repository_open(&out, cpath);

  delete [] cpath;
  if (status == GIT_OK) return (new Repository(out))->Wrapped();
  collectErr(status, err);
  V8_STHROW(composeErr(err));
}

NODE_ETYPE(Repository, "Repository") {
  V8_DEF_GET("workdir", GetWorkdir);
  V8_DEF_GET("path", GetPath);
  V8_DEF_GET("bare", IsBare);

  Local<Function> func = templ->GetFunction();

  func->Set(Symbol("discover"), Func(Discover)->GetFunction());
  func->Set(Symbol("discoverSync"), Func(DiscoverSync)->GetFunction());

  func->Set(Symbol("open"), Func(Open)->GetFunction());
  func->Set(Symbol("openSync"), Func(OpenSync)->GetFunction());

  //ENUM: repository states -- STATE
  Local<v8::Object> stateHash = v8u::Obj();
  stateHash->Set(Symbol("NONE"), Int(GIT_REPOSITORY_STATE_NONE));
  stateHash->Set(Symbol("MERGE"), Int(GIT_REPOSITORY_STATE_MERGE));
  stateHash->Set(Symbol("REVERT"), Int(GIT_REPOSITORY_STATE_REVERT));
  stateHash->Set(Symbol("CHERRY_PICK"), Int(GIT_REPOSITORY_STATE_CHERRY_PICK));
  stateHash->Set(Symbol("BISECT"), Int(GIT_REPOSITORY_STATE_BISECT));
  stateHash->Set(Symbol("REBASE"), Int(GIT_REPOSITORY_STATE_REBASE));
  stateHash->Set(Symbol("REBASE_INTERACTIVE"), Int(GIT_REPOSITORY_STATE_REBASE_INTERACTIVE));
  stateHash->Set(Symbol("REBASE_MERGE"), Int(GIT_REPOSITORY_STATE_REBASE_MERGE));
  stateHash->Set(Symbol("APPLY_MAILBOX"), Int(GIT_REPOSITORY_STATE_APPLY_MAILBOX));
  stateHash->Set(Symbol("APPLY_MAILBOX_OR_REBASE"), Int(GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE));
  func->Set(Symbol("State"), stateHash);

  //FLAG: init() options -- INIT
  Local<v8::Object> initFlagHash = v8u::Obj();
  initFlagHash->Set(Symbol("BARE"), Int(GIT_REPOSITORY_INIT_BARE));
  initFlagHash->Set(Symbol("NO_REINIT"), Int(GIT_REPOSITORY_INIT_NO_REINIT));
  initFlagHash->Set(Symbol("NO_DOTGIT_DIR"), Int(GIT_REPOSITORY_INIT_NO_DOTGIT_DIR));
  initFlagHash->Set(Symbol("MKDIR"), Int(GIT_REPOSITORY_INIT_MKDIR));
  initFlagHash->Set(Symbol("MKPATH"), Int(GIT_REPOSITORY_INIT_MKPATH));
  initFlagHash->Set(Symbol("EXTERNAL_TEMPLATE"), Int(GIT_REPOSITORY_INIT_EXTERNAL_TEMPLATE));
  func->Set(Symbol("InitFlag"), initFlagHash);

  //FLAG: init() mode options -- INIT_SHARED
  Local<v8::Object> initModeHash = v8u::Obj();
  initModeHash->Set(Symbol("SHARED_UMASK"), Int(GIT_REPOSITORY_INIT_SHARED_UMASK));
  initModeHash->Set(Symbol("SHARED_GROUP"), Int(GIT_REPOSITORY_INIT_SHARED_GROUP));
  initModeHash->Set(Symbol("SHARED_ALL"), Int(GIT_REPOSITORY_INIT_SHARED_ALL));
  func->Set(Symbol("InitMode"), initModeHash);

  //FLAG: open() options -- OPEN
  Local<v8::Object> openFlagHash = v8u::Obj();
  openFlagHash->Set(Symbol("NO_SEARCH"), Int(GIT_REPOSITORY_OPEN_NO_SEARCH));
  openFlagHash->Set(Symbol("CROSS_FS"), Int(GIT_REPOSITORY_OPEN_CROSS_FS));
  func->Set(Symbol("OpenFlag"), openFlagHash);

} NODE_TYPE_END()
V8_POST_TYPE(Repository)

};

<|endoftext|>


<commit_before>/************************************************
 *  segmenter.cpp
 *  ESA++
 *
 *  Copyright (c) 2014, Chi-En Wu
 *  Distributed under The BSD 3-Clause License
 ************************************************/

#include "segmenter.hpp"

namespace esapp
{

/************************************************
 * Implementation: class segmenter
 ************************************************/

segmenter::segmenter(double lrv_exp, size_t max_iters,
                     size_t max_len, double smooth)
    : counter_(lrv_exp, max_len, smooth), max_iters_(max_iters)
{
    // do nothing
}

std::vector<std::vector<std::wstring>> segmenter::fit_and_segment(
    std::vector<std::wstring> const &sequences)
{
    typedef decltype(fit_and_segment(sequences)) vec_type;
    typedef std::vector<std::wstring> words_type;
    return fit_and_segment(
        sequences,
        [this](std::wstring const &s) { return tokenize_iterator(s); },
        [](vec_type &v, words_type const &e) { v.push_back(e); });
}

std::vector<std::vector<std::string>> segmenter::fit_and_segment(
    std::vector<std::string> const &sequences)
{
    typedef decltype(fit_and_segment(sequences)) vec_type;
    typedef std::vector<std::wstring> words_type;
    std::wstring ws;
    return fit_and_segment(
        sequences,
        [this, &ws](std::string const &s) { ws = s2ws(s);
                                            return tokenize_iterator(ws); },
        [](vec_type &v, words_type const &e) { v.push_back(ws2s(e)); });
}

template <typename T, typename Tokenize, typename Append>
std::vector<std::vector<T>> segmenter::fit_and_segment(
    std::vector<T> const &sequences,
    Tokenize const &tokenize, Append const &append)
{
    // pre-segment sequences by alphabets, numbers, and symbols
    auto tokens = make_filter_iterator(
        [] (std::wstring const &token) { return ischs(token[0]); },
        make_flatten_iterator(
            make_map_iterator(tokenize, sequences)
        )
    );

    // construct substring counter
    counter_.fit(tokens.begin(), tokens.end());

    auto m = counter_.raw_string_count();
    std::vector<segment> prev_segs(m), segs(m);
    for (decltype(max_iters_) i = 0; i < max_iters_; ++i)
    {
        // segment sequences
        for (decltype(m) j = 0, p = 0; j < m; ++j)
        {
            auto n = counter_.raw_string_length(j);
            optimize_segment(segs[j], p, n);
            p += n + 1;
        }

        if (prev_segs == segs) { break; }

        // update substring counts
        for (decltype(m) j = 0, p = 0; j < m; ++j)
        {
            auto n = counter_.raw_string_length(j);
            if (i > 0)
            {
                counter_.unset_pres(prev_segs[j], p, n);
            }

            counter_.set_pres(segs[j], p, n);
            p += n + 1;
        }

        prev_segs.swap(segs);
    }

    // generate segmented word lists
    auto it = prev_segs.begin();
    decltype(fit_and_segment(sequences, tokenize, append)) words_list;
    words_list.reserve(sequences.size());
    for (auto const &sequence : sequences)
    {
        auto tokens = tokenize(sequence);
        std::vector<typename decltype(tokens)::value_type> words;
        for (auto const &token : tokens)
        {
            if (ischs(token[0]))    { segment_sequence(words, token, *it++); }
            else                    { words.push_back(token); }
        }

        append(words_list, words);
    }

    return words_list;
}

void segmenter::optimize_segment(segment &seg, size_t p, size_t n) const
{
    if (n == 0) { return; }

    std::vector<size_t> fs(n);
    std::vector<double> fv(n);
    for (decltype(n) i = 0; i < n; ++i)
    {
        fs[i] = 0;
        fv[i] = counter_.score(p, i + 1);
        for (decltype(i) j = 0; j < i; ++j)
        {
            auto cv = fv[j] * counter_.score(p + j + 1, i - j);
            if (cv > fv[i])
            {
                fv[i] = cv;
                fs[i] = j + 1;
            }
        }
    }

    seg.clear();
    for (auto i = fs[n - 1]; i > 0; i = fs[i - 1])
    {
        seg.push_back(i);
    }

    std::reverse(seg.begin(), seg.end());
}

void segmenter::segment_sequence(std::vector<std::wstring> &words,
                                 std::wstring const &sequence,
                                 segment const &seg) const
{
    segment::value_type start = 0;
    for (auto const &pos : seg)
    {
        auto word = sequence.substr(start, pos - start);
        words.push_back(word);
        start = pos;
    }

    auto word = sequence.substr(start);
    words.push_back(word);
}

std::vector<std::wstring> segmenter::segment_sequence(
    std::wstring const &sequence, segment const &seg) const
{
    decltype(segment_sequence(sequence, seg)) words;
    words.reserve(seg.size() + 1);
    segment_sequence(words, sequence, seg);
    return words;
}

} // namespace esapp
<commit_msg>No need to pass `this`<commit_after>/************************************************
 *  segmenter.cpp
 *  ESA++
 *
 *  Copyright (c) 2014, Chi-En Wu
 *  Distributed under The BSD 3-Clause License
 ************************************************/

#include "segmenter.hpp"

namespace esapp
{

/************************************************
 * Implementation: class segmenter
 ************************************************/

segmenter::segmenter(double lrv_exp, size_t max_iters,
                     size_t max_len, double smooth)
    : counter_(lrv_exp, max_len, smooth), max_iters_(max_iters)
{
    // do nothing
}

std::vector<std::vector<std::wstring>> segmenter::fit_and_segment(
    std::vector<std::wstring> const &sequences)
{
    typedef decltype(fit_and_segment(sequences)) vec_type;
    typedef std::vector<std::wstring> words_type;
    return fit_and_segment(
        sequences,
        [](std::wstring const &s) { return tokenize_iterator(s); },
        [](vec_type &v, words_type const &e) { v.push_back(e); });
}

std::vector<std::vector<std::string>> segmenter::fit_and_segment(
    std::vector<std::string> const &sequences)
{
    typedef decltype(fit_and_segment(sequences)) vec_type;
    typedef std::vector<std::wstring> words_type;
    std::wstring ws;
    return fit_and_segment(
        sequences,
        [&ws](std::string const &s) { ws = s2ws(s);
                                      return tokenize_iterator(ws); },
        [](vec_type &v, words_type const &e) { v.push_back(ws2s(e)); });
}

template <typename T, typename Tokenize, typename Append>
std::vector<std::vector<T>> segmenter::fit_and_segment(
    std::vector<T> const &sequences,
    Tokenize const &tokenize, Append const &append)
{
    // pre-segment sequences by alphabets, numbers, and symbols
    auto tokens = make_filter_iterator(
        [] (std::wstring const &token) { return ischs(token[0]); },
        make_flatten_iterator(
            make_map_iterator(tokenize, sequences)
        )
    );

    // construct substring counter
    counter_.fit(tokens.begin(), tokens.end());

    auto m = counter_.raw_string_count();
    std::vector<segment> prev_segs(m), segs(m);
    for (decltype(max_iters_) i = 0; i < max_iters_; ++i)
    {
        // segment sequences
        for (decltype(m) j = 0, p = 0; j < m; ++j)
        {
            auto n = counter_.raw_string_length(j);
            optimize_segment(segs[j], p, n);
            p += n + 1;
        }

        if (prev_segs == segs) { break; }

        // update substring counts
        for (decltype(m) j = 0, p = 0; j < m; ++j)
        {
            auto n = counter_.raw_string_length(j);
            if (i > 0)
            {
                counter_.unset_pres(prev_segs[j], p, n);
            }

            counter_.set_pres(segs[j], p, n);
            p += n + 1;
        }

        prev_segs.swap(segs);
    }

    // generate segmented word lists
    auto it = prev_segs.begin();
    decltype(fit_and_segment(sequences, tokenize, append)) words_list;
    words_list.reserve(sequences.size());
    for (auto const &sequence : sequences)
    {
        auto tokens = tokenize(sequence);
        std::vector<typename decltype(tokens)::value_type> words;
        for (auto const &token : tokens)
        {
            if (ischs(token[0]))    { segment_sequence(words, token, *it++); }
            else                    { words.push_back(token); }
        }

        append(words_list, words);
    }

    return words_list;
}

void segmenter::optimize_segment(segment &seg, size_t p, size_t n) const
{
    if (n == 0) { return; }

    std::vector<size_t> fs(n);
    std::vector<double> fv(n);
    for (decltype(n) i = 0; i < n; ++i)
    {
        fs[i] = 0;
        fv[i] = counter_.score(p, i + 1);
        for (decltype(i) j = 0; j < i; ++j)
        {
            auto cv = fv[j] * counter_.score(p + j + 1, i - j);
            if (cv > fv[i])
            {
                fv[i] = cv;
                fs[i] = j + 1;
            }
        }
    }

    seg.clear();
    for (auto i = fs[n - 1]; i > 0; i = fs[i - 1])
    {
        seg.push_back(i);
    }

    std::reverse(seg.begin(), seg.end());
}

void segmenter::segment_sequence(std::vector<std::wstring> &words,
                                 std::wstring const &sequence,
                                 segment const &seg) const
{
    segment::value_type start = 0;
    for (auto const &pos : seg)
    {
        auto word = sequence.substr(start, pos - start);
        words.push_back(word);
        start = pos;
    }

    auto word = sequence.substr(start);
    words.push_back(word);
}

std::vector<std::wstring> segmenter::segment_sequence(
    std::wstring const &sequence, segment const &seg) const
{
    decltype(segment_sequence(sequence, seg)) words;
    words.reserve(seg.size() + 1);
    segment_sequence(words, sequence, seg);
    return words;
}

} // namespace esapp
<|endoftext|>


<commit_before>/* $Id$ */

/*
 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 showslots.cpp

 Show the slots available in the HSM
 *****************************************************************************/

#include "showslots.h"
#include "cryptoki.h"
#include "error.h";

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern CK_FUNCTION_LIST_PTR p11;

int showSlots()
{
	CK_ULONG ulSlotCount;
	CK_RV rv = p11->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the number of slots. rv=%s\n", rv2string(rv));
		return 1;
	}

	CK_SLOT_ID_PTR pSlotList = (CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID));
	if (!pSlotList)
	{
		fprintf(stderr, "ERROR: Could not allocate memory.\n");
		return 1;
	}

	rv = p11->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the slot list. rv=%s\n", rv2string(rv));
		free(pSlotList);
		return 1;
	}

	printf("Available slots:\n");

	for (unsigned int i = 0; i < ulSlotCount; i++)
	{
		CK_SLOT_INFO slotInfo;
		CK_TOKEN_INFO tokenInfo;

		rv = p11->C_GetSlotInfo(pSlotList[i], &slotInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about slot %lu. rv=%s\n", pSlotList[i], rv2string(rv));
			continue;
		}

		printf("Slot %lu\n", pSlotList[i]);
		printf("    Slot info:\n");
		printf("        Description:      %.*s\n", 64, slotInfo.slotDescription);
		printf("        Manufacturer ID:  %.*s\n", 32, slotInfo.manufacturerID);
		printf("        Hardware version: %i.%i\n", slotInfo.hardwareVersion.major,
							    slotInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", slotInfo.firmwareVersion.major,
							    slotInfo.firmwareVersion.minor);
		printf("        Token present:    ");
		if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0)
		{
			printf("no\n");
			continue;
		}

		printf("yes\n");
		printf("    Token info:\n");

		rv = p11->C_GetTokenInfo(pSlotList[i], &tokenInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about the token in slot %lu. rv=%s\n",
				pSlotList[i], rv2string(rv));
			continue;
		}

		printf("        Manufacturer ID:  %.*s\n", 32, tokenInfo.manufacturerID);
		printf("        Model:            %.*s\n", 16, tokenInfo.model);
		printf("        Hardware version: %i.%i\n", tokenInfo.hardwareVersion.major,
							    tokenInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", tokenInfo.firmwareVersion.major,
							    tokenInfo.firmwareVersion.minor);
		printf("        Serial number:    %.*s\n", 16, tokenInfo.serialNumber);
		printf("        Initialized:      ");
		if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        User PIN init.:   ");
		if ((tokenInfo.flags & CKF_USER_PIN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        Label:            %.*s\n", 32, tokenInfo.label);
	}

	free(pSlotList);

	return 0;
}
<commit_msg>Remove extra character <commit_after>/* $Id$ */

/*
 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 showslots.cpp

 Show the slots available in the HSM
 *****************************************************************************/

#include "showslots.h"
#include "cryptoki.h"
#include "error.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern CK_FUNCTION_LIST_PTR p11;

int showSlots()
{
	CK_ULONG ulSlotCount;
	CK_RV rv = p11->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the number of slots. rv=%s\n", rv2string(rv));
		return 1;
	}

	CK_SLOT_ID_PTR pSlotList = (CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID));
	if (!pSlotList)
	{
		fprintf(stderr, "ERROR: Could not allocate memory.\n");
		return 1;
	}

	rv = p11->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the slot list. rv=%s\n", rv2string(rv));
		free(pSlotList);
		return 1;
	}

	printf("Available slots:\n");

	for (unsigned int i = 0; i < ulSlotCount; i++)
	{
		CK_SLOT_INFO slotInfo;
		CK_TOKEN_INFO tokenInfo;

		rv = p11->C_GetSlotInfo(pSlotList[i], &slotInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about slot %lu. rv=%s\n", pSlotList[i], rv2string(rv));
			continue;
		}

		printf("Slot %lu\n", pSlotList[i]);
		printf("    Slot info:\n");
		printf("        Description:      %.*s\n", 64, slotInfo.slotDescription);
		printf("        Manufacturer ID:  %.*s\n", 32, slotInfo.manufacturerID);
		printf("        Hardware version: %i.%i\n", slotInfo.hardwareVersion.major,
							    slotInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", slotInfo.firmwareVersion.major,
							    slotInfo.firmwareVersion.minor);
		printf("        Token present:    ");
		if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0)
		{
			printf("no\n");
			continue;
		}

		printf("yes\n");
		printf("    Token info:\n");

		rv = p11->C_GetTokenInfo(pSlotList[i], &tokenInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about the token in slot %lu. rv=%s\n",
				pSlotList[i], rv2string(rv));
			continue;
		}

		printf("        Manufacturer ID:  %.*s\n", 32, tokenInfo.manufacturerID);
		printf("        Model:            %.*s\n", 16, tokenInfo.model);
		printf("        Hardware version: %i.%i\n", tokenInfo.hardwareVersion.major,
							    tokenInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", tokenInfo.firmwareVersion.major,
							    tokenInfo.firmwareVersion.minor);
		printf("        Serial number:    %.*s\n", 16, tokenInfo.serialNumber);
		printf("        Initialized:      ");
		if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        User PIN init.:   ");
		if ((tokenInfo.flags & CKF_USER_PIN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        Label:            %.*s\n", 32, tokenInfo.label);
	}

	free(pSlotList);

	return 0;
}
<|endoftext|>


<commit_before>/*
  Handles the simulation part
*/
#pragma once

#include "scenario.hpp"

#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

// using namespace sim;
namespace sim {

class Simulator {
public:
    Simulator(std::string result_file) { running = false; }
    void restart_with(const Scenario scenario_)
    {
        if (scenario_.configuration) {
            running  = true;
            scenario = scenario_;

            jd = scenario.configuration->begin_jd;

            LOG_S(INFO) << "Starting simulation";
        }
    }
    void step();
    bool is_running() { return running; }

private:
    Scenario scenario;
    bool     running;
    double   jd;
};

void Simulator::step()
{
    if (running) {
        if (jd < scenario.configuration->end_jd) {
            // pretend to do something
            jd += scenario.configuration->step;
        } else {
            running = false;
            LOG_S(INFO) << "Stopping simulation";
        }
    }
}
}
<commit_msg>Implement loading of orrery files<commit_after>/*
  Handles the simulation part
*/
#pragma once

#include "scenario.hpp"
#include "spkorrery.hpp"

#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

// using namespace sim;
namespace sim {

class Simulator {
public:
    Simulator(std::string result_file) { running = false; }
    void restart_with(const Scenario scenario_)
    {
        if (scenario_.configuration) {
            running  = true;
            scenario = scenario_;

            jd = scenario.configuration->begin_jd;
            for (auto orrery_name : scenario.configuration->orrery) {
                orrery.load_orrery_model(
                    orrery_name,
                    scenario.configuration->begin_jd,
                    scenario.configuration->end_jd);
            }

            LOG_S(INFO) << "Starting simulation";
        }
    }
    void step();
    bool is_running() { return running; }

private:
    Scenario scenario;

    orrery::SpkOrrery orrery;

    bool   running;
    double jd;
};

void Simulator::step()
{
    if (running) {
        if (jd < scenario.configuration->end_jd) {
            // pretend to do something
            jd += scenario.configuration->step;
        } else {
            running = false;
            LOG_S(INFO) << "Stopping simulation";
        }
    }
}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2009, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "prefdb.h"
#include "composite.h"
#include <gdkmm.h>
#include <glibmm/i18n.h>

double red, green, blue, alpha, width;
std::list<Trace::Point> points;

Popup::Popup(int x1, int y1, int x2, int y2) : Gtk::Window(Gtk::WINDOW_POPUP), rect(x1, y1, x2-x1, y2-y1) {
	if (!is_composited())
		throw std::runtime_error(_("'composite' not available"));

	Glib::RefPtr<Gdk::Colormap> colormap = get_screen()->get_rgba_colormap();
	if (colormap)
		set_colormap(colormap);
	signal_expose_event().connect(sigc::mem_fun(*this, &Popup::on_expose));
	realize();
	move(x1, y1);
	resize(x2-x1, y2-y1);
	get_window()->input_shape_combine_region(Gdk::Region(), 0, 0);
	// tell compiz to leave this window the hell alone
	get_window()->set_type_hint(Gdk::WINDOW_TYPE_HINT_DESKTOP);
}

void Popup::invalidate(int x1, int y1, int x2, int y2) {
	if (is_mapped()) {
		Gdk::Rectangle inv(x1 - rect.get_x(), y1 - rect.get_y(), x2-x1, y2-y1);
		get_window()->invalidate_rect(inv, false);
	} else
		show();
}

Composite::Composite() {
#define N 128
	int w = gdk_screen_width();
	int h = gdk_screen_height();
	num_x = (gdk_screen_width()  - 1)/N + 1;
	num_y = (gdk_screen_height() - 1)/N + 1;
	pieces = new Popup**[num_x];
	for (int i = 0; i < num_x; i++) {
		pieces[i] = new Popup*[num_y];
		for (int j = 0; j < num_y; j++)
			pieces[i][j] = new Popup(i*N,j*N,MIN((i+1)*N,w),MIN((j+1)*N,h));

	}
}

void Composite::draw(Point p, Point q) {
	if (!points.size()) {
		points.push_back(p);
	}
	points.push_back(q);
	int x1 = (int)(p.x < q.x ? p.x : q.x);
	int x2 = (int)(p.x < q.x ? q.x : p.x);
	int y1 = (int)(p.y < q.y ? p.y : q.y);
	int y2 = (int)(p.y < q.y ? q.y : p.y);
	int bw = (int)(width/2.0) + 2;
	x1 -= bw; y1 -= bw;
	x2 += bw; y2 += bw;
	for (int i = x1/N; i<num_x && i<=x2/N; i++)
		for (int j = y1/N; j<num_y && j<=y2/N; j++)
			pieces[i][j]->invalidate(x1, y1, x2, y2);
}

void Composite::start_() {
	RGBA rgba = prefs.color.get();
	red = rgba.color.get_red_p();
	green = rgba.color.get_green_p();
	blue = rgba.color.get_blue_p();
	alpha = ((double)rgba.alpha)/65535.0;
	width = prefs.trace_width.get();
}

void Popup::draw_line(Cairo::RefPtr<Cairo::Context> ctx) {
	if (!points.size())
		return;
	std::list<Trace::Point>::iterator i = points.begin();
	ctx->move_to (i->x, i->y);
	for (; i != points.end(); i++)
		ctx->line_to (i->x, i->y);
	ctx->set_source_rgba((red+0.5)/2.0, (green+0.5)/2.0, (blue+0.5)/2.0, alpha/2.0);
	ctx->set_line_width(width+1.0);
	ctx->set_line_cap(Cairo::LINE_CAP_ROUND);
	ctx->set_line_join(Cairo::LINE_JOIN_ROUND);
	ctx->stroke_preserve();

	ctx->set_source_rgba(red, green, blue, alpha);
	ctx->set_line_width(width*0.7);
	ctx->stroke();

}

bool Popup::on_expose(GdkEventExpose* event) {
	Cairo::RefPtr<Cairo::Context> ctx = get_window()->create_cairo_context();
	ctx->set_operator(Cairo::OPERATOR_SOURCE);

	Gdk::Region region(event->region, true);
	Gdk::Cairo::add_region_to_path(ctx, region);
	ctx->clip();

	Gdk::Cairo::add_region_to_path(ctx, region);
	ctx->set_source_rgba(0.0, 0.0, 0.0, 0.0);
	ctx->fill();

	ctx->translate(-rect.get_x(), -rect.get_y());
	draw_line(ctx);

	return false;
}

void Composite::end_() {
	points.clear();
	for (int i = 0; i < num_x; i++)
		for (int j = 0; j < num_y; j++)
			pieces[i][j]->hide();
}

Composite::~Composite() {
	for (int i = 0; i < num_x; i++) {
		for (int j = 0; j < num_y; j++)
			delete pieces[i][j];
		delete[] pieces[i];
	}
	delete[] pieces;
}
<commit_msg>Bounds checking<commit_after>/*
 * Copyright (c) 2008-2009, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "prefdb.h"
#include "composite.h"
#include <gdkmm.h>
#include <glibmm/i18n.h>

double red, green, blue, alpha, width;
std::list<Trace::Point> points;

Popup::Popup(int x1, int y1, int x2, int y2) : Gtk::Window(Gtk::WINDOW_POPUP), rect(x1, y1, x2-x1, y2-y1) {
	if (!is_composited())
		throw std::runtime_error(_("'composite' not available"));

	Glib::RefPtr<Gdk::Colormap> colormap = get_screen()->get_rgba_colormap();
	if (colormap)
		set_colormap(colormap);
	signal_expose_event().connect(sigc::mem_fun(*this, &Popup::on_expose));
	realize();
	move(x1, y1);
	resize(x2-x1, y2-y1);
	get_window()->input_shape_combine_region(Gdk::Region(), 0, 0);
	// tell compiz to leave this window the hell alone
	get_window()->set_type_hint(Gdk::WINDOW_TYPE_HINT_DESKTOP);
}

void Popup::invalidate(int x1, int y1, int x2, int y2) {
	if (is_mapped()) {
		Gdk::Rectangle inv(x1 - rect.get_x(), y1 - rect.get_y(), x2-x1, y2-y1);
		get_window()->invalidate_rect(inv, false);
	} else
		show();
}

Composite::Composite() {
#define N 128
	int w = gdk_screen_width();
	int h = gdk_screen_height();
	num_x = (gdk_screen_width()  - 1)/N + 1;
	num_y = (gdk_screen_height() - 1)/N + 1;
	pieces = new Popup**[num_x];
	for (int i = 0; i < num_x; i++) {
		pieces[i] = new Popup*[num_y];
		for (int j = 0; j < num_y; j++)
			pieces[i][j] = new Popup(i*N,j*N,MIN((i+1)*N,w),MIN((j+1)*N,h));

	}
}

void Composite::draw(Point p, Point q) {
	if (!points.size()) {
		points.push_back(p);
	}
	points.push_back(q);
	int x1 = (int)(p.x < q.x ? p.x : q.x);
	int x2 = (int)(p.x < q.x ? q.x : p.x);
	int y1 = (int)(p.y < q.y ? p.y : q.y);
	int y2 = (int)(p.y < q.y ? q.y : p.y);
	int bw = (int)(width/2.0) + 2;
	x1 -= bw; y1 -= bw;
	x2 += bw; y2 += bw;
	if (x1 < 0)
		x1 = 0;
	if (y1 < 0)
		y1 = 0;
	for (int i = x1/N; i<num_x && i<=x2/N; i++)
		for (int j = y1/N; j<num_y && j<=y2/N; j++)
			pieces[i][j]->invalidate(x1, y1, x2, y2);
}

void Composite::start_() {
	RGBA rgba = prefs.color.get();
	red = rgba.color.get_red_p();
	green = rgba.color.get_green_p();
	blue = rgba.color.get_blue_p();
	alpha = ((double)rgba.alpha)/65535.0;
	width = prefs.trace_width.get();
}

void Popup::draw_line(Cairo::RefPtr<Cairo::Context> ctx) {
	if (!points.size())
		return;
	std::list<Trace::Point>::iterator i = points.begin();
	ctx->move_to (i->x, i->y);
	for (; i != points.end(); i++)
		ctx->line_to (i->x, i->y);
	ctx->set_source_rgba((red+0.5)/2.0, (green+0.5)/2.0, (blue+0.5)/2.0, alpha/2.0);
	ctx->set_line_width(width+1.0);
	ctx->set_line_cap(Cairo::LINE_CAP_ROUND);
	ctx->set_line_join(Cairo::LINE_JOIN_ROUND);
	ctx->stroke_preserve();

	ctx->set_source_rgba(red, green, blue, alpha);
	ctx->set_line_width(width*0.7);
	ctx->stroke();

}

bool Popup::on_expose(GdkEventExpose* event) {
	Cairo::RefPtr<Cairo::Context> ctx = get_window()->create_cairo_context();
	ctx->set_operator(Cairo::OPERATOR_SOURCE);

	Gdk::Region region(event->region, true);
	Gdk::Cairo::add_region_to_path(ctx, region);
	ctx->clip();

	Gdk::Cairo::add_region_to_path(ctx, region);
	ctx->set_source_rgba(0.0, 0.0, 0.0, 0.0);
	ctx->fill();

	ctx->translate(-rect.get_x(), -rect.get_y());
	draw_line(ctx);

	return false;
}

void Composite::end_() {
	points.clear();
	for (int i = 0; i < num_x; i++)
		for (int j = 0; j < num_y; j++)
			pieces[i][j]->hide();
}

Composite::~Composite() {
	for (int i = 0; i < num_x; i++) {
		for (int j = 0; j < num_y; j++)
			delete pieces[i][j];
		delete[] pieces[i];
	}
	delete[] pieces;
}
<|endoftext|>


<commit_before>#include "YASegmenter.h"
#include "MT/MT_Core/gl/glSupport.h"  // for blob drawing

#include <algorithm>  // for sort and unique

BlobberParameters::BlobberParameters(int* val_thresh_low,
                                     int* val_thresh_high,
                                     int* area_thresh_low,
                                     int* area_thresh_high,
                                     bool* testbool,
                                     double* testdouble)
  : MT_DataGroup("Blobber Parameters")
{

    AddInt("Diff Thresh Low", val_thresh_low, MT_DATA_READWRITE, 0, 512);
    AddInt("Diff Thresh High", val_thresh_high, MT_DATA_READWRITE, 1, 512);
    AddInt("Area Thresh Low", area_thresh_low, MT_DATA_READWRITE, 0);
    AddInt("Area Thresh High", area_thresh_high, MT_DATA_READWRITE, 0);
    AddBool("Test Bool", testbool);
    AddDouble("Test Double", testdouble);

}

BlobberFrameGroup::BlobberFrameGroup(IplImage** diff_frame, IplImage** thresh_frame)
{

    StandardFrameGroupInit(2);

    m_vFrameNames[0] = "Diff Frame";
    m_vFrameNames[1] = "Threshold Frame";

    m_vFrames[0] = diff_frame;
    m_vFrames[1] = thresh_frame;

}

BlobInfoReport::BlobInfoReport(std::vector<int>* indexes,
                               std::vector<double>* Xs,
                               std::vector<double>* Ys,
                               std::vector<double>* Areas,
                               std::vector<double>* Orientations)
  : MT_DataReport("Blob Info")
{

    AddInt("Index", indexes);
    AddDouble("X [px]", Xs);
    AddDouble("Y [px]", Ys);
    AddDouble("Area [px]", Areas);
    AddDouble("Orientation [deg]", Orientations);

}

/*************************************************************/
# pragma mark -
# pragma mark Segmenter

Segmenter::Segmenter(IplImage* ProtoFrame)
  : m_Blobber(false)
{

    Init(ProtoFrame);

}

void segmenterTestMe(GLfloat x, GLfloat y)
{
  fprintf(stdout, "Printing (%f, %f)\n", x, y);
}

void Segmenter::Init(IplImage* ProtoFrame)
{

    /* frame group initialization */
    m_pTrackerFrameGroup = new BlobberFrameGroup(&diff_frame, &thresh_frame);

    blob_val_thresh_low = RT_MIN_BLOB_VAL;
    blob_val_thresh_high = RT_MAX_BLOB_VAL;
    blob_area_thresh_low = RT_MIN_BLOB_SIZE;
    blob_area_thresh_high = RT_MAX_BLOB_SIZE;

    test_bool = true;
    test_double = 3.1415926;

    m_vDataGroups.resize(0);
    m_vDataGroups.push_back(new BlobberParameters(&blob_val_thresh_low, &blob_val_thresh_high, &blob_area_thresh_low, &blob_area_thresh_high, &test_bool, &test_double));

    BlobIndexes.resize(0);
    XBlobs.resize(0);
    YBlobs.resize(0);
    ABlobs.resize(0);
    OBlobs.resize(0);

    m_vDataReports.resize(0);
    m_vDataReports.push_back(new BlobInfoReport(&BlobIndexes, &XBlobs, &YBlobs, &ABlobs, &OBlobs));

    BG_frame = 0;
    GS_frame = 0;
    diff_frame = 0;
    thresh_frame = 0;
    ROI_frame = 0;

    frame_counter = 0;
    NFound = 0;

    if(ProtoFrame)
    {
        train(ProtoFrame);
    }
    else
    {
        FrameWidth = 0;
        FrameHeight = 0;
    }

    //m_pBlobFile = NULL;

    m_YABlobs.resize(0);

}

Segmenter::~Segmenter()
{

    //delete m_pBlobFile;

    if(BG_frame)
    {
        cvReleaseImage(&BG_frame);
        cvReleaseImage(&GS_frame);
        cvReleaseImage(&diff_frame);
        cvReleaseImage(&thresh_frame);
    }
    /* note ~TrackerCore will release ROI_frame */
}

void Segmenter::train(IplImage* frame)
{

    // TODO Should really check this against the ROI frame if it exists

    CvSize framesize = cvSize(frame->width,frame->height);

    FrameWidth = frame->width;
    FrameHeight = frame->height;

    createFrames();

    if(frame->nChannels == 3)
    {
        cvCvtColor(frame, BG_frame, CV_BGR2GRAY);
    } else {
        cvCopy(frame, BG_frame);
    }

}

void Segmenter::createFrames()
{

    CvSize framesize = cvSize(FrameWidth, FrameHeight);

    if(BG_frame)
    {
        cvReleaseImage(&BG_frame);
        cvReleaseImage(&GS_frame);
        cvReleaseImage(&diff_frame);
        cvReleaseImage(&thresh_frame);
    }

    BG_frame = cvCreateImage(framesize, IPL_DEPTH_8U, 1);
    GS_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);
    diff_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);
    thresh_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);

}

void Segmenter::doMeasurement()
{

    // get the blob centroids and areas
    XBlobs = blobs.GetSTLResult( MT_CBlobGetXCenterOfMass() );
    YBlobs = blobs.GetSTLResult( MT_CBlobGetYCenterOfMass() );
    ABlobs = blobs.GetSTLResult( CBlobGetArea() );
    // translate from image coordinates
    for(unsigned int k = 0; k < NFound; k++)
    {
        YBlobs[k] = FrameHeight - YBlobs[k];
    }

}

void Segmenter::setBlobFile(const char* blobfilename, const char* description)
{

    /*if(!m_pBlobFile)
    {
        m_pBlobFile = new BlobFile(blobfilename, description, FrameWidth, FrameHeight);
    }*/

}

void Segmenter::setDiffThreshLow(int newThresh)
{
    blob_val_thresh_low = newThresh;
}

void Segmenter::setAreaThreshLow(int newThresh)
{
    blob_area_thresh_low = newThresh;
}

void Segmenter::setAreaThreshHigh(int newThresh)
{
    blob_area_thresh_high = newThresh;
}

int Segmenter::getDiffThreshLow()
{
    return blob_val_thresh_low;
}

int Segmenter::getAreaThreshLow()
{
    return blob_area_thresh_low;
}

int Segmenter::getAreaThreshHigh()
{
    return blob_area_thresh_high;
}

void Segmenter::doImageProcessing()
{

    // Find regions that are darker than the background
    //   - first, mark pixels that are darker into a binary image
    //    (note we hijack the thresh_frame for the result, since it is temporary)
    cvCmp(BG_frame,GS_frame,thresh_frame,CV_CMP_GT);
    //   - second, find the absolute value of the difference between the images
    cvAbsDiff(BG_frame,GS_frame,diff_frame);
    //   - then, AND with the binary image to keep the difference only for darker pixels
    cvAnd(diff_frame,thresh_frame,diff_frame);

    if(ROI_frame)   // only if the ROI has been specified
    {
        printf("Apply ROI frame\n");
        //   - also AND with the ROI to make sure that blobs are only found inside the tank
        cvAnd(diff_frame,ROI_frame,diff_frame);
    }

    // Find the threshold of the difference
    cvThreshold(diff_frame, thresh_frame, blob_val_thresh_low, 255.0, CV_THRESH_BINARY);

}

void Segmenter::doSegmentation()
{

    // Use the blob finding algorithm to find the blobs based on trhesholding
    //   the difference frame
    if(ROI_frame)
    {
        blobs = CBlobResult(thresh_frame, ROI_frame, 0);
    } else {
        blobs = CBlobResult(thresh_frame, RT_NOMASK, 0);
    }

#ifdef TRACKER_VERBOSE
    for(unsigned int i = 0; i < blobs.GetNumBlobs(); i++)
    {
        printf("Unfiltered Blob %d, Area = %f, at (%f, %f) with orientation %f\n",i,
               blobs.GetNumber( i, CBlobGetArea() ),
               blobs.GetNumber( i, CBlobGetXCenter() ),
               blobs.GetNumber( i, CBlobGetYCenter() ),
               blobs.GetNumber( i, MT_CBlobGetHeadOrientation() ) );
    }
#endif

    // Get rid of blobs that are either too big or too small
    blobs.Filter(blobs, B_INCLUDE, CBlobGetArea(), B_GREATER, blob_area_thresh_low);
    blobs.Filter(blobs, B_INCLUDE, CBlobGetArea(), B_LESS, blob_area_thresh_high);
    // Certain conditions tend to generate a blob with this property - delete it
    blobs.Filter(blobs, B_EXCLUDE, CBlobGetXCenter(), B_EQUAL, 0.5*((double) thresh_frame->width) + 0.5 );

#ifdef TRACKER_VERBOSE
    for(unsigned int i = 0; i < blobs.GetNumBlobs(); i++)
    {
        printf("Filtered Blob %d, Area = %f, at (%f, %f) with orientation %f\n",i,
               blobs.GetNumber( i, CBlobGetArea() ),
               blobs.GetNumber( i, CBlobGetXCenter() ),
               blobs.GetNumber( i, CBlobGetYCenter() ),
               blobs.GetNumber( i, MT_CBlobGetHeadOrientation() ) );
    }
#endif

    // How many blobs did we find on first pass?
    NFound = blobs.GetNumBlobs();

}

void Segmenter::doMeasurementWithYABlobs()
{

    BlobIndexes.resize(NFound);
    XBlobs.resize(NFound);
    YBlobs.resize(NFound);
    ABlobs.resize(NFound);
    OBlobs.resize(NFound);

    for(unsigned int i = 0; i < NFound; i++)
    {
        BlobIndexes[i] = i;
        XBlobs[i] = m_YABlobs[i].COMx;
        YBlobs[i] = m_YABlobs[i].COMy;
        ABlobs[i] = m_YABlobs[i].area;
        OBlobs[i] = m_YABlobs[i].orientation;
    }

}

// Main Tracking Function - this is the main workhorse.
void Segmenter::doTracking(IplImage* frame)
{
    //printf("thresh low %d\n area low %d\n bool %d\n double %f\n", blob_val_thresh_low, blob_area_thresh_low, test_bool, test_double);

    static double t_previous = MT_getTimeSec();

    double dt;
    double t_now = MT_getTimeSec();

    dt = t_now - t_previous;  /// TODO for an AVI, dt should be constant

    //dt = 0.04;
    t_previous = t_now;

    frame_counter++;

    // Keep a copy of the original frame pointer for display purposes
    org_frame = frame;

    // Convert to grayscale if necessary
	if(frame->nChannels == 3)
    {
        cvCvtColor(frame, GS_frame, CV_BGR2GRAY);
    } else {
        cvCopy(frame, GS_frame);
    }

    double t0 = MT_getTimeSec();

    // image operations to extract regions where fish are likely
    //  e.g. background substitution, thresholding
    doImageProcessing();

    // image segmentation - i.e. blob detection
    //DoSegmentation();
    // data association and assignment
    //DoMeasurement();

    double t1 = MT_getTimeSec();
    //printf("Image Processing %f\n", t1-t0);

    t0 = MT_getTimeSec();

    m_YABlobs = m_Blobber.FindBlobs(thresh_frame, 10, blob_area_thresh_low);
    t1 = MT_getTimeSec();
    //printf("Blobbing %f\n", t1-t0);
    NFound = m_YABlobs.size();
    doMeasurementWithYABlobs();

    /*if(m_pBlobFile)
    {
        m_pBlobFile->WriteBlobs(frame_counter, dt, blobs);
    }*/

}

void Segmenter::glDraw(bool DrawBlobs)
{

    MT_R3 blobcenter;
	MT_InitGLLists();

    if(DrawBlobs)
    {
        /*   for(int i = 0; i < blobs.GetNumBlobs(); i++)
             {

             blobcenter.setx( blobs.GetNumber(i, MT_CBlobGetXCenterOfMass()));
             blobcenter.sety( FrameHeight - blobs.GetNumber(i, MT_CBlobGetYCenterOfMass()));
             blobcenter.setz( 0 );

             DrawArrow( blobcenter,
             1.5*blobs.GetNumber(i, CBlobGetMajorAxisLength()),
             MT_DEG2RAD*blobs.GetNumber(i, MT_CBlobGetHeadOrientation()),
             MT_Green,
             1.0 // fixed arrow width
             );
             }*/

        for(int i = 0; i < m_YABlobs.size(); i++)
        {

            blobcenter.setx(m_YABlobs[i].COMx);
            blobcenter.sety(FrameHeight-m_YABlobs[i].COMy);
            blobcenter.setz( 0.0 );

			//fprintf(stdout, "I'm drawing to (%f, %f)\n", m_YABlobs[i].COMx, FrameHeight - m_YABlobs[i].COMy);
            MT_DrawArrow( blobcenter,
                       1.5*m_YABlobs[i].area,
                       MT_DEG2RAD*m_YABlobs[i].orientation,
                       MT_Red,
                       1.0 // fixed arrow width
                );

        }
    }

}

void Segmenter::doGLDrawing(int flags)
{

    glDraw(flags > 0);

}
<commit_msg>Eliminated some debug print statements<commit_after>#include "YASegmenter.h"
#include "MT/MT_Core/gl/glSupport.h"  // for blob drawing

#include <algorithm>  // for sort and unique

BlobberParameters::BlobberParameters(int* val_thresh_low,
                                     int* val_thresh_high,
                                     int* area_thresh_low,
                                     int* area_thresh_high,
                                     bool* testbool,
                                     double* testdouble)
  : MT_DataGroup("Blobber Parameters")
{

    AddInt("Diff Thresh Low", val_thresh_low, MT_DATA_READWRITE, 0, 512);
    AddInt("Diff Thresh High", val_thresh_high, MT_DATA_READWRITE, 1, 512);
    AddInt("Area Thresh Low", area_thresh_low, MT_DATA_READWRITE, 0);
    AddInt("Area Thresh High", area_thresh_high, MT_DATA_READWRITE, 0);
    AddBool("Test Bool", testbool);
    AddDouble("Test Double", testdouble);

}

BlobberFrameGroup::BlobberFrameGroup(IplImage** diff_frame, IplImage** thresh_frame)
{

    StandardFrameGroupInit(2);

    m_vFrameNames[0] = "Diff Frame";
    m_vFrameNames[1] = "Threshold Frame";

    m_vFrames[0] = diff_frame;
    m_vFrames[1] = thresh_frame;

}

BlobInfoReport::BlobInfoReport(std::vector<int>* indexes,
                               std::vector<double>* Xs,
                               std::vector<double>* Ys,
                               std::vector<double>* Areas,
                               std::vector<double>* Orientations)
  : MT_DataReport("Blob Info")
{

    AddInt("Index", indexes);
    AddDouble("X [px]", Xs);
    AddDouble("Y [px]", Ys);
    AddDouble("Area [px]", Areas);
    AddDouble("Orientation [deg]", Orientations);

}

/*************************************************************/
# pragma mark -
# pragma mark Segmenter

Segmenter::Segmenter(IplImage* ProtoFrame)
  : m_Blobber(false)
{

    Init(ProtoFrame);

}

void Segmenter::Init(IplImage* ProtoFrame)
{

    /* frame group initialization */
    m_pTrackerFrameGroup = new BlobberFrameGroup(&diff_frame, &thresh_frame);

    blob_val_thresh_low = RT_MIN_BLOB_VAL;
    blob_val_thresh_high = RT_MAX_BLOB_VAL;
    blob_area_thresh_low = RT_MIN_BLOB_SIZE;
    blob_area_thresh_high = RT_MAX_BLOB_SIZE;

    test_bool = true;
    test_double = 3.1415926;

    m_vDataGroups.resize(0);
    m_vDataGroups.push_back(new BlobberParameters(&blob_val_thresh_low, &blob_val_thresh_high, &blob_area_thresh_low, &blob_area_thresh_high, &test_bool, &test_double));

    BlobIndexes.resize(0);
    XBlobs.resize(0);
    YBlobs.resize(0);
    ABlobs.resize(0);
    OBlobs.resize(0);

    m_vDataReports.resize(0);
    m_vDataReports.push_back(new BlobInfoReport(&BlobIndexes, &XBlobs, &YBlobs, &ABlobs, &OBlobs));

    BG_frame = 0;
    GS_frame = 0;
    diff_frame = 0;
    thresh_frame = 0;
    ROI_frame = 0;

    frame_counter = 0;
    NFound = 0;

    if(ProtoFrame)
    {
        train(ProtoFrame);
    }
    else
    {
        FrameWidth = 0;
        FrameHeight = 0;
    }

    //m_pBlobFile = NULL;

    m_YABlobs.resize(0);

}

Segmenter::~Segmenter()
{

    //delete m_pBlobFile;

    if(BG_frame)
    {
        cvReleaseImage(&BG_frame);
        cvReleaseImage(&GS_frame);
        cvReleaseImage(&diff_frame);
        cvReleaseImage(&thresh_frame);
    }
    /* note ~TrackerCore will release ROI_frame */
}

void Segmenter::train(IplImage* frame)
{

    // TODO Should really check this against the ROI frame if it exists

    CvSize framesize = cvSize(frame->width,frame->height);

    FrameWidth = frame->width;
    FrameHeight = frame->height;

    createFrames();

    if(frame->nChannels == 3)
    {
        cvCvtColor(frame, BG_frame, CV_BGR2GRAY);
    } else {
        cvCopy(frame, BG_frame);
    }

}

void Segmenter::createFrames()
{

    CvSize framesize = cvSize(FrameWidth, FrameHeight);

    if(BG_frame)
    {
        cvReleaseImage(&BG_frame);
        cvReleaseImage(&GS_frame);
        cvReleaseImage(&diff_frame);
        cvReleaseImage(&thresh_frame);
    }

    BG_frame = cvCreateImage(framesize, IPL_DEPTH_8U, 1);
    GS_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);
    diff_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);
    thresh_frame = cvCreateImage(framesize, IPL_DEPTH_8U,1);

}

void Segmenter::doMeasurement()
{

    // get the blob centroids and areas
    XBlobs = blobs.GetSTLResult( MT_CBlobGetXCenterOfMass() );
    YBlobs = blobs.GetSTLResult( MT_CBlobGetYCenterOfMass() );
    ABlobs = blobs.GetSTLResult( CBlobGetArea() );
    // translate from image coordinates
    for(unsigned int k = 0; k < NFound; k++)
    {
        YBlobs[k] = FrameHeight - YBlobs[k];
    }

}

void Segmenter::setBlobFile(const char* blobfilename, const char* description)
{

    /*if(!m_pBlobFile)
    {
        m_pBlobFile = new BlobFile(blobfilename, description, FrameWidth, FrameHeight);
    }*/

}

void Segmenter::setDiffThreshLow(int newThresh)
{
    blob_val_thresh_low = newThresh;
}

void Segmenter::setAreaThreshLow(int newThresh)
{
    blob_area_thresh_low = newThresh;
}

void Segmenter::setAreaThreshHigh(int newThresh)
{
    blob_area_thresh_high = newThresh;
}

int Segmenter::getDiffThreshLow()
{
    return blob_val_thresh_low;
}

int Segmenter::getAreaThreshLow()
{
    return blob_area_thresh_low;
}

int Segmenter::getAreaThreshHigh()
{
    return blob_area_thresh_high;
}

void Segmenter::doImageProcessing()
{

    // Find regions that are darker than the background
    //   - first, mark pixels that are darker into a binary image
    //    (note we hijack the thresh_frame for the result, since it is temporary)
    cvCmp(BG_frame,GS_frame,thresh_frame,CV_CMP_GT);
    //   - second, find the absolute value of the difference between the images
    cvAbsDiff(BG_frame,GS_frame,diff_frame);
    //   - then, AND with the binary image to keep the difference only for darker pixels
    cvAnd(diff_frame,thresh_frame,diff_frame);

    if(ROI_frame)   // only if the ROI has been specified
    {
        printf("Apply ROI frame\n");
        //   - also AND with the ROI to make sure that blobs are only found inside the tank
        cvAnd(diff_frame,ROI_frame,diff_frame);
    }

    // Find the threshold of the difference
    cvThreshold(diff_frame, thresh_frame, blob_val_thresh_low, 255.0, CV_THRESH_BINARY);

}

void Segmenter::doSegmentation()
{

    // Use the blob finding algorithm to find the blobs based on trhesholding
    //   the difference frame
    if(ROI_frame)
    {
        blobs = CBlobResult(thresh_frame, ROI_frame, 0);
    } else {
        blobs = CBlobResult(thresh_frame, RT_NOMASK, 0);
    }

#ifdef TRACKER_VERBOSE
    for(unsigned int i = 0; i < blobs.GetNumBlobs(); i++)
    {
        printf("Unfiltered Blob %d, Area = %f, at (%f, %f) with orientation %f\n",i,
               blobs.GetNumber( i, CBlobGetArea() ),
               blobs.GetNumber( i, CBlobGetXCenter() ),
               blobs.GetNumber( i, CBlobGetYCenter() ),
               blobs.GetNumber( i, MT_CBlobGetHeadOrientation() ) );
    }
#endif

    // Get rid of blobs that are either too big or too small
    blobs.Filter(blobs, B_INCLUDE, CBlobGetArea(), B_GREATER, blob_area_thresh_low);
    blobs.Filter(blobs, B_INCLUDE, CBlobGetArea(), B_LESS, blob_area_thresh_high);
    // Certain conditions tend to generate a blob with this property - delete it
    blobs.Filter(blobs, B_EXCLUDE, CBlobGetXCenter(), B_EQUAL, 0.5*((double) thresh_frame->width) + 0.5 );

#ifdef TRACKER_VERBOSE
    for(unsigned int i = 0; i < blobs.GetNumBlobs(); i++)
    {
        printf("Filtered Blob %d, Area = %f, at (%f, %f) with orientation %f\n",i,
               blobs.GetNumber( i, CBlobGetArea() ),
               blobs.GetNumber( i, CBlobGetXCenter() ),
               blobs.GetNumber( i, CBlobGetYCenter() ),
               blobs.GetNumber( i, MT_CBlobGetHeadOrientation() ) );
    }
#endif

    // How many blobs did we find on first pass?
    NFound = blobs.GetNumBlobs();

}

void Segmenter::doMeasurementWithYABlobs()
{

    BlobIndexes.resize(NFound);
    XBlobs.resize(NFound);
    YBlobs.resize(NFound);
    ABlobs.resize(NFound);
    OBlobs.resize(NFound);

    for(unsigned int i = 0; i < NFound; i++)
    {
        BlobIndexes[i] = i;
        XBlobs[i] = m_YABlobs[i].COMx;
        YBlobs[i] = m_YABlobs[i].COMy;
        ABlobs[i] = m_YABlobs[i].area;
        OBlobs[i] = m_YABlobs[i].orientation;
    }

}

// Main Tracking Function - this is the main workhorse.
void Segmenter::doTracking(IplImage* frame)
{
    //printf("thresh low %d\n area low %d\n bool %d\n double %f\n", blob_val_thresh_low, blob_area_thresh_low, test_bool, test_double);

    static double t_previous = MT_getTimeSec();

    double dt;
    double t_now = MT_getTimeSec();

    dt = t_now - t_previous;  /// TODO for an AVI, dt should be constant

    //dt = 0.04;
    t_previous = t_now;

    frame_counter++;

    // Keep a copy of the original frame pointer for display purposes
    org_frame = frame;

    // Convert to grayscale if necessary
	if(frame->nChannels == 3)
    {
        cvCvtColor(frame, GS_frame, CV_BGR2GRAY);
    } else {
        cvCopy(frame, GS_frame);
    }

    double t0 = MT_getTimeSec();

    // image operations to extract regions where fish are likely
    //  e.g. background substitution, thresholding
    doImageProcessing();

    // image segmentation - i.e. blob detection
    //DoSegmentation();
    // data association and assignment
    //DoMeasurement();

    double t1 = MT_getTimeSec();
    //printf("Image Processing %f\n", t1-t0);

    t0 = MT_getTimeSec();

    m_YABlobs = m_Blobber.FindBlobs(thresh_frame, 10, blob_area_thresh_low);
    t1 = MT_getTimeSec();
    //printf("Blobbing %f\n", t1-t0);
    NFound = m_YABlobs.size();
    doMeasurementWithYABlobs();

    /*if(m_pBlobFile)
    {
        m_pBlobFile->WriteBlobs(frame_counter, dt, blobs);
    }*/

}

void Segmenter::glDraw(bool DrawBlobs)
{

    MT_R3 blobcenter;
	MT_InitGLLists();

    if(DrawBlobs)
    {
        /*   for(int i = 0; i < blobs.GetNumBlobs(); i++)
             {

             blobcenter.setx( blobs.GetNumber(i, MT_CBlobGetXCenterOfMass()));
             blobcenter.sety( FrameHeight - blobs.GetNumber(i, MT_CBlobGetYCenterOfMass()));
             blobcenter.setz( 0 );

             DrawArrow( blobcenter,
             1.5*blobs.GetNumber(i, CBlobGetMajorAxisLength()),
             MT_DEG2RAD*blobs.GetNumber(i, MT_CBlobGetHeadOrientation()),
             MT_Green,
             1.0 // fixed arrow width
             );
             }*/

        for(int i = 0; i < m_YABlobs.size(); i++)
        {

            blobcenter.setx(m_YABlobs[i].COMx);
            blobcenter.sety(FrameHeight-m_YABlobs[i].COMy);
            blobcenter.setz( 0.0 );

            MT_DrawArrow( blobcenter,
                       1.5*m_YABlobs[i].area,
                       MT_DEG2RAD*m_YABlobs[i].orientation,
                       MT_Red,
                       1.0 // fixed arrow width
                );

        }
    }

}

void Segmenter::doGLDrawing(int flags)
{

    glDraw(flags > 0);

}
<|endoftext|>


<commit_before>#include <Windows.h>
#include <cstdio>
#include <cstring>

using namespace std;

enum DisplaySelection {
	DS_MONITOR = 1,
	DS_HDMI = 2,
	DS_TOGGLE = 3,
};

/* This array must match the above enum */
char *DisplaySelectionString[] = {
	"Monitor",
	"HDMI",
	"Toggle",
};

#define MAX_PATH_ELEMENTS 128
#define MAX_MODE_ELEMENTS 8

int main(int argc, char *argv[])
{
	LONG retval;
	DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS];
	DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS];
	UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]);
	UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]);
	UINT32 hdmi_idx = MAX_PATH_ELEMENTS;
	UINT32 dvi_idx = MAX_PATH_ELEMENTS;
	DisplaySelection current_selection = DS_TOGGLE;

	retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL);

	if (ERROR_SUCCESS != retval) {
		printf("Query failure - unable to set new path!!\n");
		return 2;
	}

	/* Find the target paths we care about */
	for (unsigned int path = 0; path < numPathElements; path++) {
		if (pathArray[path].sourceInfo.modeInfoIdx >= 0
			&& pathArray[path].sourceInfo.modeInfoIdx < numModeElements) {

			if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI)
				&& (pathArray[path].targetInfo.targetAvailable == TRUE)) {
				hdmi_idx = path;
				if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags)
					current_selection = DS_HDMI;
			}
			else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI)
				&& (pathArray[path].targetInfo.targetAvailable == TRUE)) {
				dvi_idx = path;
				if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags)
					current_selection = DS_MONITOR;
			}
		}
	}
	if (current_selection == DS_TOGGLE) {
		printf("Unable to determine current video output -- exiting\n");
		return 3;
	}

	/* No argument means toggle output */
	unsigned int input = DS_TOGGLE;
	DISPLAYCONFIG_PATH_INFO desiredSettings;

	/* Try to get the desired output setting */
	if (argc > 1) {
		input = atoi(argv[1]);
	}

	/* input should match the enum above. indexed into the string array as (input - 1) */
	if ((input - 1) < (sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]))) {
		printf("Device to be selected is the %s selection.\n", DisplaySelectionString[input - 1]);
		if ((DS_MONITOR == input && current_selection == DS_HDMI) || (DS_TOGGLE == input && DS_HDMI == current_selection)) {
			if (dvi_idx < MAX_PATH_ELEMENTS)
				desiredSettings = pathArray[dvi_idx];
			else {
				printf("Attempting to switch to DVI, but unable to find config element -- exiting\n");
				return 4;
			}
		}
		else if ((DS_HDMI == input && current_selection == DS_MONITOR) || (DS_TOGGLE == input && DS_MONITOR == current_selection))
		{
			if (hdmi_idx < MAX_PATH_ELEMENTS)
				desiredSettings = pathArray[hdmi_idx];
			else {
				printf("Attempting to switch to HDMI, but unable to find config element -- exiting\n");
				return 5;
			}
		}
		else
		{
			printf("Output already set to the desired selection.\n");
			return 0;
		}
	}
	else
	{
		printf("Unknown display selection: %d\n\n", input);
		printf("Usage:\n");
		printf("\tDisplayController_Config.exe [new_output]\n");
		for (int i = 0; i < sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]); i++) {
			printf("\t\t%d: %s\n", i + 1, DisplaySelectionString[i]);
		}
		printf("\n\tNo parameter means Toggle\n");
		return 1;
	}

	/* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */
	desiredSettings.flags = DISPLAYCONFIG_PATH_ACTIVE;
	desiredSettings.targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
	desiredSettings.sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
	retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES);

	if (ERROR_SUCCESS != retval) {
		printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n");
		retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES |
													SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG);
		if (ERROR_SUCCESS != retval) {
			printf("Unable to set the new display config!!\n");
			return 3;
		}
	}

	return 0;
}<commit_msg>Added error message for insufficient buffer<commit_after>#include <Windows.h>
#include <cstdio>
#include <cstring>

using namespace std;

enum DisplaySelection {
	DS_MONITOR = 1,
	DS_HDMI = 2,
	DS_TOGGLE = 3,
};

/* This array must match the above enum */
char *DisplaySelectionString[] = {
	"Monitor",
	"HDMI",
	"Toggle",
};

#define MAX_PATH_ELEMENTS 128
#define MAX_MODE_ELEMENTS 8

int main(int argc, char *argv[])
{
	LONG retval;
	DISPLAYCONFIG_PATH_INFO pathArray[MAX_PATH_ELEMENTS];
	DISPLAYCONFIG_MODE_INFO modeArray[MAX_MODE_ELEMENTS];
	UINT32 numPathElements = sizeof(pathArray)/sizeof(pathArray[0]);
	UINT32 numModeElements = sizeof(modeArray)/sizeof(modeArray[0]);
	UINT32 hdmi_idx = MAX_PATH_ELEMENTS;
	UINT32 dvi_idx = MAX_PATH_ELEMENTS;
	DisplaySelection current_selection = DS_TOGGLE;

	retval = QueryDisplayConfig(QDC_ALL_PATHS, &numPathElements, pathArray, &numModeElements, modeArray, NULL);

	if (ERROR_SUCCESS != retval) {
		printf("Query failure - unable to set new path!!\n");
		if (ERROR_INSUFFICIENT_BUFFER == retval)
			printf("Insufficient buffer failure; increase MAX_PATH_ELEMENTS or MAX_MODE_ELEMENTS and re-compile.");
		return 2;
	}

	/* Find the target paths we care about */
	for (unsigned int path = 0; path < numPathElements; path++) {
		if (pathArray[path].sourceInfo.modeInfoIdx >= 0
			&& pathArray[path].sourceInfo.modeInfoIdx < numModeElements) {

			if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI)
				&& (pathArray[path].targetInfo.targetAvailable == TRUE)) {
				hdmi_idx = path;
				if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags)
					current_selection = DS_HDMI;
			}
			else if ((pathArray[path].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI)
				&& (pathArray[path].targetInfo.targetAvailable == TRUE)) {
				dvi_idx = path;
				if (DISPLAYCONFIG_PATH_ACTIVE & pathArray[path].flags)
					current_selection = DS_MONITOR;
			}
		}
	}
	if (current_selection == DS_TOGGLE) {
		printf("Unable to determine current video output -- exiting\n");
		return 3;
	}

	/* No argument means toggle output */
	unsigned int input = DS_TOGGLE;
	DISPLAYCONFIG_PATH_INFO desiredSettings;

	/* Try to get the desired output setting */
	if (argc > 1) {
		input = atoi(argv[1]);
	}

	/* input should match the enum above. indexed into the string array as (input - 1) */
	if ((input - 1) < (sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]))) {
		printf("Device to be selected is the %s selection.\n", DisplaySelectionString[input - 1]);
		if ((DS_MONITOR == input && current_selection == DS_HDMI) || (DS_TOGGLE == input && DS_HDMI == current_selection)) {
			if (dvi_idx < MAX_PATH_ELEMENTS)
				desiredSettings = pathArray[dvi_idx];
			else {
				printf("Attempting to switch to DVI, but unable to find config element -- exiting\n");
				return 4;
			}
		}
		else if ((DS_HDMI == input && current_selection == DS_MONITOR) || (DS_TOGGLE == input && DS_MONITOR == current_selection))
		{
			if (hdmi_idx < MAX_PATH_ELEMENTS)
				desiredSettings = pathArray[hdmi_idx];
			else {
				printf("Attempting to switch to HDMI, but unable to find config element -- exiting\n");
				return 5;
			}
		}
		else
		{
			printf("Output already set to the desired selection.\n");
			return 0;
		}
	}
	else
	{
		printf("Unknown display selection: %d\n\n", input);
		printf("Usage:\n");
		printf("\tDisplayController_Config.exe [new_output]\n");
		for (int i = 0; i < sizeof(DisplaySelectionString) / sizeof(DisplaySelectionString[0]); i++) {
			printf("\t\t%d: %s\n", i + 1, DisplaySelectionString[i]);
		}
		printf("\n\tNo parameter means Toggle\n");
		return 1;
	}

	/* If we get here we will attempt to set the path -- let SetDisplayConfig pick the mode info */
	desiredSettings.flags = DISPLAYCONFIG_PATH_ACTIVE;
	desiredSettings.targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
	desiredSettings.sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
	retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_APPLY | SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_PATH_ORDER_CHANGES);

	if (ERROR_SUCCESS != retval) {
		printf("Unable to set -- trying again with SetDisplayConfig creating mode info\n");
		retval = SetDisplayConfig(1, &desiredSettings, 0, NULL, SDC_TOPOLOGY_SUPPLIED | SDC_ALLOW_CHANGES |
													SDC_ALLOW_PATH_ORDER_CHANGES |SDC_USE_SUPPLIED_DISPLAY_CONFIG);
		if (ERROR_SUCCESS != retval) {
			printf("Unable to set the new display config!!\n");
			return 3;
		}
	}

	return 0;
}<|endoftext|>