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

#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"

#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "views/fill_layout.h"

// Some of this class is implemented in tab_contents_container.cc, where
// the implementation doesn't vary between a pure views approach and a
// native view host approach. See the header file for details.

////////////////////////////////////////////////////////////////////////////////
// TabContentsContainer, public:

TabContentsContainer::TabContentsContainer()
    : tab_contents_(NULL) {
  SetID(VIEW_ID_TAB_CONTAINER);
}

void TabContentsContainer::SetReservedContentsRect(
    const gfx::Rect& reserved_rect) {
  cached_reserved_rect_ = reserved_rect;
  // TODO(anicolao): find out what this is supposed to be used for and ensure
  // it's OK for touch.
}

void TabContentsContainer::ChangeTabContents(TabContents* contents) {
  if (tab_contents_) {
    views::View *v = static_cast<TabContentsViewViews*>(tab_contents_->view());
    RemoveChildView(v);
    tab_contents_->WasHidden();
    RemoveObservers();
  }
  tab_contents_ = contents;
  // When detaching the last tab of the browser ChangeTabContents is invoked
  // with NULL. Don't attempt to do anything in that case.
  if (tab_contents_) {
    views::View *v = static_cast<TabContentsViewViews*>(contents->view());
    AddChildView(v);
    SetLayoutManager(new views::FillLayout());
    Layout();
    AddObservers();
  }
}

void TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {
}

void TabContentsContainer::SetFastResize(bool fast_resize) {
}

void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,
                                                 RenderViewHost* new_host) {
  NOTIMPLEMENTED();  // TODO(anicolao)
}
<commit_msg>Do not include GTK file on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"

#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "views/fill_layout.h"

#if defined(OS_LINUX)
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"
#endif

// Some of this class is implemented in tab_contents_container.cc, where
// the implementation doesn't vary between a pure views approach and a
// native view host approach. See the header file for details.

////////////////////////////////////////////////////////////////////////////////
// TabContentsContainer, public:

TabContentsContainer::TabContentsContainer()
    : tab_contents_(NULL) {
  SetID(VIEW_ID_TAB_CONTAINER);
}

void TabContentsContainer::SetReservedContentsRect(
    const gfx::Rect& reserved_rect) {
  cached_reserved_rect_ = reserved_rect;
  // TODO(anicolao): find out what this is supposed to be used for and ensure
  // it's OK for touch.
}

void TabContentsContainer::ChangeTabContents(TabContents* contents) {
  if (tab_contents_) {
    views::View *v = static_cast<TabContentsViewViews*>(tab_contents_->view());
    RemoveChildView(v);
    tab_contents_->WasHidden();
    RemoveObservers();
  }
  tab_contents_ = contents;
  // When detaching the last tab of the browser ChangeTabContents is invoked
  // with NULL. Don't attempt to do anything in that case.
  if (tab_contents_) {
    views::View *v = static_cast<TabContentsViewViews*>(contents->view());
    AddChildView(v);
    SetLayoutManager(new views::FillLayout());
    Layout();
    AddObservers();
  }
}

void TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {
}

void TabContentsContainer::SetFastResize(bool fast_resize) {
}

void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,
                                                 RenderViewHost* new_host) {
  NOTIMPLEMENTED();  // TODO(anicolao)
}
<|endoftext|>


<commit_before>/*
  Copyright 2017 Barcelona Supercomputing Center (www.bsc.es)

  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 "persistent_cache.h"

static int cached_object_init(cached_object* self,
  PyObject *args, PyObject *kwds) {
    return 0;
}

static void cached_object_dealloc(cached_object* self) {
  Py_DECREF(self->obj);
  Py_XDECREF(self->comparison_function);
}

bool _default_comparison_function(const cached_object& a,  const cached_object& b) {
  if(a.hit_count != b.hit_count) {
    return a.hit_count < b.hit_count;
  }
  if(a.last_hit_time != b.last_hit_time) {
    return a.last_hit_time < b.last_hit_time;
  }
  return a.id < b.id;
}

static PyObject* default_comparison_function(PyObject* self, PyObject* args) {
  PyObject* a;
  PyObject* b;
  if(!Py_BuildValue("OO", &a, &b)) {
    return NULL;
  }
  cached_object* _a = (cached_object*)a;
  cached_object* _b = (cached_object*)b;
  return PyBool_FromLong(_default_comparison_function(*_a, *_b));
}

static PyObject*
cached_object_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
  cached_object* self = (cached_object*)type->tp_alloc(type, 0);
  const char* object_id;

  if(!PyArg_ParseTuple(args, "sOlOl", &object_id, &self->obj, &self->object_size,
  &self->comparison_function, &self->last_hit_time)) {
    return NULL;
  }
  Py_INCREF(self->obj);
  Py_XINCREF(self->comparison_function);
  self->id = std::string(object_id);
  return (PyObject*)self;
}

static PyObject* cached_object_get_id(PyObject* self, PyObject* args) {
  cached_object* _self = (cached_object*)self;
  return PyString_FromStringAndSize(_self->id.c_str(), _self->id.size());
}

static PyObject* cached_object_get_obj(PyObject* self, PyObject* args) {
  cached_object* _self = (cached_object*)self;
  return _self->obj;
}

void _delete_element(Cache* c, cached_object* obj) {
  c->current_size -= obj->object_size;
  c->H->erase(obj->id);
  Py_DECREF(obj->obj);
  Py_XDECREF(obj->comparison_function);
  c->S->erase(*obj);
}

void _delete_first_element(Cache* c) {
  cached_object* first_element = (cached_object*)&*(c->S->begin());
  _delete_element(c, first_element);
}

static void Cache_dealloc(Cache* self) {
  while(!self->S->empty()) _delete_first_element(self);
  delete(self->S);
  delete(self->H);
  Py_XDECREF(self->comparator);
}

static int Cache_init(Cache* self, PyObject* args, PyObject* kwds) {
  return 0;
}

static PyObject* Cache_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
  Cache* self = (Cache*)type->tp_alloc(type, 0);
  self->S = new std::set< cached_object, cached_object_comparator >();
  self->H = new std::map< std::string, cached_object >();
  self->current_time = 0ll;
  self->size_limit = 1024*1024*1024ll;
  static char* kwlist[] = {(char*)"size_limit", (char*)"comparison_function"};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|lO", kwlist, &self->size_limit,
  &self->comparator)) {
         return NULL;
  }
  Py_XINCREF(self->comparator);
  return (PyObject*)self;
}

static PyObject* Cache_add(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* object_id;
  PyObject* obj_to_add;
  long long object_size = -1ll;
  if(!PyArg_ParseTuple(args, "sO|l", &object_id, &obj_to_add, &object_size)) {
    return NULL;
  }
  cached_object to_add = *(new cached_object());
  to_add.id = std::string(object_id);
  if(_self->H->count(to_add.id)) {
    std::string err_msg = "Object with id " + to_add.id + " is\
    already cached!";
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  to_add.obj = obj_to_add;
  if(object_size == -1ll) {
    // rough approximation to the object's size (only invoked when obj size is
    // not given by the user)
    object_size = sizeof(*obj_to_add);
  }
  // Delete the object with least priority until cache is empty or
  // the total used space is less than the limit
  // Note that this operation can delete the most recent object
  // depending on the comparison function
  while(!_self->S->empty() && _self->current_size >= _self->size_limit) {
    _delete_first_element(_self);
  }
  // Does this object fit on cache?
  // If yes, add it and then update the total used cache space
  if(_self->current_size + object_size <= _self->size_limit) {
    to_add.object_size = object_size;
    to_add.hit_count = 1;
    to_add.last_hit_time = _self->current_time;
    to_add.comparison_function = _self->comparator;
    Py_XINCREF(_self->comparator);
    Py_INCREF(to_add.obj);
    _self->current_size += to_add.object_size;
    std::map< std::string, cached_object >& map_ref = *_self->H;
    map_ref[to_add.id] = to_add;
    _self->S->insert(map_ref[to_add.id]);
  }
  ++_self->current_time;
  Py_RETURN_NONE;
}

bool _has_object(Cache* self, std::string id) {
  return self->H->count(id);
}

static PyObject* Cache_has_object(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  return PyBool_FromLong(_has_object(_self, std::string(to_query)));
}

static PyObject* Cache_hit(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*) self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string object_id(to_query);
  if(!_has_object(_self, object_id)) {
    std::string err_msg = "Cache does not contain object with id " +
    object_id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  cached_object& cached_friend = map_ref[object_id];
  // As a remark: an std::set cannot know when some of its objects changes in
  // such a way that its ordering also does, so it must be removed and then
  // re-added in order to ensure that it is in a proper place inside the set
  _self->S->erase(cached_friend);
  ++cached_friend.hit_count;
  cached_friend.last_hit_time = _self->current_time;
  _self->S->insert(cached_friend);
  ++_self->current_time;
  Py_RETURN_NONE;
}

static PyObject* Cache_get(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string id(to_query);
  if(!_has_object(_self, id)) {
    std::string err_msg = "Cache does not contain object with id " +
    id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  PyObject* ret = map_ref[id].obj;
  Py_INCREF(ret);
  return ret;
}

static PyObject* Cache_delete(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*) self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string id(to_query);
  if(!_has_object(_self, id)) {
    std::string err_msg = "Cache does not contain object with id " +
    id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  cached_object& cached_friend = map_ref[id];
  _delete_element(_self, &cached_friend);
  Py_RETURN_NONE;
}

static PyObject* Cache_get_last(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  cached_object ret = *_self->S->begin();
  Py_INCREF(ret.obj);
  return ret.obj;
}

static PyObject* Cache_is_empty(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  return PyBool_FromLong(_self->S->empty());
}

static PyObject* Cache_set_object(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  PyObject* new_obj;
  long long new_object_size = -1;
  if(!PyArg_ParseTuple(args, "sO|l", &to_query, &new_obj, &new_object_size)) {
    return NULL;
  }
  if(new_object_size == -1) {
    new_object_size = sizeof(*new_obj);
  }
  std::string id(to_query);
  std::map< std::string, cached_object >& map_ref = *_self->H;
  // let's get the cached_object that contains our target object
  // and remove it from the priority set
  cached_object& cached_friend = map_ref[id];
  long long old_object_size = cached_friend.object_size;
  _self->S->erase(cached_friend);
  Py_DECREF(cached_friend.obj);
  // update the data structure with the new object
  cached_friend.obj = new_obj;
  Py_INCREF(cached_friend.obj);
  cached_friend.object_size = new_object_size;
  _self->current_size -= old_object_size;
  _self->current_size += new_object_size;
  _self->S->insert(cached_friend);
  // a new object may have its size modified (for example, it we append stuff
  // to some list). Let's be sure that this modification do not violate the
  // cache invariant
  while(!_self->S->empty() && _self->current_size >= _self->size_limit) {
    _delete_first_element(_self);
  }
  Py_RETURN_NONE;
}

PyMODINIT_FUNC initpersistent_cache(void) {
    PyObject* m;
    m = Py_InitModule("persistent_cache", module_methods);

    if (PyType_Ready(&cached_objectType) < 0)
        return;
    Py_INCREF(&cached_objectType);
    PyModule_AddObject(m, "cached_object", (PyObject*)&cached_objectType);

    if (PyType_Ready(&CacheType) < 0)
        return;
    Py_INCREF(&CacheType);
    PyModule_AddObject(m, "Cache", (PyObject*)&CacheType);
}
<commit_msg>add explanatory comments to the size approximation in set_object<commit_after>/*
  Copyright 2017 Barcelona Supercomputing Center (www.bsc.es)

  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 "persistent_cache.h"

static int cached_object_init(cached_object* self,
  PyObject *args, PyObject *kwds) {
    return 0;
}

static void cached_object_dealloc(cached_object* self) {
  Py_DECREF(self->obj);
  Py_XDECREF(self->comparison_function);
}

bool _default_comparison_function(const cached_object& a,  const cached_object& b) {
  if(a.hit_count != b.hit_count) {
    return a.hit_count < b.hit_count;
  }
  if(a.last_hit_time != b.last_hit_time) {
    return a.last_hit_time < b.last_hit_time;
  }
  return a.id < b.id;
}

static PyObject* default_comparison_function(PyObject* self, PyObject* args) {
  PyObject* a;
  PyObject* b;
  if(!Py_BuildValue("OO", &a, &b)) {
    return NULL;
  }
  cached_object* _a = (cached_object*)a;
  cached_object* _b = (cached_object*)b;
  return PyBool_FromLong(_default_comparison_function(*_a, *_b));
}

static PyObject*
cached_object_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
  cached_object* self = (cached_object*)type->tp_alloc(type, 0);
  const char* object_id;

  if(!PyArg_ParseTuple(args, "sOlOl", &object_id, &self->obj, &self->object_size,
  &self->comparison_function, &self->last_hit_time)) {
    return NULL;
  }
  Py_INCREF(self->obj);
  Py_XINCREF(self->comparison_function);
  self->id = std::string(object_id);
  return (PyObject*)self;
}

static PyObject* cached_object_get_id(PyObject* self, PyObject* args) {
  cached_object* _self = (cached_object*)self;
  return PyString_FromStringAndSize(_self->id.c_str(), _self->id.size());
}

static PyObject* cached_object_get_obj(PyObject* self, PyObject* args) {
  cached_object* _self = (cached_object*)self;
  return _self->obj;
}

void _delete_element(Cache* c, cached_object* obj) {
  c->current_size -= obj->object_size;
  c->H->erase(obj->id);
  Py_DECREF(obj->obj);
  Py_XDECREF(obj->comparison_function);
  c->S->erase(*obj);
}

void _delete_first_element(Cache* c) {
  cached_object* first_element = (cached_object*)&*(c->S->begin());
  _delete_element(c, first_element);
}

static void Cache_dealloc(Cache* self) {
  while(!self->S->empty()) _delete_first_element(self);
  delete(self->S);
  delete(self->H);
  Py_XDECREF(self->comparator);
}

static int Cache_init(Cache* self, PyObject* args, PyObject* kwds) {
  return 0;
}

static PyObject* Cache_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
  Cache* self = (Cache*)type->tp_alloc(type, 0);
  self->S = new std::set< cached_object, cached_object_comparator >();
  self->H = new std::map< std::string, cached_object >();
  self->current_time = 0ll;
  self->size_limit = 1024*1024*1024ll;
  static char* kwlist[] = {(char*)"size_limit", (char*)"comparison_function"};
  if (!PyArg_ParseTupleAndKeywords(args, kwds, "|lO", kwlist, &self->size_limit,
  &self->comparator)) {
         return NULL;
  }
  Py_XINCREF(self->comparator);
  return (PyObject*)self;
}

static PyObject* Cache_add(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* object_id;
  PyObject* obj_to_add;
  long long object_size = -1ll;
  if(!PyArg_ParseTuple(args, "sO|l", &object_id, &obj_to_add, &object_size)) {
    return NULL;
  }
  cached_object to_add = *(new cached_object());
  to_add.id = std::string(object_id);
  if(_self->H->count(to_add.id)) {
    std::string err_msg = "Object with id " + to_add.id + " is\
    already cached!";
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  to_add.obj = obj_to_add;
  if(object_size == -1ll) {
    // rough approximation to the object's size (only invoked when obj size is
    // not given by the user)
    object_size = sizeof(*obj_to_add);
  }
  // Delete the object with least priority until cache is empty or
  // the total used space is less than the limit
  // Note that this operation can delete the most recent object
  // depending on the comparison function
  while(!_self->S->empty() && _self->current_size >= _self->size_limit) {
    _delete_first_element(_self);
  }
  // Does this object fit on cache?
  // If yes, add it and then update the total used cache space
  if(_self->current_size + object_size <= _self->size_limit) {
    to_add.object_size = object_size;
    to_add.hit_count = 1;
    to_add.last_hit_time = _self->current_time;
    to_add.comparison_function = _self->comparator;
    Py_XINCREF(_self->comparator);
    Py_INCREF(to_add.obj);
    _self->current_size += to_add.object_size;
    std::map< std::string, cached_object >& map_ref = *_self->H;
    map_ref[to_add.id] = to_add;
    _self->S->insert(map_ref[to_add.id]);
  }
  ++_self->current_time;
  Py_RETURN_NONE;
}

bool _has_object(Cache* self, std::string id) {
  return self->H->count(id);
}

static PyObject* Cache_has_object(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  return PyBool_FromLong(_has_object(_self, std::string(to_query)));
}

static PyObject* Cache_hit(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*) self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string object_id(to_query);
  if(!_has_object(_self, object_id)) {
    std::string err_msg = "Cache does not contain object with id " +
    object_id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  cached_object& cached_friend = map_ref[object_id];
  // As a remark: an std::set cannot know when some of its objects changes in
  // such a way that its ordering also does, so it must be removed and then
  // re-added in order to ensure that it is in a proper place inside the set
  _self->S->erase(cached_friend);
  ++cached_friend.hit_count;
  cached_friend.last_hit_time = _self->current_time;
  _self->S->insert(cached_friend);
  ++_self->current_time;
  Py_RETURN_NONE;
}

static PyObject* Cache_get(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string id(to_query);
  if(!_has_object(_self, id)) {
    std::string err_msg = "Cache does not contain object with id " +
    id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  PyObject* ret = map_ref[id].obj;
  Py_INCREF(ret);
  return ret;
}

static PyObject* Cache_delete(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*) self;
  const char* to_query;
  if(!PyArg_ParseTuple(args, "s", &to_query)) {
    return NULL;
  }
  std::string id(to_query);
  if(!_has_object(_self, id)) {
    std::string err_msg = "Cache does not contain object with id " +
    id;
    PyErr_SetString(PyExc_KeyError, err_msg.c_str());
    return NULL;
  }
  std::map< std::string, cached_object >& map_ref = *_self->H;
  cached_object& cached_friend = map_ref[id];
  _delete_element(_self, &cached_friend);
  Py_RETURN_NONE;
}

static PyObject* Cache_get_last(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  cached_object ret = *_self->S->begin();
  Py_INCREF(ret.obj);
  return ret.obj;
}

static PyObject* Cache_is_empty(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  return PyBool_FromLong(_self->S->empty());
}

static PyObject* Cache_set_object(PyObject* self, PyObject* args) {
  Cache* _self = (Cache*)self;
  const char* to_query;
  PyObject* new_obj;
  long long new_object_size = -1;
  if(!PyArg_ParseTuple(args, "sO|l", &to_query, &new_obj, &new_object_size)) {
    return NULL;
  }
  // same as add method, this is intended to be a rough approximation
  // to the object's size and its only used if the object size is not
  // provided as a parameter
  if(new_object_size == -1) {
    new_object_size = sizeof(*new_obj);
  }
  std::string id(to_query);
  std::map< std::string, cached_object >& map_ref = *_self->H;
  // let's get the cached_object that contains our target object
  // and remove it from the priority set
  cached_object& cached_friend = map_ref[id];
  long long old_object_size = cached_friend.object_size;
  _self->S->erase(cached_friend);
  Py_DECREF(cached_friend.obj);
  // update the data structure with the new object
  cached_friend.obj = new_obj;
  Py_INCREF(cached_friend.obj);
  cached_friend.object_size = new_object_size;
  _self->current_size -= old_object_size;
  _self->current_size += new_object_size;
  _self->S->insert(cached_friend);
  // a new object may have its size modified (for example, it we append stuff
  // to some list). Let's be sure that this modification do not violate the
  // cache invariant
  while(!_self->S->empty() && _self->current_size >= _self->size_limit) {
    _delete_first_element(_self);
  }
  Py_RETURN_NONE;
}

PyMODINIT_FUNC initpersistent_cache(void) {
    PyObject* m;
    m = Py_InitModule("persistent_cache", module_methods);

    if (PyType_Ready(&cached_objectType) < 0)
        return;
    Py_INCREF(&cached_objectType);
    PyModule_AddObject(m, "cached_object", (PyObject*)&cached_objectType);

    if (PyType_Ready(&CacheType) < 0)
        return;
    Py_INCREF(&CacheType);
    PyModule_AddObject(m, "Cache", (PyObject*)&CacheType);
}
<|endoftext|>


<commit_before>/**
 * Problem description:      Given a linked list, sort it using insertion sort.
 * Solution time complexity: O(n^2)
 * Comments:
 */

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    ListNode *insertionSortList(ListNode *head)
    {
        auto dummy = ListNode{ 0 };
        auto node  = head;

        while (node != nullptr)
        {
            auto next = node->next;
            auto dest = &dummy;

            while (dest->next != nullptr && node->val > dest->next->val) {
                dest = dest->next;
            }

            node->next = dest->next;
            dest->next = node;

            node       = next;
        }

        return dummy.next;
    }
};
<commit_msg>Update solution.cpp<commit_after>/**
 * Problem description:      Given a linked list, sort it using insertion sort.
 * Solution time complexity: O(n^2)
 * Comments:                 Dummy node technique is used to facilitate sorting.
 */

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    ListNode *insertionSortList(ListNode *head)
    {
        auto dummy = ListNode{ 0 };
        auto node  = head;

        while (node != nullptr)
        {
            auto next = node->next;
            auto dest = &dummy;

            while (dest->next != nullptr && node->val > dest->next->val) {
                dest = dest->next;
            }

            node->next = dest->next;
            dest->next = node;

            node       = next;
        }

        return dummy.next;
    }
};
<|endoftext|>


<commit_before>/* Copyright 2016 Samsung Electronics Co., LTD
 *
 * 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 "daydream_renderer.h"
#include "glm/gtc/matrix_inverse.hpp"

namespace {
    static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;
    static const int kDefaultFboResolution = 1024;

    // Use the same default clipping distances as the perspective camera
    // TODO: Change this to read the values from the gvr.xml file
    static const float kZNear = 0.1f;
    static const float kZFar = 1000.0f;

    static glm::mat4 MatrixToGLMMatrix(const gvr::Mat4f &matrix) {
        glm::mat4 result;
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 4; ++j) {
                result[i][j] = matrix.m[i][j];
            }
        }
        return result;
    }

    static gvr::Rectf ModulateRect(const gvr::Rectf &rect, float width,
                                   float height) {
        gvr::Rectf result = {rect.left * width, rect.right * width,
                             rect.bottom * height, rect.top * height};
        return result;
    }

    static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei &texture_size,
                                              const gvr::Rectf &texture_rect) {
        const float width = static_cast<float>(texture_size.width);
        const float height = static_cast<float>(texture_size.height);
        const gvr::Rectf rect = ModulateRect(texture_rect, width, height);
        const gvr::Recti result = {
                static_cast<int>(rect.left), static_cast<int>(rect.right),
                static_cast<int>(rect.bottom), static_cast<int>(rect.top)};
        return result;
    }

    static void CheckGLError(const char *label) {
        int gl_error = glGetError();
        if (gl_error != GL_NO_ERROR) {
            LOGW("GL error @ %s: %d", label, gl_error);
            // Crash immediately to make OpenGL errors obvious.
            abort();
        }
    }

}  // namespace

DaydreamRenderer::DaydreamRenderer(JNIEnv &env, jclass clazz,
                                   gvr_context *gvr_context)
        : gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),
          scratch_viewport_(gvr_api_->CreateBufferViewport()) {
    jclass rendererClass = env.GetObjectClass(clazz);
    rendererObject_ = env.NewGlobalRef(clazz);
    onDrawEyeMethodId_ = env.GetMethodID(rendererClass, "onDrawEye", "(I)V");
    env.DeleteLocalRef(rendererClass);
}

DaydreamRenderer::~DaydreamRenderer() {
}

void DaydreamRenderer::InitializeGl() {
    gvr_api_->InitializeGl();

    //@todo read gvr.xml and obtain the values from EyeBufferParams
    render_size_.height = kDefaultFboResolution;
    render_size_.width = 2*kDefaultFboResolution;
    std::vector <gvr::BufferSpec> specs;
    specs.push_back(gvr_api_->CreateBufferSpec());
    specs.push_back(gvr_api_->CreateBufferSpec());

    specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
    specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);
    specs[0].SetSize(render_size_);
    specs[0].SetSamples(2);

    specs[1].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
    specs[1].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);
    specs[1].SetSize(render_size_);
    specs[1].SetSamples(2);
    swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));

    viewport_list_.reset(new gvr::BufferViewportList(
            gvr_api_->CreateEmptyBufferViewportList()));
    scratch_viewport_list_.reset(new gvr::BufferViewportList(
            gvr_api_->CreateEmptyBufferViewportList()));

}

void DaydreamRenderer::DrawFrame(JNIEnv &env) {
    // use the scratch list to get the recommended viewports
    scratch_viewport_list_->SetToRecommendedBufferViewports();

    // construct FBO backed viewports
    gvr::BufferViewport fbo_viewport = gvr_api_->CreateBufferViewport();

    scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);
    fbo_viewport.SetSourceBufferIndex(0);
    fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());
    fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());
    fbo_viewport.SetSourceUv(scratch_viewport_.GetSourceUv());
    fbo_viewport.SetTargetEye(GVR_LEFT_EYE);
    viewport_list_->SetBufferViewport(0, fbo_viewport);

    scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);
    fbo_viewport.SetSourceBufferIndex(1);
    fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());
    fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());
    fbo_viewport.SetSourceUv(scratch_viewport_.GetSourceUv());
    fbo_viewport.SetTargetEye(GVR_RIGHT_EYE);
    viewport_list_->SetBufferViewport(1, fbo_viewport);

    gvr::Frame frame = swapchain_->AcquireFrame();

    gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();
    target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;

    head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);

    cameraRig_->getHeadTransform()->setModelMatrix(MatrixToGLMMatrix(head_view_));

    // Render the eye images.
    for (int eye = 0; eye < 2; eye++) {
        frame.BindBuffer(eye);
        viewport_list_->GetBufferViewport(eye, &scratch_viewport_);
        SetViewport(scratch_viewport_);
        env.CallVoidMethod(rendererObject_, onDrawEyeMethodId_, eye);
        frame.Unbind();
    }

    // Submit frame.
    frame.Submit(*viewport_list_, head_view_);

    CheckGLError("onDrawFrame");
}

void DaydreamRenderer::OnPause() {
    gvr_api_->PauseTracking();
}

void DaydreamRenderer::OnResume() {
    gvr_api_->RefreshViewerProfile();
    gvr_api_->ResumeTracking();
}

void DaydreamRenderer::OnDestroy(JNIEnv &env) {
    env.DeleteGlobalRef(rendererObject_);
    delete cameraRig_;
}

void DaydreamRenderer::SetViewport(const gvr::BufferViewport &viewport) {
    const gvr::Recti pixel_rect = CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());

    glViewport(pixel_rect.left, pixel_rect.bottom,
               pixel_rect.right - pixel_rect.left,
               pixel_rect.top - pixel_rect.bottom);

    CheckGLError("SetViewport");
}

void DaydreamRenderer::SetCameraRig(jlong native_camera) {
    cameraRig_ = reinterpret_cast<gvr::CameraRig *>(native_camera);
    scratch_viewport_list_->SetToRecommendedBufferViewports();

    scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);
    SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->left_camera(), scratch_viewport_
            .GetSourceFov(), kZNear, kZFar);

    scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);
    SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->right_camera(), scratch_viewport_
            .GetSourceFov(), kZNear, kZFar);
}

void DaydreamRenderer::SetCameraProjectionMatrix(gvr::CustomCamera *camera, const gvr::Rectf &fov,
                                                 float z_near, float z_far) {
    float x_left = -std::tan(fov.left * M_PI / 180.0f) * z_near;
    float x_right = std::tan(fov.right * M_PI / 180.0f) * z_near;
    float y_bottom = -std::tan(fov.bottom * M_PI / 180.0f) * z_near;
    float y_top = std::tan(fov.top * M_PI / 180.0f) * z_near;
    glm::mat4 projection_matrix = glm::frustum(x_left, x_right, y_bottom, y_top, z_near, z_far);
    // set the camera projection matrix
    camera->set_projection_matrix(projection_matrix);
}<commit_msg>Fix the daydream default FBO and UV values.<commit_after>/* Copyright 2016 Samsung Electronics Co., LTD
 *
 * 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 "daydream_renderer.h"
#include "glm/gtc/matrix_inverse.hpp"

namespace {
    static const uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;
    static const int kDefaultFboResolution = 1024;
    static const gvr::Rectf kDefaultUV = {0.0f, 1.0f, 0.0f, 1.0f};

    // Use the same default clipping distances as the perspective camera
    // TODO: Change this to read the values from the gvr.xml file
    static const float kZNear = 0.1f;
    static const float kZFar = 1000.0f;

    static glm::mat4 MatrixToGLMMatrix(const gvr::Mat4f &matrix) {
        glm::mat4 result;
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 4; ++j) {
                result[i][j] = matrix.m[i][j];
            }
        }
        return result;
    }

    static gvr::Rectf ModulateRect(const gvr::Rectf &rect, float width,
                                   float height) {
        gvr::Rectf result = {rect.left * width, rect.right * width,
                             rect.bottom * height, rect.top * height};
        return result;
    }

    static gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei &texture_size,
                                              const gvr::Rectf &texture_rect) {
        const float width = static_cast<float>(texture_size.width);
        const float height = static_cast<float>(texture_size.height);
        const gvr::Rectf rect = ModulateRect(texture_rect, width, height);
        const gvr::Recti result = {
                static_cast<int>(rect.left), static_cast<int>(rect.right),
                static_cast<int>(rect.bottom), static_cast<int>(rect.top)};
        return result;
    }

    static void CheckGLError(const char *label) {
        int gl_error = glGetError();
        if (gl_error != GL_NO_ERROR) {
            LOGW("GL error @ %s: %d", label, gl_error);
            // Crash immediately to make OpenGL errors obvious.
            abort();
        }
    }

}  // namespace

DaydreamRenderer::DaydreamRenderer(JNIEnv &env, jclass clazz,
                                   gvr_context *gvr_context)
        : gvr_api_(gvr::GvrApi::WrapNonOwned(gvr_context)),
          scratch_viewport_(gvr_api_->CreateBufferViewport()) {
    jclass rendererClass = env.GetObjectClass(clazz);
    rendererObject_ = env.NewGlobalRef(clazz);
    onDrawEyeMethodId_ = env.GetMethodID(rendererClass, "onDrawEye", "(I)V");
    env.DeleteLocalRef(rendererClass);
}

DaydreamRenderer::~DaydreamRenderer() {
}

void DaydreamRenderer::InitializeGl() {
    gvr_api_->InitializeGl();

    //@todo read gvr.xml and obtain the values from EyeBufferParams
    render_size_.height = kDefaultFboResolution;
    render_size_.width = kDefaultFboResolution;
    std::vector <gvr::BufferSpec> specs;
    specs.push_back(gvr_api_->CreateBufferSpec());
    specs.push_back(gvr_api_->CreateBufferSpec());

    specs[0].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
    specs[0].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);
    specs[0].SetSize(render_size_);
    specs[0].SetSamples(2);

    specs[1].SetColorFormat(GVR_COLOR_FORMAT_RGBA_8888);
    specs[1].SetDepthStencilFormat(GVR_DEPTH_STENCIL_FORMAT_DEPTH_24_STENCIL_8);
    specs[1].SetSize(render_size_);
    specs[1].SetSamples(2);
    swapchain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));

    viewport_list_.reset(new gvr::BufferViewportList(
            gvr_api_->CreateEmptyBufferViewportList()));
    scratch_viewport_list_.reset(new gvr::BufferViewportList(
            gvr_api_->CreateEmptyBufferViewportList()));

}

void DaydreamRenderer::DrawFrame(JNIEnv &env) {
    // use the scratch list to get the recommended viewports
    scratch_viewport_list_->SetToRecommendedBufferViewports();

    // construct FBO backed viewports
    gvr::BufferViewport fbo_viewport = gvr_api_->CreateBufferViewport();

    scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);
    fbo_viewport.SetSourceBufferIndex(0);
    fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());
    fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());
    fbo_viewport.SetSourceUv(kDefaultUV);
    fbo_viewport.SetTargetEye(GVR_LEFT_EYE);
    viewport_list_->SetBufferViewport(0, fbo_viewport);

    scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);
    fbo_viewport.SetSourceBufferIndex(1);
    fbo_viewport.SetSourceFov(scratch_viewport_.GetSourceFov());
    fbo_viewport.SetReprojection(scratch_viewport_.GetReprojection());
    fbo_viewport.SetSourceUv(kDefaultUV);
    fbo_viewport.SetTargetEye(GVR_RIGHT_EYE);
    viewport_list_->SetBufferViewport(1, fbo_viewport);

    gvr::Frame frame = swapchain_->AcquireFrame();

    gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();
    target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;

    head_view_ = gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);

    cameraRig_->getHeadTransform()->setModelMatrix(MatrixToGLMMatrix(head_view_));

    // Render the eye images.
    for (int eye = 0; eye < 2; eye++) {
        frame.BindBuffer(eye);
        viewport_list_->GetBufferViewport(eye, &scratch_viewport_);
        SetViewport(scratch_viewport_);
        env.CallVoidMethod(rendererObject_, onDrawEyeMethodId_, eye);
        frame.Unbind();
    }

    // Submit frame.
    frame.Submit(*viewport_list_, head_view_);

    CheckGLError("onDrawFrame");
}

void DaydreamRenderer::OnPause() {
    gvr_api_->PauseTracking();
}

void DaydreamRenderer::OnResume() {
    gvr_api_->RefreshViewerProfile();
    gvr_api_->ResumeTracking();
}

void DaydreamRenderer::OnDestroy(JNIEnv &env) {
    env.DeleteGlobalRef(rendererObject_);
    delete cameraRig_;
}

void DaydreamRenderer::SetViewport(const gvr::BufferViewport &viewport) {
    const gvr::Recti pixel_rect = CalculatePixelSpaceRect(render_size_, viewport.GetSourceUv());

    glViewport(pixel_rect.left, pixel_rect.bottom,
               pixel_rect.right - pixel_rect.left,
               pixel_rect.top - pixel_rect.bottom);

    CheckGLError("SetViewport");
}

void DaydreamRenderer::SetCameraRig(jlong native_camera) {
    cameraRig_ = reinterpret_cast<gvr::CameraRig *>(native_camera);
    scratch_viewport_list_->SetToRecommendedBufferViewports();

    scratch_viewport_list_->GetBufferViewport(0, &scratch_viewport_);
    SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->left_camera(), scratch_viewport_
            .GetSourceFov(), kZNear, kZFar);

    scratch_viewport_list_->GetBufferViewport(1, &scratch_viewport_);
    SetCameraProjectionMatrix((gvr::CustomCamera *) cameraRig_->right_camera(), scratch_viewport_
            .GetSourceFov(), kZNear, kZFar);
}

void DaydreamRenderer::SetCameraProjectionMatrix(gvr::CustomCamera *camera, const gvr::Rectf &fov,
                                                 float z_near, float z_far) {
    float x_left = -std::tan(fov.left * M_PI / 180.0f) * z_near;
    float x_right = std::tan(fov.right * M_PI / 180.0f) * z_near;
    float y_bottom = -std::tan(fov.bottom * M_PI / 180.0f) * z_near;
    float y_top = std::tan(fov.top * M_PI / 180.0f) * z_near;
    glm::mat4 projection_matrix = glm::frustum(x_left, x_right, y_bottom, y_top, z_near, z_far);
    // set the camera projection matrix
    camera->set_projection_matrix(projection_matrix);
}<|endoftext|>


<commit_before>#include "Channel_AWGN_fast_LLR.hpp"

#include <algorithm>
#include <cassert>

template <typename R>
Channel_AWGN_fast_LLR<R>
::Channel_AWGN_fast_LLR(const R& sigma, const int seed, const R scaling_factor)
: sigma(sigma),
  scaling_factor(scaling_factor),
  rd(),
  rd_engine(this->rd()),
  dist(std::numeric_limits<R>::min(),1)
{
	rd_engine.seed(seed);

	std::cout << "min = " << std::numeric_limits<R>::min() << std::endl;
}

template <typename R>
Channel_AWGN_fast_LLR<R>
::~Channel_AWGN_fast_LLR()
{
}

// box muller method in the polar form
template <typename R>
void Channel_AWGN_fast_LLR<R>
::add_noise(const mipp::vector<R>& X_N, mipp::vector<R>& Y_N)
{
	assert(X_N.size() % 2                       == 0         );
	assert(X_N.size()                           == Y_N.size());
	assert(scaling_factor                       != 0         );
	assert(sigma                                != 0         );
	assert(X_N.size() % (2 * mipp::nElReg<R>()) == 0         );

	const auto loop_size = (int)Y_N.size();
	for (auto i = 0; i < loop_size; i++)
	{
		Y_N[i] = this->dist(this->rd_engine);
		if (Y_N[i] == 0)
			std::cout << "PROUTTTT" << std::endl;
	}

	// const mipp::Reg<R> sf       = this->scaling_factor;
	// const mipp::Reg<R> sigma    = this->sigma;
	// const mipp::Reg<R> twopi    = 2.0 * 3.14159265358979323846;
	// const mipp::Reg<R> one      = 1.0;
	// const mipp::Reg<R> minustwo = -2.0;

	// for (auto i = 0; i < loop_size; i += mipp::nElReg<R>() * 2)
	// {
	// 	// const auto u1 = one - mipp::Reg<R>(&Y_N[i                    ]); // [0, 1) -> (0, 1]
	// 	const auto u1 = mipp::Reg<R>(&Y_N[i                    ]);
	// 	const auto u2 = mipp::Reg<R>(&Y_N[i + mipp::nElReg<R>()]);

	// 	const auto radius = mipp::sqrt(minustwo * mipp::log(u1)) * sigma;
	// 	const auto theta  = twopi * u2;

	// 	mipp::Reg<R> sintheta, costheta;
	// 	mipp::sincos(theta, sintheta, costheta);

	// 	// fmadd(a, b, c) = a * b + c
	// 	auto awgn1 = mipp::fmadd(radius, costheta, mipp::Reg<R>(&X_N[i                    ])) * sf;
	// 	auto awgn2 = mipp::fmadd(radius, sintheta, mipp::Reg<R>(&X_N[i + mipp::nElReg<R>()])) * sf;

	// 	awgn1.store(&Y_N[i                    ]);
	// 	awgn2.store(&Y_N[i + mipp::nElReg<R>()]);
	// }

	auto twopi = (R)(2.0 * 3.14159265358979323846);
	for (auto i = 0; i < loop_size; i += 2)
	{
		// auto x  = (R)sqrt(-2.0 * log((R)rand() / (R)2147483647));
		// auto y  = (R)rand() / (R)2147483647;
		const auto u1 = Y_N[i +0];
		const auto u2 = Y_N[i +1];

		const auto radius = (R)std::sqrt((R)-2.0 * std::log(u1)) * sigma;
		const auto theta  = twopi * u2;

		const auto sintheta = std::sin(theta);
		const auto costheta = std::cos(theta);

		Y_N[i +0] = (X_N[i +0] + radius * sintheta) * scaling_factor;
		Y_N[i +1] = (X_N[i +1] + radius * costheta) * scaling_factor;
	}

	for (auto i = 0; i < loop_size; i++)
		if (std::isnan(Y_N[i]))
			std::cout << "NaN" << std::endl;
}

// ==================================================================================== explicit template instantiation
#include "../../../Tools/types.h"
#ifdef MULTI_PREC
template class Channel_AWGN_fast_LLR<R_32>;
template class Channel_AWGN_fast_LLR<R_64>;
#else
template class Channel_AWGN_fast_LLR<R>;
#endif
// ==================================================================================== explicit template instantiation<commit_msg>Turn on SIMD code.<commit_after>#include "Channel_AWGN_fast_LLR.hpp"

#include <algorithm>
#include <cassert>

template <typename R>
Channel_AWGN_fast_LLR<R>
::Channel_AWGN_fast_LLR(const R& sigma, const int seed, const R scaling_factor)
: sigma(sigma),
  scaling_factor(scaling_factor),
  rd(),
  rd_engine(this->rd()),
  dist(std::numeric_limits<R>::min(),1)
{
	rd_engine.seed(seed);

	std::cout << "min = " << std::numeric_limits<R>::min() << std::endl;
}

template <typename R>
Channel_AWGN_fast_LLR<R>
::~Channel_AWGN_fast_LLR()
{
}

// box muller method in the polar form
template <typename R>
void Channel_AWGN_fast_LLR<R>
::add_noise(const mipp::vector<R>& X_N, mipp::vector<R>& Y_N)
{
	assert(X_N.size() % 2                       == 0         );
	assert(X_N.size()                           == Y_N.size());
	assert(scaling_factor                       != 0         );
	assert(sigma                                != 0         );
	assert(X_N.size() % (2 * mipp::nElReg<R>()) == 0         );

	const auto loop_size = (int)Y_N.size();
	for (auto i = 0; i < loop_size; i++)
	{
		Y_N[i] = this->dist(this->rd_engine);
		// if (Y_N[i] == 0)
		// 	std::cout << "PROUTTTT" << std::endl;
	}

	const mipp::Reg<R> sf       = this->scaling_factor;
	const mipp::Reg<R> sigma    = this->sigma;
	const mipp::Reg<R> twopi    = 2.0 * 3.14159265358979323846;
	const mipp::Reg<R> one      = 1.0;
	const mipp::Reg<R> minustwo = -2.0;

	for (auto i = 0; i < loop_size; i += mipp::nElReg<R>() * 2)
	{
		// const auto u1 = one - mipp::Reg<R>(&Y_N[i                    ]); // [0, 1) -> (0, 1]
		const auto u1 = mipp::Reg<R>(&Y_N[i                    ]);
		const auto u2 = mipp::Reg<R>(&Y_N[i + mipp::nElReg<R>()]);

		const auto radius = mipp::sqrt(minustwo * mipp::log(u1)) * sigma;
		const auto theta  = twopi * u2;

		mipp::Reg<R> sintheta, costheta;
		mipp::sincos(theta, sintheta, costheta);

		// fmadd(a, b, c) = a * b + c
		auto awgn1 = mipp::fmadd(radius, costheta, mipp::Reg<R>(&X_N[i                    ])) * sf;
		auto awgn2 = mipp::fmadd(radius, sintheta, mipp::Reg<R>(&X_N[i + mipp::nElReg<R>()])) * sf;

		awgn1.store(&Y_N[i                    ]);
		awgn2.store(&Y_N[i + mipp::nElReg<R>()]);
	}

	// auto twopi = (R)(2.0 * 3.14159265358979323846);
	// for (auto i = 0; i < loop_size; i += 2)
	// {
	// 	// auto x  = (R)sqrt(-2.0 * log((R)rand() / (R)2147483647));
	// 	// auto y  = (R)rand() / (R)2147483647;
	// 	const auto u1 = Y_N[i +0];
	// 	const auto u2 = Y_N[i +1];

	// 	const auto radius = (R)std::sqrt((R)-2.0 * std::log(u1)) * sigma;
	// 	const auto theta  = twopi * u2;

	// 	const auto sintheta = std::sin(theta);
	// 	const auto costheta = std::cos(theta);

	// 	Y_N[i +0] = (X_N[i +0] + radius * sintheta) * scaling_factor;
	// 	Y_N[i +1] = (X_N[i +1] + radius * costheta) * scaling_factor;
	// }

	// for (auto i = 0; i < loop_size; i++)
	// 	if (std::isnan(Y_N[i]))
	// 		std::cout << "NaN" << std::endl;
}

// ==================================================================================== explicit template instantiation
#include "../../../Tools/types.h"
#ifdef MULTI_PREC
template class Channel_AWGN_fast_LLR<R_32>;
template class Channel_AWGN_fast_LLR<R_64>;
#else
template class Channel_AWGN_fast_LLR<R>;
#endif
// ==================================================================================== explicit template instantiation<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Laura Schlimmer <laura@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include "eventql/eventql.h"
#include "eventql/util/stringutil.h"
#include "eventql/util/io/fileutil.h"
#include "eventql/util/csv/CSVOutputStream.h"
#include "eventql/sql/runtime/defaultruntime.h"
#include "eventql/sql/CSTableScanProvider.h"
#include "eventql/sql/result_list.h"
#include "eventql/util/csv/CSVInputStream.h"
#include "test_repository.h"

namespace eventql {
namespace test {
namespace sql {

enum class ResultExpectation { TABLE, CHART, ERROR };

const auto kBaseDirectoryPath = "./test";
const auto kDirectoryPath = FileUtil::joinPaths(kBaseDirectoryPath, "sql");
const auto kTestListFile = FileUtil::joinPaths(
    kBaseDirectoryPath,
    "sql_tests.lst");
const auto kSQLPathEnding = ".sql";
const auto kResultPathEnding = ".result.txt";
const auto kActualResultPathEnding = ".actual.result.txt";
const auto kChartColumnName = "__chart";
const auto kDefaultResultExpectation = ResultExpectation::TABLE;

std::string getResultCSV(
    csql::ResultList* result,
    const std::string& row_sep = "\n") {
  std::string result_csv;
  auto is = new StringOutputStream(&result_csv);
  auto csv_is = new CSVOutputStream(
      std::unique_ptr<OutputStream>(is),
      ";",
      row_sep);

  auto columns = result->getColumns();
  csv_is->appendRow(columns);

  auto num_rows = result->getNumRows();
  for (size_t i = 0; i < num_rows; ++i) {
    auto row = result->getRow(i);
    csv_is->appendRow(row);
  }

  return result_csv;
}

Status checkTableResult(
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto csv_is = CSVInputStream::openFile(result_file_path);
  std::vector<std::string> columns;
  if (!csv_is->readNextRow(&columns)) {
    return Status(eRuntimeError, "CSV needs a header");
  }

  /* compare columns */
  if (result->getNumColumns() != columns.size()) {
    return Status(eRuntimeError, StringUtil::format(
        "wrong number of columns, expected $0 to be $1",
        result->getNumColumns(),
        columns.size()));
  }

  auto returned_columns = result->getColumns();
  for (size_t i = 0; i < returned_columns.size(); ++i) {
    if (returned_columns[i] != columns[i]) {
      return Status(eRuntimeError, StringUtil::format(
          "wrong column name, expected $0 to be $1",
          returned_columns[i],
          columns[i]));
    }
  }

  /* compare rows */
  auto num_returned_rows = result->getNumRows();
  size_t count = 0;
  std::vector<std::string> row;
  while (csv_is->readNextRow(&row)) {
    if (count >= num_returned_rows) {
      return Status(eRuntimeError, "not enough rows returned");
    }

    auto returned_row = result->getRow(count);
    if (returned_row.size() != row.size()) {
      return Status(eRuntimeError, StringUtil::format(
          "wrong number of values, expected $0 to be $1",
          returned_row.size(),
          row.size()));
    }

    for (size_t i = 0; i < row.size(); ++i) {
      if (row[i] != returned_row[i]) {
        return Status(
            eRuntimeError,
            StringUtil::format(
                "result mismatch at row $0, column $1; expected: >$2<, got: >$3<",
                count,
                i,
                row[i],
                returned_row[i]));
      }
    }

    ++count;
  }

  if (count < num_returned_rows) {
    return Status(eRuntimeError, StringUtil::format(
        "too many rows, expected $0 to be $1",
        num_returned_rows,
        count));
  }

  return Status::success();
}

Status checkChartResult(
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto num_returned_rows = result->getNumRows();
  if (num_returned_rows != 1) {
    return Status(eRuntimeError, StringUtil::format(
        "wrong number of rows returned, expected $0 to be 1",
        num_returned_rows));
  }

  auto is = FileInputStream::openFile(result_file_path);
  std::string expected_result;
  is->readUntilEOF(&expected_result);

  auto returned_result = result->getRow(0)[0];
  if (expected_result != returned_result) {
    return Status(eRuntimeError, "result charts don't match");
  }

  return Status::success();
}

Status checkErrorResult(
    const std::string& error_message,
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto is = FileInputStream::openFile(result_file_path);

  {
    std::string result_expectation_line;
    is->readLine(&result_expectation_line);
  }

  std::string expected_error;
  is->readUntilEOF(&expected_error);
  StringUtil::chomp(&expected_error);

  if (expected_error == error_message) {
    return Status::success();
  } else {
    if (error_message.empty()) {
      auto result_csv = getResultCSV(result, " ");
      return Status(eRuntimeError, StringUtil::format(
          "expected error: $0 but got result: $1",
          expected_error,
          result_csv));

    } else {
      return Status(eRuntimeError, StringUtil::format(
          "expected error: $0 but got error $1",
          expected_error,
          error_message));
    }
  }
}

bool runTest(std::string id) {
  auto sql_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kSQLPathEnding));

  if (!FileUtil::exists(sql_file_path)) {
    RAISE(
        kIOError,
        StringUtil::format("File does not exist: $0", sql_file_path));
  }

  auto result_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kResultPathEnding));

  if (!FileUtil::exists(result_file_path)) {
    RAISE(
        kIOError,
        StringUtil::format("File does not exist: $0", result_file_path));
  }

  auto result_expectation = kDefaultResultExpectation;
  auto result_is = FileInputStream::openFile(result_file_path);
  std::string first_line;
  if (result_is->readLine(&first_line)) {
    StringUtil::chomp(&first_line);
    if (first_line == "ERROR!") {
      result_expectation = ResultExpectation::ERROR;
    }
  }

  /* input table path */
  auto sql_is = FileInputStream::openFile(sql_file_path);
  std::string input_table_path;
  if (!sql_is->readLine(&input_table_path) ||
      !StringUtil::beginsWith(input_table_path, "--")) {
    RAISE(kRuntimeError, "no input table provided");
  }

  StringUtil::replaceAll(&input_table_path, "--");
  StringUtil::ltrim(&input_table_path);
  StringUtil::chomp(&input_table_path);
  input_table_path = FileUtil::joinPaths(
      kBaseDirectoryPath,
      input_table_path);

  if (!FileUtil::exists(input_table_path)) {
    RAISE(
        kRuntimeError,
        StringUtil::format("file does not exist: $0", input_table_path));
  }

  std::string query;
  sql_is->readUntilEOF(&query);

  /* execute query */
  auto runtime = csql::Runtime::getDefaultRuntime();
  auto txn = runtime->newTransaction();

  txn->setTableProvider(
      new csql::CSTableScanProvider("testtable", input_table_path));
  csql::ResultList result;

  std::string error_message;
  try {
    auto qplan = runtime->buildQueryPlan(txn.get(), query);
    qplan->execute(0, &result);
  } catch (const std::exception& e) {
    error_message = e.what();

    if (result_expectation != ResultExpectation::ERROR) {
      RAISE(
          kRuntimeError,
          StringUtil::format("unexpected error: $0", error_message));
    }
  }

  if (result.getNumColumns() == 1 &&
      result.getColumns()[0] == kChartColumnName) {
    result_expectation = ResultExpectation::CHART;
  }

  auto rc = Status::success();
  switch (result_expectation) {
    case ResultExpectation::TABLE:
      rc = checkTableResult(&result, result_file_path);
      break;

    case ResultExpectation::CHART:
      rc = checkChartResult(&result, result_file_path);
      break;

    case ResultExpectation::ERROR:
      rc = checkErrorResult(error_message, &result, result_file_path);
      break;
  }

  if (rc.isSuccess()) {
    return true;
  }

  /* write file with actual result */
  auto acutal_result_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kActualResultPathEnding));

  const auto& csv_result = getResultCSV(&result);
  FileUtil::write(acutal_result_file_path, csv_result);

  RAISE(kRuntimeError, rc.message());
}

void setup_sql_tests(TestRepository* repo) {
  auto is = FileInputStream::openFile(kTestListFile);
  std::string test_id;
  while (is->readLine(&test_id)) {
    StringUtil::chomp(&test_id);

    auto test_case = eventql::test::TestCase {
      .test_id = StringUtil::format("SQL-$0", test_id.substr(0, 5)),
      .description = test_id,
      .fun = std::bind(runTest, test_id),
      .suites =  { TestSuite::WORLD, TestSuite::SMOKE }
    };

    repo->addTestBundle({ test_case });
    test_id.clear();
  }

}

} // namespace sql
} // namespace test
} // namespace eventql

<commit_msg>improved sql test description<commit_after>/**
 * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Laura Schlimmer <laura@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include "eventql/eventql.h"
#include "eventql/util/stringutil.h"
#include "eventql/util/io/fileutil.h"
#include "eventql/util/csv/CSVOutputStream.h"
#include "eventql/sql/runtime/defaultruntime.h"
#include "eventql/sql/CSTableScanProvider.h"
#include "eventql/sql/result_list.h"
#include "eventql/util/csv/CSVInputStream.h"
#include "test_repository.h"

namespace eventql {
namespace test {
namespace sql {

enum class ResultExpectation { TABLE, CHART, ERROR };

const auto kBaseDirectoryPath = "./test";
const auto kDirectoryPath = FileUtil::joinPaths(kBaseDirectoryPath, "sql");
const auto kTestListFile = FileUtil::joinPaths(
    kBaseDirectoryPath,
    "sql_tests.lst");
const auto kSQLPathEnding = ".sql";
const auto kResultPathEnding = ".result.txt";
const auto kActualResultPathEnding = ".actual.result.txt";
const auto kChartColumnName = "__chart";
const auto kDefaultResultExpectation = ResultExpectation::TABLE;

std::string getResultCSV(
    csql::ResultList* result,
    const std::string& row_sep = "\n") {
  std::string result_csv;
  auto is = new StringOutputStream(&result_csv);
  auto csv_is = new CSVOutputStream(
      std::unique_ptr<OutputStream>(is),
      ";",
      row_sep);

  auto columns = result->getColumns();
  csv_is->appendRow(columns);

  auto num_rows = result->getNumRows();
  for (size_t i = 0; i < num_rows; ++i) {
    auto row = result->getRow(i);
    csv_is->appendRow(row);
  }

  return result_csv;
}

Status checkTableResult(
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto csv_is = CSVInputStream::openFile(result_file_path);
  std::vector<std::string> columns;
  if (!csv_is->readNextRow(&columns)) {
    return Status(eRuntimeError, "CSV needs a header");
  }

  /* compare columns */
  if (result->getNumColumns() != columns.size()) {
    return Status(eRuntimeError, StringUtil::format(
        "wrong number of columns, expected $0 to be $1",
        result->getNumColumns(),
        columns.size()));
  }

  auto returned_columns = result->getColumns();
  for (size_t i = 0; i < returned_columns.size(); ++i) {
    if (returned_columns[i] != columns[i]) {
      return Status(eRuntimeError, StringUtil::format(
          "wrong column name, expected $0 to be $1",
          returned_columns[i],
          columns[i]));
    }
  }

  /* compare rows */
  auto num_returned_rows = result->getNumRows();
  size_t count = 0;
  std::vector<std::string> row;
  while (csv_is->readNextRow(&row)) {
    if (count >= num_returned_rows) {
      return Status(eRuntimeError, "not enough rows returned");
    }

    auto returned_row = result->getRow(count);
    if (returned_row.size() != row.size()) {
      return Status(eRuntimeError, StringUtil::format(
          "wrong number of values, expected $0 to be $1",
          returned_row.size(),
          row.size()));
    }

    for (size_t i = 0; i < row.size(); ++i) {
      if (row[i] != returned_row[i]) {
        return Status(
            eRuntimeError,
            StringUtil::format(
                "result mismatch at row $0, column $1; expected: >$2<, got: >$3<",
                count,
                i,
                row[i],
                returned_row[i]));
      }
    }

    ++count;
  }

  if (count < num_returned_rows) {
    return Status(eRuntimeError, StringUtil::format(
        "too many rows, expected $0 to be $1",
        num_returned_rows,
        count));
  }

  return Status::success();
}

Status checkChartResult(
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto num_returned_rows = result->getNumRows();
  if (num_returned_rows != 1) {
    return Status(eRuntimeError, StringUtil::format(
        "wrong number of rows returned, expected $0 to be 1",
        num_returned_rows));
  }

  auto is = FileInputStream::openFile(result_file_path);
  std::string expected_result;
  is->readUntilEOF(&expected_result);

  auto returned_result = result->getRow(0)[0];
  if (expected_result != returned_result) {
    return Status(eRuntimeError, "result charts don't match");
  }

  return Status::success();
}

Status checkErrorResult(
    const std::string& error_message,
    csql::ResultList* result,
    const std::string& result_file_path) {
  auto is = FileInputStream::openFile(result_file_path);

  {
    std::string result_expectation_line;
    is->readLine(&result_expectation_line);
  }

  std::string expected_error;
  is->readUntilEOF(&expected_error);
  StringUtil::chomp(&expected_error);

  if (expected_error == error_message) {
    return Status::success();
  } else {
    if (error_message.empty()) {
      auto result_csv = getResultCSV(result, " ");
      return Status(eRuntimeError, StringUtil::format(
          "expected error: $0 but got result: $1",
          expected_error,
          result_csv));

    } else {
      return Status(eRuntimeError, StringUtil::format(
          "expected error: $0 but got error $1",
          expected_error,
          error_message));
    }
  }
}

bool runTest(std::string id) {
  auto sql_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kSQLPathEnding));

  if (!FileUtil::exists(sql_file_path)) {
    RAISE(
        kIOError,
        StringUtil::format("File does not exist: $0", sql_file_path));
  }

  auto result_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kResultPathEnding));

  if (!FileUtil::exists(result_file_path)) {
    RAISE(
        kIOError,
        StringUtil::format("File does not exist: $0", result_file_path));
  }

  auto result_expectation = kDefaultResultExpectation;
  auto result_is = FileInputStream::openFile(result_file_path);
  std::string first_line;
  if (result_is->readLine(&first_line)) {
    StringUtil::chomp(&first_line);
    if (first_line == "ERROR!") {
      result_expectation = ResultExpectation::ERROR;
    }
  }

  /* input table path */
  auto sql_is = FileInputStream::openFile(sql_file_path);
  std::string input_table_path;
  if (!sql_is->readLine(&input_table_path) ||
      !StringUtil::beginsWith(input_table_path, "--")) {
    RAISE(kRuntimeError, "no input table provided");
  }

  StringUtil::replaceAll(&input_table_path, "--");
  StringUtil::ltrim(&input_table_path);
  StringUtil::chomp(&input_table_path);
  input_table_path = FileUtil::joinPaths(
      kBaseDirectoryPath,
      input_table_path);

  if (!FileUtil::exists(input_table_path)) {
    RAISE(
        kRuntimeError,
        StringUtil::format("file does not exist: $0", input_table_path));
  }

  std::string query;
  sql_is->readUntilEOF(&query);

  /* execute query */
  auto runtime = csql::Runtime::getDefaultRuntime();
  auto txn = runtime->newTransaction();

  txn->setTableProvider(
      new csql::CSTableScanProvider("testtable", input_table_path));
  csql::ResultList result;

  std::string error_message;
  try {
    auto qplan = runtime->buildQueryPlan(txn.get(), query);
    qplan->execute(0, &result);
  } catch (const std::exception& e) {
    error_message = e.what();

    if (result_expectation != ResultExpectation::ERROR) {
      RAISE(
          kRuntimeError,
          StringUtil::format("unexpected error: $0", error_message));
    }
  }

  if (result.getNumColumns() == 1 &&
      result.getColumns()[0] == kChartColumnName) {
    result_expectation = ResultExpectation::CHART;
  }

  auto rc = Status::success();
  switch (result_expectation) {
    case ResultExpectation::TABLE:
      rc = checkTableResult(&result, result_file_path);
      break;

    case ResultExpectation::CHART:
      rc = checkChartResult(&result, result_file_path);
      break;

    case ResultExpectation::ERROR:
      rc = checkErrorResult(error_message, &result, result_file_path);
      break;
  }

  if (rc.isSuccess()) {
    return true;
  }

  /* write file with actual result */
  auto acutal_result_file_path = FileUtil::joinPaths(
      kDirectoryPath,
      StringUtil::format("$0$1", id, kActualResultPathEnding));

  const auto& csv_result = getResultCSV(&result);
  FileUtil::write(acutal_result_file_path, csv_result);

  RAISE(kRuntimeError, rc.message());
}

void setup_sql_tests(TestRepository* repo) {
  auto is = FileInputStream::openFile(kTestListFile);
  std::string test_id;
  while (is->readLine(&test_id)) {
    StringUtil::chomp(&test_id);

    auto test_case = eventql::test::TestCase {
      .test_id = StringUtil::format("SQL-$0", test_id.substr(0, 5)),
      .description = test_id.substr(6),
      .fun = std::bind(runTest, test_id),
      .suites =  { TestSuite::WORLD, TestSuite::SMOKE }
    };

    repo->addTestBundle({ test_case });
    test_id.clear();
  }
}

} // namespace sql
} // namespace test
} // namespace eventql

<|endoftext|>


<commit_before>#include "game.hpp"

//////////
// Code //

struct PositionEvent : public clibgame::Event {
    std::string name;
    float x, y;
    float w, h;

    PositionEvent(std::string name,
                   float x, float y,
                   float w, float h) {
        this->name = name;

        this->x = x;
        this->y = y;
        this->w = w;
        this->h = h;
    }

    std::string getEventType() const { return this->name; }
};

struct Position : public clibgame::Component {
    float x, y, w, h;
    bool alert;

    Position(float x, float y,
             float w, float h,
             bool alert) {
        this->x = x;
        this->y = y;

        this->w = w;
        this->h = h;

        this->alert = alert;
    }

    std::string getName() const { return "position"; }

    void translate(float dx, float dy) {
        this->x += dx;
        this->y += dy;

        if (this->alert)
            clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),
                                                                      this->x, this->y,
                                                                      this->w, this->h));
    }
};

struct PlayerController : public clibgame::Component {
    float speed;

    PlayerController(float speed) {
        this->speed = speed;
    }

    std::string getName() const { return "playerController"; }

    void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {
        float dx = 0,
              dy = 0;

        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
            dy += speed;
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
            dy -= speed;
        if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
            dx -= speed;
        if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
            dx += speed;

        if (dx != 0 || dy != 0) {
            Position& p = dynamic_cast<Position&>(this->getOwner().getComponent("position"));
            p.translate(dx, dy);
        }
    }
};

struct PlayerRender : public clibgame::Component,
                      public clibgame::Listener {
    clibgame::Texture* texture;
    clibgame::Shader* shader;
    GLuint vao, ebo;

    GLuint vbo1, vbo2;
    bool mode;

    std::vector<GLfloat> generateCoords(float x, float y,
                                        float w, float h) {
        std::vector<GLfloat> vertices = {
            x    , y    , 0, 0,
            x + w, y    , 1, 0,
            x + w, y + h, 1, 1,
            x    , y + h, 0, 1
        };

        return vertices;
    }

    void updateVertices(float x, float y, float w, float h) {
        auto vVertices = generateCoords(x, y, w, h);

        GLfloat aVertices[vVertices.size()];
        for (int i = 0; i < vVertices.size(); i++)
            aVertices[i] = vVertices.at(i);

        glBindBuffer(GL_ARRAY_BUFFER, this->mode ? vbo1 : vbo2);
        glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);
        mode = !mode;
    }

    PlayerRender() {
        clibgame::ListenerManager::instance().registerListener(this, "position");

        texture = nullptr;
        shader  = nullptr;
        vao     = 0;
        vbo1    = 0;
        vbo2    = 0;
        ebo     = 0;
    }

    ~PlayerRender() {
        if (texture != nullptr)
            delete texture;
        if (shader != nullptr)
            delete shader;

        glDeleteVertexArrays(1, &this->vao);
        glDeleteBuffers(1, &this->vbo1);
        glDeleteBuffers(1, &this->vbo2);
        glDeleteBuffers(1, &this->ebo);
    }

    std::string getName() const { return "playerRender"; }

    void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
        texture = new clibgame::Texture(res.getTexture("res/test.png"));
        shader = new clibgame::Shader(res.getShader("res/test"));

        glGenVertexArrays(1, &this->vao);
        glBindVertexArray(this->vao);

        glGenBuffers(1, &this->vbo1);
        glGenBuffers(1, &this->vbo2);
        this->updateVertices(0, 0, 0.1, 0.1);
        this->updateVertices(0, 0, 0.1, 0.1);

        glGenBuffers(1, &this->ebo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);

        GLuint order[] = {
            0, 1, 2,
            2, 3, 0
        };

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
    }

    void render() const {
        glBindVertexArray(this->vao);
        glBindBuffer(GL_ARRAY_BUFFER, this->mode ? vbo2 : vbo1);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);

        glUseProgram(this->shader->getShaderID());

        // Initializing the coordinates.
        GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");

        glEnableVertexAttribArray(coordAttrib);
        glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);

        // Initializing the texture.
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());
        glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    }

    void alert(const clibgame::Event&& e) {
        if (e.getEventType() == "position") {
            const PositionEvent&& pe = dynamic_cast<const PositionEvent&&>(e);
            //this->updateVertices(pe.x, pe.y,
                                 //pe.w, pe.h);
        }
    }
};

// Creating a new game.
Game::Game() {
    this->addEntity("player");
    this->getEntity("player").addComponent(new Position(0, 0, 0.1, 0.1, true));
    this->getEntity("player").addComponent(new PlayerController(0.5));
    this->getEntity("player").addComponent(new PlayerRender());
}
<commit_msg>Some stuff!<commit_after>#include "game.hpp"

//////////
// Code //

struct PositionEvent : public clibgame::Event {
    std::string name;
    float x, y;
    float w, h;

    PositionEvent(std::string name,
                   float x, float y,
                   float w, float h) {
        this->name = name;

        this->x = x;
        this->y = y;
        this->w = w;
        this->h = h;
    }

    std::string getEventType() const { return this->name; }
};

struct Position : public clibgame::Component {
    float x, y, w, h;
    bool alert;

    Position(float x, float y,
             float w, float h,
             bool alert) {
        this->x = x;
        this->y = y;

        this->w = w;
        this->h = h;

        this->alert = alert;
    }

    std::string getName() const { return "position"; }

    void translate(float dx, float dy) {
        this->x += dx;
        this->y += dy;

        if (this->alert)
            clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),
                                                                      this->x, this->y,
                                                                      this->w, this->h));
    }
};

struct PlayerController : public clibgame::Component {
    float speed;

    PlayerController(float speed) {
        this->speed = speed;
    }

    std::string getName() const { return "playerController"; }

    void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {
        float dx = 0,
              dy = 0;

        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
            dy += speed;
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
            dy -= speed;
        if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
            dx -= speed;
        if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
            dx += speed;

        if (dx != 0 || dy != 0) {
            Position& p = dynamic_cast<Position&>(this->getOwner().getComponent("position"));
            p.translate(dx * dt, dy * dt);
        }
    }
};

struct PlayerRender : public clibgame::Component,
                      public clibgame::Listener {
    clibgame::Texture* texture;
    clibgame::Shader* shader;
    GLuint vao, vbo, ebo;

    std::vector<GLfloat> generateCoords(float x, float y,
                                        float w, float h) {
        std::vector<GLfloat> vertices = {
            x    , y    , 0, 0,
            x + w, y    , 1, 0,
            x + w, y + h, 1, 1,
            x    , y + h, 0, 1
        };

        return vertices;
    }

    void updateVertices(float x, float y, float w, float h) {
        auto vVertices = generateCoords(x, y, w, h);

        GLfloat aVertices[vVertices.size()];
        for (int i = 0; i < vVertices.size(); i++)
            aVertices[i] = vVertices.at(i);

        glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
        glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);
    }

    PlayerRender() {
        clibgame::ListenerManager::instance().registerListener(this, "position");

        texture = nullptr;
        shader  = nullptr;
        vao     = 0;
        vbo     = 0;
        ebo     = 0;
    }

    ~PlayerRender() {
        if (texture != nullptr)
            delete texture;
        if (shader != nullptr)
            delete shader;

        glDeleteVertexArrays(1, &this->vao);
        glDeleteBuffers(1, &this->vbo);
        glDeleteBuffers(1, &this->ebo);
    }

    std::string getName() const { return "playerRender"; }

    void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
        texture = new clibgame::Texture(res.getTexture("res/test.png"));
        shader = new clibgame::Shader(res.getShader("res/test"));

        glGenVertexArrays(1, &this->vao);
        glBindVertexArray(this->vao);

        glGenBuffers(1, &this->vbo);
        this->updateVertices(0, 0, 0.1, 0.1);

        glGenBuffers(1, &this->ebo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);

        GLuint order[] = {
            0, 1, 2,
            2, 3, 0
        };

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
    }

    void render() const {
        glBindVertexArray(this->vao);
        glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);

        glUseProgram(this->shader->getShaderID());

        // Initializing the coordinates.
        GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");

        glEnableVertexAttribArray(coordAttrib);
        glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);

        // Initializing the texture.
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());
        glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    }

    void alert(const clibgame::Event&& e) {
        if (e.getEventType() == "position") {
            const PositionEvent&& pe = dynamic_cast<const PositionEvent&&>(e);
            this->updateVertices(pe.x, pe.y,
                                 pe.w, pe.h);
        }
    }
};

// Creating a new game.
Game::Game() {
    this->addEntity("player");
    this->getEntity("player").addComponent(new Position(0, 0, 0.1, 0.1, true));
    this->getEntity("player").addComponent(new PlayerController(0.5));
    this->getEntity("player").addComponent(new PlayerRender());
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) University College London (UCL).
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkCmdLineModuleMenuComboBox.h"
#include <iostream>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QList>
#include <cassert>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleManager.h>

// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)
: ctkMenuComboBox(parent)
, m_ModuleManager(NULL)
{
}

// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()
{

}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)
{
  if (m_ModuleManager != NULL)
  {
    QObject::disconnect(manager, 0, this, 0);
  }

  m_ModuleManager = manager;

  connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));
  connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));
}

// -------------------------------------------------------------------------
ctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const
{
  return m_ModuleManager;
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference& ref)
{
  this->RebuildMenu();
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference& ref)
{
  this->RebuildMenu();
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::AddName(
    QList< QHash<QString, QMenu*>* >& listOfHashMaps,
    const int& depth,
    const QString& name,
    QMenu* menu
    )
{
  if (depth >= listOfHashMaps.size())
  {
    int need = depth - listOfHashMaps.size();
    for (int i = 0; i <= need; i++)
    {
      QHash<QString, QMenu*> *newHashMap = new QHash<QString, QMenu*>();
      listOfHashMaps.push_back(newHashMap);
    }
  }
  listOfHashMaps[depth]->insert(name, menu);
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::RebuildMenu()
{
  if (m_ModuleManager == NULL)
  {
    qDebug() << "QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?";
    return;
  }

  // Can't see another way to get a nested menu, without rebuilding the whole thing each time.
  // :-(

  QMenu *menu = new QMenu();
  QStringList listOfModules;

  QList<ctkCmdLineModuleReference> references = m_ModuleManager->moduleReferences();

  // Get full names
  for (int i = 0; i < references.size(); i++)
  {
    ctkCmdLineModuleReference reference = references[i];
    ctkCmdLineModuleDescription description = reference.description();
    QString title = description.title();
    QString category = description.category();
    QString fullName = category + "." + title;
    listOfModules << fullName;
  }

  // Sort list, so menu comes out in some sort of nice order.
  listOfModules.sort();

  qDebug() << "QmitkCmdLineModuleMenuComboBox::RebuildMenu, listOfModules=" << listOfModules;

  // Temporary data structure to enable connecting menus together.
  QList< QHash<QString, QMenu*>* > list;

  // Iterate through all modules.
  foreach (QString fullName, listOfModules)
  {
    // Pointer to keep track of where we are in the menu tree.
    QMenu *currentMenu = menu;

    // Get individual parts, as they correspond to menu levels.
    QStringList nameParts = fullName.split(".", QString::SkipEmptyParts);

    // Iterate over each part, building up either a QMenu or QAction.
    for (int i = 0; i < nameParts.size(); i++)
    {
      QString part = nameParts[i];

      if (i != nameParts.size() - 1)
      {
        // Need to add a menu/submenu, not an action.
        if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))
        {
          QMenu *newMenu = new QMenu(part);
          currentMenu->addMenu(newMenu);
          currentMenu = newMenu;

          // Add this newMenu pointer to temporary datastructure,
          // so we know we have already created it.
          this->AddName(list, i, part, newMenu);
        }
        else
        {
          currentMenu = list[i]->value(part);
        }
      }
      else
      {
        // Leaf node, just add the action.
        currentMenu->addAction(part);
      }
    }
  }

  // Clearup termporary data structure
  for (int i = 0; i < list.size(); i++)
  {
    delete list[i];
  }

  // Set the constructed menu on the base class combo box.
  this->setMenu(menu);
}

<commit_msg>Removed spurious debug output from QmitkCmdLineModuleMenuComboBox<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) University College London (UCL).
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkCmdLineModuleMenuComboBox.h"
#include <iostream>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QList>
#include <cassert>
#include <ctkCmdLineModuleDescription.h>
#include <ctkCmdLineModuleReference.h>
#include <ctkCmdLineModuleManager.h>

// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::QmitkCmdLineModuleMenuComboBox(QWidget* parent)
: ctkMenuComboBox(parent)
, m_ModuleManager(NULL)
{
}

// -------------------------------------------------------------------------
QmitkCmdLineModuleMenuComboBox::~QmitkCmdLineModuleMenuComboBox()
{

}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::SetManager(ctkCmdLineModuleManager* manager)
{
  if (m_ModuleManager != NULL)
  {
    QObject::disconnect(manager, 0, this, 0);
  }

  m_ModuleManager = manager;

  connect(m_ModuleManager, SIGNAL(moduleRegistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleRegistered(const ctkCmdLineModuleReference&)));
  connect(m_ModuleManager, SIGNAL(moduleUnregistered(const ctkCmdLineModuleReference&)), this, SLOT(OnModuleUnRegistered(const ctkCmdLineModuleReference&)));
}

// -------------------------------------------------------------------------
ctkCmdLineModuleManager* QmitkCmdLineModuleMenuComboBox::GetManager() const
{
  return m_ModuleManager;
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleRegistered(const ctkCmdLineModuleReference& ref)
{
  this->RebuildMenu();
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::OnModuleUnRegistered(const ctkCmdLineModuleReference& ref)
{
  this->RebuildMenu();
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::AddName(
    QList< QHash<QString, QMenu*>* >& listOfHashMaps,
    const int& depth,
    const QString& name,
    QMenu* menu
    )
{
  if (depth >= listOfHashMaps.size())
  {
    int need = depth - listOfHashMaps.size();
    for (int i = 0; i <= need; i++)
    {
      QHash<QString, QMenu*> *newHashMap = new QHash<QString, QMenu*>();
      listOfHashMaps.push_back(newHashMap);
    }
  }
  listOfHashMaps[depth]->insert(name, menu);
}

// -------------------------------------------------------------------------
void QmitkCmdLineModuleMenuComboBox::RebuildMenu()
{
  if (m_ModuleManager == NULL)
  {
    qDebug() << "QmitkCmdLineModuleMenuComboBox::RebuildMenu(): Module Manager is NULL? Surely a bug?";
    return;
  }

  // Can't see another way to get a nested menu, without rebuilding the whole thing each time.
  // :-(

  QMenu *menu = new QMenu();
  QStringList listOfModules;

  QList<ctkCmdLineModuleReference> references = m_ModuleManager->moduleReferences();

  // Get full names
  for (int i = 0; i < references.size(); i++)
  {
    ctkCmdLineModuleReference reference = references[i];
    ctkCmdLineModuleDescription description = reference.description();
    QString title = description.title();
    QString category = description.category();
    QString fullName = category + "." + title;
    listOfModules << fullName;
  }

  // Sort list, so menu comes out in some sort of nice order.
  listOfModules.sort();

  // Temporary data structure to enable connecting menus together.
  QList< QHash<QString, QMenu*>* > list;

  // Iterate through all modules.
  foreach (QString fullName, listOfModules)
  {
    // Pointer to keep track of where we are in the menu tree.
    QMenu *currentMenu = menu;

    // Get individual parts, as they correspond to menu levels.
    QStringList nameParts = fullName.split(".", QString::SkipEmptyParts);

    // Iterate over each part, building up either a QMenu or QAction.
    for (int i = 0; i < nameParts.size(); i++)
    {
      QString part = nameParts[i];

      if (i != nameParts.size() - 1)
      {
        // Need to add a menu/submenu, not an action.
        if (list.size() <= i || list[i] == NULL || !list[i]->contains(part))
        {
          QMenu *newMenu = new QMenu(part);
          currentMenu->addMenu(newMenu);
          currentMenu = newMenu;

          // Add this newMenu pointer to temporary datastructure,
          // so we know we have already created it.
          this->AddName(list, i, part, newMenu);
        }
        else
        {
          currentMenu = list[i]->value(part);
        }
      }
      else
      {
        // Leaf node, just add the action.
        currentMenu->addAction(part);
      }
    }
  }

  // Clearup termporary data structure
  for (int i = 0; i < list.size(); i++)
  {
    delete list[i];
  }

  // Set the constructed menu on the base class combo box.
  this->setMenu(menu);
}

<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Math

#include "math.hpp"

#include <iostream>
#include <ostream>
#include <sstream>
#include <boost/test/included/unit_test.hpp>

using namespace Math;

const quat<float> R0{0,0,0,0}, R1{1,0,0,0},
	  i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};
const dual<float> E0{R0}, E1{R0, 1},
	  Ei = i*E1, Ej = j*E1, Ek = k*E1;

BOOST_AUTO_TEST_CASE(quaternions) {
	BOOST_REQUIRE(i*j == k);
	BOOST_REQUIRE(j*i == -k);
	BOOST_REQUIRE(i*i == -R1);
	BOOST_REQUIRE(j*j == -R1);
	BOOST_REQUIRE(k*k == -R1);
}

BOOST_AUTO_TEST_CASE(dual_quaternions) {
	BOOST_REQUIRE(E1 != 0);
	BOOST_REQUIRE(E1*E1 == 0);
}
<commit_msg>Added a test<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Math

#include "math.hpp"

#include <iostream>
#include <ostream>
#include <sstream>
#include <boost/test/included/unit_test.hpp>

using namespace Math;

const quat<float> R0{0,0,0,0}, R1{1,0,0,0},
	  i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};
const dual<float> E0{R0}, E1{R0, 1},
	  Ei = i*E1, Ej = j*E1, Ek = k*E1;

BOOST_AUTO_TEST_CASE(quaternions) {
	BOOST_REQUIRE(i*j == k);
	BOOST_REQUIRE(j*i == -k);
	BOOST_REQUIRE(i*i == -R1);
	BOOST_REQUIRE(j*j == -R1);
	BOOST_REQUIRE(k*k == -R1);
}

BOOST_AUTO_TEST_CASE(dual_quaternions) {
	BOOST_REQUIRE(E1 != 0);
	BOOST_REQUIRE(E1*E1 == 0);
	BOOST_REQUIRE((k*E1)*i != i*(k*E1));
}
<|endoftext|>