<commit_before>/*
 * File:   BoyerMoore.cpp
 * Author: Dimitar
 *
 * Created on June 9, 2015, 6:12 PM
 */

#include "BoyerMoore.hpp"
#include <iostream>
#include <string.h>

BoyerMoore::BoyerMoore(char* pattern) :
pattern(pattern) {
    this->pattern_length = strlen(pattern);

    border = new int[pattern_length + 1];
    shift = new int[pattern_length + 1];

    preprocess_bad_character_rule();
    preprocess_good_suffixes_rule_case1();
    preprocess_good_suffixes_rule_case2();
}

BoyerMoore::~BoyerMoore() {
    delete[] border;
    delete[] shift;
}

void BoyerMoore::preprocess_bad_character_rule() {
    for (int i = 0; i < pattern_length; ++i)
        bad_match_table[pattern[i]] = i;
}

void BoyerMoore::preprocess_good_suffixes_rule_case1() {

    for (int i = 0; i <= pattern_length; i++) {
        shift[i] = 0;
    }

    int i = pattern_length;
    int j = pattern_length + 1;
    border[i] = j;

    while (i > 0) {
        while (j <= pattern_length && pattern[i - 1] != pattern[j - 1]) {
            if (shift[j] == 0) shift[j] = j - i;
            j = border[j];
        }
        i--;
        j--;
        border[i] = j;
    }
}

void BoyerMoore::preprocess_good_suffixes_rule_case2() {
    int i;
    int j = border[0];

    for (i = 0; i <= pattern_length; i++) {
        if (shift[i] == 0) shift[i] = j;
        if (i == j) j = border[j];
    }

}

bool BoyerMoore::map_contains(int key) {
    std::unordered_map<int, int>::const_iterator got = bad_match_table.find(key);
    return got != bad_match_table.end();
}

int BoyerMoore::get_bad_char(int key) {
    if (map_contains(key))
        return bad_match_table[key];
    else return -1;
}

void BoyerMoore::test() {
    std::cout << "--- bad characters ---" << std::endl;
    for (std::unordered_map<int, int>::iterator it = bad_match_table.begin(); it != bad_match_table.end(); it++) {
        std::cout << char((*it).first) << " " << (*it).first << " " << (*it).second << std::endl;
    }
    std::cout << "---- good suffixes ---" << std::endl;
    for (int i = 0; i <= pattern_length; i++)
        std::cout << pattern[i] << " " << border[i] << std::endl;
    std::cout << "------shift-----------" << std::endl;
    for (int i = 0; i <= pattern_length; i++)
        std::cout << pattern[i] << " " << shift[i] << std::endl;
    std::cout << "----------------------" << std::endl;
}

<commit_msg>refactor<commit_after>/*
 * File:   BoyerMoore.cpp
 * Author: Dimitar
 *
 * Created on June 9, 2015, 6:12 PM
 */

#include "BoyerMoore.hpp"
#include <iostream>
#include <string.h>

BoyerMoore::BoyerMoore(char* pattern) :
pattern(pattern) {
    this->pattern_length = strlen(pattern);

    border = new int[pattern_length + 1];
    shift = new int[pattern_length + 1];

    for (int i = 0; i <= pattern_length; i++) {
        shift[i] = 0;
        border[i] = 0;
    }

    preprocess_bad_character_rule();
    preprocess_good_suffixes_rule_case1();
    preprocess_good_suffixes_rule_case2();
}

BoyerMoore::~BoyerMoore() {
    delete[] border;
    delete[] shift;
}

void BoyerMoore::preprocess_bad_character_rule() {
    for (int i = 0; i < pattern_length; ++i)
        bad_match_table[pattern[i]] = i;
}

void BoyerMoore::preprocess_good_suffixes_rule_case1() {

    int i = pattern_length;
    int j = pattern_length + 1;
    border[i] = j;

    while (i > 0) {
        while (j <= pattern_length && pattern[i - 1] != pattern[j - 1]) {
            if (shift[j] == 0) shift[j] = j - i;
            j = border[j];
        }
        i--;
        j--;
        border[i] = j;
    }
}

void BoyerMoore::preprocess_good_suffixes_rule_case2() {
    int i;
    int j = border[0];

    for (i = 0; i <= pattern_length; i++) {
        if (shift[i] == 0) shift[i] = j;
        if (i == j) j = border[j];
    }

}

bool BoyerMoore::map_contains(int key) {
    std::unordered_map<int, int>::const_iterator got = bad_match_table.find(key);
    return got != bad_match_table.end();
}

int BoyerMoore::get_bad_char(int key) {
    if (map_contains(key))
        return bad_match_table[key];
    else return -1;
}

void BoyerMoore::test() {
    std::cout << "--- bad characters ---" << std::endl;
    for (std::unordered_map<int, int>::iterator it = bad_match_table.begin(); it != bad_match_table.end(); it++) {
        std::cout << char((*it).first) << " " << (*it).first << " " << (*it).second << std::endl;
    }
    std::cout << "---- good suffixes ---" << std::endl;
    for (int i = 0; i <= pattern_length; i++)
        std::cout << pattern[i] << " " << border[i] << std::endl;
    std::cout << "------shift-----------" << std::endl;
    for (int i = 0; i <= pattern_length; i++)
        std::cout << pattern[i] << " " << shift[i] << std::endl;
    std::cout << "----------------------" << std::endl;
}

<|endoftext|>


<commit_before><commit_msg>Augment synonym with translated synonyms<commit_after><|endoftext|>


<commit_before><commit_msg>use Bcp47CountryEntry<commit_after><|endoftext|>


<commit_before><commit_msg>update output_dir variable, checking wether has slash or not at the end of folder's name<commit_after><|endoftext|>


<commit_before><commit_msg>CORE.cc: Move rate limiting logic to download() function<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 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 "views/controls/tabbed_pane/native_tabbed_pane_gtk.h"

#include <gtk/gtk.h>

#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, public:

NativeTabbedPaneGtk::NativeTabbedPaneGtk(TabbedPane* tabbed_pane)
    : NativeControlGtk(),
      tabbed_pane_(tabbed_pane) {
  set_focus_view(tabbed_pane);
}

NativeTabbedPaneGtk::~NativeTabbedPaneGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, NativeTabbedPaneWrapper implementation:

void NativeTabbedPaneGtk::AddTab(const std::wstring& title, View* contents) {
  AddTabAtIndex(GetTabCount(), title, contents, true);
}

void NativeTabbedPaneGtk::AddTabAtIndex(int index, const std::wstring& title,
                                        View* contents,
                                        bool select_if_first_tab) {
  DCHECK(native_view());
  DoAddTabAtIndex(index, title, contents, select_if_first_tab);
}

View* NativeTabbedPaneGtk::RemoveTabAtIndex(int index) {
  int tab_count = GetTabCount();
  DCHECK(index >= 0 && index < tab_count);

  if (index < (tab_count - 1)) {
    // Select the next tab.
    SelectTabAt(index + 1);
  } else {
    // We are the last tab, select the previous one.
    if (index > 0) {
      SelectTabAt(index - 1);
    } else {
      // last tab. nothing to select.
    }
  }

  GtkWidget* page =
      gtk_notebook_get_nth_page(GTK_NOTEBOOK(native_view()), index);
  WidgetGtk* widget = WidgetGtk::GetViewForNative(page);

  // detach the content view from widget so that we can delete widget
  // without destroying the content view.
  View* removed_tab = GetTabViewAt(index);
  widget->GetRootView()->RemoveChildView(removed_tab);

  // widget delete itself when native_view is deleted.
  gtk_notebook_remove_page(GTK_NOTEBOOK(native_view()), index);

  return removed_tab;
}

void NativeTabbedPaneGtk::SelectTabAt(int index) {
  DCHECK((index >= 0) && (index < GetTabCount()));
  gtk_notebook_set_current_page(GTK_NOTEBOOK(native_view()), index);
}

int NativeTabbedPaneGtk::GetTabCount() {
  return gtk_notebook_get_n_pages(GTK_NOTEBOOK(native_view()));
}

int NativeTabbedPaneGtk::GetSelectedTabIndex() {
  return gtk_notebook_get_current_page(GTK_NOTEBOOK(native_view()));
}

View* NativeTabbedPaneGtk::GetSelectedTab() {
  return GetTabViewAt(GetSelectedTabIndex());
}

View* NativeTabbedPaneGtk::GetView() {
  return this;
}

void NativeTabbedPaneGtk::SetFocus() {
  Focus();
}

gfx::NativeView NativeTabbedPaneGtk::GetTestingHandle() const {
  return native_view();
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, NativeControlGtk override:

void NativeTabbedPaneGtk::CreateNativeControl() {
  GtkWidget* widget = gtk_notebook_new();
  gtk_notebook_set_tab_pos(GTK_NOTEBOOK(widget), GTK_POS_TOP);
  g_signal_connect(G_OBJECT(widget), "switch-page",
                   G_CALLBACK(CallSwitchPage), this);
  NativeControlCreated(widget);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, private:
void NativeTabbedPaneGtk::DoAddTabAtIndex(int index, const std::wstring& title,
                                          View* contents,
                                          bool select_if_first_tab) {
  int tab_count = GetTabCount();
  DCHECK(index <= tab_count);

  WidgetGtk* page_container = new WidgetGtk(WidgetGtk::TYPE_CHILD);
  page_container->Init(NULL, gfx::Rect());
  page_container->SetContentsView(contents);
  page_container->Show();

  GtkWidget* page = page_container->GetNativeView();

  // increment ref count not to delete on remove below
  g_object_ref(page);
  // detach parent from the page so that we can add it to notebook
  GtkWidget* parent = gtk_widget_get_parent(page);
  gtk_container_remove(GTK_CONTAINER(parent), page);

  GtkWidget* label = gtk_label_new(WideToUTF8(title).c_str());
  gtk_widget_show(label);
  gtk_notebook_insert_page(GTK_NOTEBOOK(native_view()),
                           page,
                           label,
                           index);
  g_object_unref(page);

  if (tab_count == 0 && select_if_first_tab)
    gtk_notebook_set_current_page(GTK_NOTEBOOK(native_view()), 0);
}

View* NativeTabbedPaneGtk::GetTabViewAt(int index) {
  DCHECK(index <= GetTabCount());
  GtkWidget* page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(native_view()),
                                              index);
  WidgetGtk* widget = WidgetGtk::GetViewForNative(page);
  DCHECK(widget && widget->GetRootView()->GetChildViewCount() == 1);
  return widget->GetRootView()->GetChildViewAt(0);
}

void NativeTabbedPaneGtk::OnSwitchPage(int selected_tab_index) {
  TabbedPane::Listener* listener = tabbed_pane_->listener();
  if (listener != NULL)
    listener->TabSelectedAt(selected_tab_index);
}

// static
void NativeTabbedPaneGtk::CallSwitchPage(GtkNotebook* widget,
                                         GtkNotebookPage* page,
                                         guint selected_tab_index,
                                         NativeTabbedPaneGtk* tabbed_pane) {
  tabbed_pane->OnSwitchPage(selected_tab_index);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWrapper, public:

// static
NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(
    TabbedPane* tabbed_pane) {
  return new NativeTabbedPaneGtk(tabbed_pane);
}

}  // namespace views
<commit_msg>Set background to tabbed pane's content.<commit_after>// Copyright (c) 2009 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 "views/controls/tabbed_pane/native_tabbed_pane_gtk.h"

#include <gtk/gtk.h>

#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "skia/ext/skia_utils_gtk.h"
#include "views/background.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, public:

NativeTabbedPaneGtk::NativeTabbedPaneGtk(TabbedPane* tabbed_pane)
    : NativeControlGtk(),
      tabbed_pane_(tabbed_pane) {
  set_focus_view(tabbed_pane);
}

NativeTabbedPaneGtk::~NativeTabbedPaneGtk() {
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, NativeTabbedPaneWrapper implementation:

void NativeTabbedPaneGtk::AddTab(const std::wstring& title, View* contents) {
  AddTabAtIndex(GetTabCount(), title, contents, true);
}

void NativeTabbedPaneGtk::AddTabAtIndex(int index, const std::wstring& title,
                                        View* contents,
                                        bool select_if_first_tab) {
  DCHECK(native_view());
  DoAddTabAtIndex(index, title, contents, select_if_first_tab);
}

View* NativeTabbedPaneGtk::RemoveTabAtIndex(int index) {
  int tab_count = GetTabCount();
  DCHECK(index >= 0 && index < tab_count);

  if (index < (tab_count - 1)) {
    // Select the next tab.
    SelectTabAt(index + 1);
  } else {
    // We are the last tab, select the previous one.
    if (index > 0) {
      SelectTabAt(index - 1);
    } else {
      // last tab. nothing to select.
    }
  }

  GtkWidget* page =
      gtk_notebook_get_nth_page(GTK_NOTEBOOK(native_view()), index);
  WidgetGtk* widget = WidgetGtk::GetViewForNative(page);

  // detach the content view from widget so that we can delete widget
  // without destroying the content view.
  View* removed_tab = GetTabViewAt(index);
  widget->GetRootView()->RemoveChildView(removed_tab);

  // widget delete itself when native_view is deleted.
  gtk_notebook_remove_page(GTK_NOTEBOOK(native_view()), index);

  return removed_tab;
}

void NativeTabbedPaneGtk::SelectTabAt(int index) {
  DCHECK((index >= 0) && (index < GetTabCount()));
  gtk_notebook_set_current_page(GTK_NOTEBOOK(native_view()), index);
}

int NativeTabbedPaneGtk::GetTabCount() {
  return gtk_notebook_get_n_pages(GTK_NOTEBOOK(native_view()));
}

int NativeTabbedPaneGtk::GetSelectedTabIndex() {
  return gtk_notebook_get_current_page(GTK_NOTEBOOK(native_view()));
}

View* NativeTabbedPaneGtk::GetSelectedTab() {
  return GetTabViewAt(GetSelectedTabIndex());
}

View* NativeTabbedPaneGtk::GetView() {
  return this;
}

void NativeTabbedPaneGtk::SetFocus() {
  Focus();
}

gfx::NativeView NativeTabbedPaneGtk::GetTestingHandle() const {
  return native_view();
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, NativeControlGtk override:

void NativeTabbedPaneGtk::CreateNativeControl() {
  GtkWidget* widget = gtk_notebook_new();
  gtk_notebook_set_tab_pos(GTK_NOTEBOOK(widget), GTK_POS_TOP);
  g_signal_connect(G_OBJECT(widget), "switch-page",
                   G_CALLBACK(CallSwitchPage), this);
  NativeControlCreated(widget);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneGtk, private:
void NativeTabbedPaneGtk::DoAddTabAtIndex(int index, const std::wstring& title,
                                          View* contents,
                                          bool select_if_first_tab) {
  int tab_count = GetTabCount();
  DCHECK(index <= tab_count);

  WidgetGtk* page_container = new WidgetGtk(WidgetGtk::TYPE_CHILD);
  page_container->Init(NULL, gfx::Rect());
  page_container->SetContentsView(contents);
  page_container->Show();

  if (!contents->background()) {
    GtkStyle* window_style =
        gtk_widget_get_style(page_container->GetNativeView());
    contents->set_background(
        Background::CreateSolidBackground(
            skia::GdkColorToSkColor(window_style->bg[GTK_STATE_NORMAL])));
  }

  GtkWidget* page = page_container->GetNativeView();

  // increment ref count not to delete on remove below
  g_object_ref(page);
  // detach parent from the page so that we can add it to notebook
  GtkWidget* parent = gtk_widget_get_parent(page);
  gtk_container_remove(GTK_CONTAINER(parent), page);

  GtkWidget* label = gtk_label_new(WideToUTF8(title).c_str());
  gtk_widget_show(label);
  gtk_notebook_insert_page(GTK_NOTEBOOK(native_view()),
                           page,
                           label,
                           index);
  g_object_unref(page);

  if (tab_count == 0 && select_if_first_tab)
    gtk_notebook_set_current_page(GTK_NOTEBOOK(native_view()), 0);
}

View* NativeTabbedPaneGtk::GetTabViewAt(int index) {
  DCHECK(index <= GetTabCount());
  GtkWidget* page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(native_view()),
                                              index);
  WidgetGtk* widget = WidgetGtk::GetViewForNative(page);
  DCHECK(widget && widget->GetRootView()->GetChildViewCount() == 1);
  return widget->GetRootView()->GetChildViewAt(0);
}

void NativeTabbedPaneGtk::OnSwitchPage(int selected_tab_index) {
  TabbedPane::Listener* listener = tabbed_pane_->listener();
  if (listener != NULL)
    listener->TabSelectedAt(selected_tab_index);
}

// static
void NativeTabbedPaneGtk::CallSwitchPage(GtkNotebook* widget,
                                         GtkNotebookPage* page,
                                         guint selected_tab_index,
                                         NativeTabbedPaneGtk* tabbed_pane) {
  tabbed_pane->OnSwitchPage(selected_tab_index);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWrapper, public:

// static
NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper(
    TabbedPane* tabbed_pane) {
  return new NativeTabbedPaneGtk(tabbed_pane);
}

}  // namespace views
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_ENGINE_SMOOTHMESHENGINE_INL
#define SOFA_COMPONENT_ENGINE_SMOOTHMESHENGINE_INL

#if !defined(__GNUC__) || (__GNUC__ > 3 || (_GNUC__ == 3 && __GNUC_MINOR__ > 3))
#pragma once
#endif

#include "SmoothMeshEngine.h"
#include <sofa/helper/gl/template.h>

#include <sofa/core/visual/VisualParams.h>

namespace sofa
{

namespace component
{

namespace engine
{

using namespace sofa::helper;
using namespace sofa::defaulttype;
using namespace core::objectmodel;

template <class DataTypes>
SmoothMeshEngine<DataTypes>::SmoothMeshEngine()
    : input_position( initData (&input_position, "input_position", "Input position") )
    , input_indices( initData (&input_indices, "input_indices", "Position indices that need to be smoothed") )
    , output_position( initData (&output_position, "output_position", "Output position") )
    , nb_iterations( initData (&nb_iterations, (unsigned int)1, "nb_iterations", "Number of iterations of laplacian smoothing") )
    , showInput( initData (&showInput, false, "showInput", "showInput") )
    , showOutput( initData (&showOutput, false, "showOutput", "showOutput") )
{

}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::init()
{
    m_topo = this->getContext()->getMeshTopology();
    if (!m_topo)
        serr << "SmoothMeshEngine requires a mesh topology" << sendl;

    addInput(&input_position);
    addOutput(&output_position);

    setDirtyValue();
}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::reinit()
{
    update();
}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::update()
{
    cleanDirty();

    if (!m_topo) return;

    helper::ReadAccessor< Data<VecCoord> > in(input_position);
    helper::ReadAccessor< Data<helper::vector <unsigned int > > > indices(input_indices);
    helper::WriteAccessor< Data<VecCoord> > out(output_position);

    out.resize(in.size());
    for (unsigned int i =0; i<in.size();i++) out[i] = in[i];

    for (unsigned int n=0; n < nb_iterations.getValue(); n++)
    {
        VecCoord t;
        t.resize(out.size());

        if(!indices.size())
        {
            for (unsigned int i = 0; i < out.size(); i++)
            {
                BaseMeshTopology::VerticesAroundVertex v = m_topo->getVerticesAroundVertex(i);
                Coord p = Coord();
                for (unsigned int j = 0; j < v.size(); j++)
                    p += out[v[j]];
                t[i] = p / v.size();
            }
        }
        else
        {
            // init
            for (unsigned int i = 0; i < out.size(); i++)
            {

                t[i] = in[i];
            }
            for(unsigned int i = 0; i < indices.size(); i++)
            {
                BaseMeshTopology::VerticesAroundVertex v = m_topo->getVerticesAroundVertex(i);
                Coord p = Coord();
                for (unsigned int j = 0; j < v.size(); j++)
                    p += out[v[j]];
                t[i] = p / v.size();
            }
        }
        for (unsigned int i = 0; i < out.size(); i++) out[i] = t[i];
    }

}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
#ifndef SOFA_NO_OPENGL
    if (!vparams->displayFlags().getShowVisualModels()) return;

    bool wireframe=vparams->displayFlags().getShowWireFrame();

    BaseMeshTopology::SeqTriangles tri = m_topo->getTriangles();

    glPushAttrib( GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_LINE_BIT | GL_CURRENT_BIT);
    glEnable( GL_LIGHTING);

    if (this->showInput.getValue())
    {
        helper::ReadAccessor< Data<VecCoord> > in(input_position);

        float color[]= {1.0,0.76078431372,0.,0.}, specular[]= {0.,0.,0.,0.};
        glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color);
        glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular);
        glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,0.0);

        if(!wireframe) glBegin(GL_TRIANGLES);
        for (unsigned int i=0; i<tri.size(); ++i)
        {
            if(wireframe) glBegin(GL_LINE_LOOP);
            const Vec<3,Real>& a = in[ tri[i][0] ];
            const Vec<3,Real>& b = in[ tri[i][1] ];
            const Vec<3,Real>& c = in[ tri[i][2] ];
            Vec<3,Real> n = cross((a-b),(a-c));	n.normalize();
            glNormal3d(n[0],n[1],n[2]);

            glVertex3d(a[0],a[1],a[2]);
            glVertex3d(b[0],b[1],b[2]);
            glVertex3d(c[0],c[1],c[2]);

            if(wireframe)  glEnd();
        }
        if(!wireframe) glEnd();
    }

    if (this->showOutput.getValue())
    {
        helper::ReadAccessor< Data<VecCoord> > out(output_position);

        float color[]= {0.,0.6,0.8,0.}, specular[]= {0.,0.,0.,0.};
        glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color);
        glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular);
        glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,0.0);

        if(!wireframe) glBegin(GL_TRIANGLES);
        for (unsigned int i=0; i<tri.size(); ++i)
        {
            if(wireframe) glBegin(GL_LINE_LOOP);
            const Vec<3,Real>& a = out[ tri[i][0] ];
            const Vec<3,Real>& b = out[ tri[i][1] ];
            const Vec<3,Real>& c = out[ tri[i][2] ];
            Vec<3,Real> n = cross((a-b),(a-c));	n.normalize();
            glNormal3d(n[0],n[1],n[2]);

            glVertex3d(a[0],a[1],a[2]);
            glVertex3d(b[0],b[1],b[2]);
            glVertex3d(c[0],c[1],c[2]);

            if(wireframe)  glEnd();
        }
        if(!wireframe) glEnd();
    }

    glPopAttrib();

#endif
}

} // namespace engine

} // namespace component

} // namespace sofa

#endif
<commit_msg>r11317/sofa : FIX: smooth engine, indices correction<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_ENGINE_SMOOTHMESHENGINE_INL
#define SOFA_COMPONENT_ENGINE_SMOOTHMESHENGINE_INL

#if !defined(__GNUC__) || (__GNUC__ > 3 || (_GNUC__ == 3 && __GNUC_MINOR__ > 3))
#pragma once
#endif

#include "SmoothMeshEngine.h"
#include <sofa/helper/gl/template.h>

#include <sofa/core/visual/VisualParams.h>

namespace sofa
{

namespace component
{

namespace engine
{

using namespace sofa::helper;
using namespace sofa::defaulttype;
using namespace core::objectmodel;

template <class DataTypes>
SmoothMeshEngine<DataTypes>::SmoothMeshEngine()
    : input_position( initData (&input_position, "input_position", "Input position") )
    , input_indices( initData (&input_indices, "input_indices", "Position indices that need to be smoothed") )
    , output_position( initData (&output_position, "output_position", "Output position") )
    , nb_iterations( initData (&nb_iterations, (unsigned int)1, "nb_iterations", "Number of iterations of laplacian smoothing") )
    , showInput( initData (&showInput, false, "showInput", "showInput") )
    , showOutput( initData (&showOutput, false, "showOutput", "showOutput") )
{

}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::init()
{
    m_topo = this->getContext()->getMeshTopology();
    if (!m_topo)
        serr << "SmoothMeshEngine requires a mesh topology" << sendl;

    addInput(&input_position);
    addOutput(&output_position);

    setDirtyValue();
}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::reinit()
{
    update();
}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::update()
{
    cleanDirty();

    if (!m_topo) return;

    helper::ReadAccessor< Data<VecCoord> > in(input_position);
    helper::ReadAccessor< Data<helper::vector <unsigned int > > > indices(input_indices);
    helper::WriteAccessor< Data<VecCoord> > out(output_position);

    out.resize(in.size());
    for (unsigned int i =0; i<in.size();i++) out[i] = in[i];

    for (unsigned int n=0; n < nb_iterations.getValue(); n++)
    {
        VecCoord t;
        t.resize(out.size());

        if(!indices.size())
        {
            for (unsigned int i = 0; i < out.size(); i++)
            {
                BaseMeshTopology::VerticesAroundVertex v = m_topo->getVerticesAroundVertex(i);
                Coord p = Coord();
                for (unsigned int j = 0; j < v.size(); j++)
                    p += out[v[j]];
                t[i] = p / v.size();
            }
        }
        else
        {
            // init
            for (unsigned int i = 0; i < out.size(); i++)
            {

                t[i] = out[i];
            }
            for(unsigned int i = 0; i < indices.size(); i++)
            {
                BaseMeshTopology::VerticesAroundVertex v = m_topo->getVerticesAroundVertex(indices[i]);
                Coord p = Coord();
                for (unsigned int j = 0; j < v.size(); j++)
                    p += out[v[j]];
                t[indices[i]] = p / v.size();
            }
        }
        for (unsigned int i = 0; i < out.size(); i++) out[i] = t[i];
    }

}

template <class DataTypes>
void SmoothMeshEngine<DataTypes>::draw(const core::visual::VisualParams* vparams)
{
#ifndef SOFA_NO_OPENGL
    if (!vparams->displayFlags().getShowVisualModels()) return;

    bool wireframe=vparams->displayFlags().getShowWireFrame();

    BaseMeshTopology::SeqTriangles tri = m_topo->getTriangles();

    glPushAttrib( GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_LINE_BIT | GL_CURRENT_BIT);
    glEnable( GL_LIGHTING);

    if (this->showInput.getValue())
    {
        helper::ReadAccessor< Data<VecCoord> > in(input_position);

        float color[]= {1.0,0.76078431372,0.,0.}, specular[]= {0.,0.,0.,0.};
        glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color);
        glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular);
        glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,0.0);

        if(!wireframe) glBegin(GL_TRIANGLES);
        for (unsigned int i=0; i<tri.size(); ++i)
        {
            if(wireframe) glBegin(GL_LINE_LOOP);
            const Vec<3,Real>& a = in[ tri[i][0] ];
            const Vec<3,Real>& b = in[ tri[i][1] ];
            const Vec<3,Real>& c = in[ tri[i][2] ];
            Vec<3,Real> n = cross((a-b),(a-c));	n.normalize();
            glNormal3d(n[0],n[1],n[2]);

            glVertex3d(a[0],a[1],a[2]);
            glVertex3d(b[0],b[1],b[2]);
            glVertex3d(c[0],c[1],c[2]);

            if(wireframe)  glEnd();
        }
        if(!wireframe) glEnd();
    }

    if (this->showOutput.getValue())
    {
        helper::ReadAccessor< Data<VecCoord> > out(output_position);

        float color[]= {0.,0.6,0.8,0.}, specular[]= {0.,0.,0.,0.};
        glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color);
        glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular);
        glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,0.0);

        if(!wireframe) glBegin(GL_TRIANGLES);
        for (unsigned int i=0; i<tri.size(); ++i)
        {
            if(wireframe) glBegin(GL_LINE_LOOP);
            const Vec<3,Real>& a = out[ tri[i][0] ];
            const Vec<3,Real>& b = out[ tri[i][1] ];
            const Vec<3,Real>& c = out[ tri[i][2] ];
            Vec<3,Real> n = cross((a-b),(a-c));	n.normalize();
            glNormal3d(n[0],n[1],n[2]);

            glVertex3d(a[0],a[1],a[2]);
            glVertex3d(b[0],b[1],b[2]);
            glVertex3d(c[0],c[1],c[2]);

            if(wireframe)  glEnd();
        }
        if(!wireframe) glEnd();
    }

    glPopAttrib();

#endif
}

} // namespace engine

} // namespace component

} // namespace sofa

#endif
<|endoftext|>


<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2006 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

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

#include <vpr/md/SIM/DNS.h>         /* for simulated DNS lookups... */
#include <vpr/md/SIM/IO/Socket/InetAddrSIM.h>
#include <vpr/System.h>

namespace vpr
{
   const InetAddrSIM InetAddrSIM::AnyAddr;

   vpr::InetAddrSIM InetAddrSIM::getLocalHost()
   {
      throw UnknownHostException("No IP address for could be found for localhost.",
                                 VPR_LOCATION);
      return vpr::InetAddrSIM;
   }

   void InetAddrSIM::setAddress(const std::string& address)
   {
      std::string::size_type pos;
      std::string host_addr, host_port;
      vpr::Uint32 port;

      // Extract the address and the port number from the given string.
      pos       = address.find( ":" );
      host_addr = address.substr( 0, pos );
      host_port = address.substr( pos + 1 );
      port      = (vpr::Uint32) atoi( host_port.c_str() );

      //setAddress( host_addr );
      mAddress = vpr::sim::DNS::instance()->lookupAddress( host_addr );
      setPort( port );
      setFamily( vpr::SocketTypes::INET );
      setDebugData();
   }

   void InetAddrSIM::setAddress(const std::string& address,
                                             const vpr::Uint32 port)
   {
      mAddress = vpr::sim::DNS::instance()->lookupAddress(address);
      setPort( port );
      setFamily( vpr::SocketTypes::INET );
      setDebugData();
   }

   std::string InetAddrSIM::getAddressString() const
   {
      char buffer[sizeof("255.255.255.255")];

      union
      {
         vpr::Uint8 bytes[sizeof(vpr::Uint32)];
         vpr::Uint32 value;
      } addr;

      addr.value = vpr::System::Htonl(mAddress);
      memset(buffer, '\0', sizeof(buffer));
      sprintf(buffer, "%u.%u.%u.%u", addr.bytes[0], addr.bytes[1],
              addr.bytes[2], addr.bytes[3]);
      //std::string result = buffer;

      return std::string(buffer);
   }

} // End of vpr namespace
<commit_msg>- Coding standard.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2006 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

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

#include <vpr/md/SIM/DNS.h>         /* for simulated DNS lookups... */
#include <vpr/md/SIM/IO/Socket/InetAddrSIM.h>
#include <vpr/System.h>

namespace vpr
{
const InetAddrSIM InetAddrSIM::AnyAddr;

vpr::InetAddrSIM InetAddrSIM::getLocalHost()
{
   throw UnknownHostException("No IP address for could be found for localhost.",
                              VPR_LOCATION);
   return vpr::InetAddrSIM;
}

void InetAddrSIM::setAddress(const std::string& address)
{
   std::string::size_type pos;
   std::string host_addr, host_port;
   vpr::Uint32 port;

   // Extract the address and the port number from the given string.
   pos       = address.find( ":" );
   host_addr = address.substr( 0, pos );
   host_port = address.substr( pos + 1 );
   port      = (vpr::Uint32) atoi( host_port.c_str() );

   //setAddress( host_addr );
   mAddress = vpr::sim::DNS::instance()->lookupAddress( host_addr );
   setPort( port );
   setFamily( vpr::SocketTypes::INET );
   setDebugData();
}

void InetAddrSIM::setAddress(const std::string& address,
                                          const vpr::Uint32 port)
{
   mAddress = vpr::sim::DNS::instance()->lookupAddress(address);
   setPort( port );
   setFamily( vpr::SocketTypes::INET );
   setDebugData();
}

std::string InetAddrSIM::getAddressString() const
{
   char buffer[sizeof("255.255.255.255")];

   union
   {
      vpr::Uint8 bytes[sizeof(vpr::Uint32)];
      vpr::Uint32 value;
   } addr;

   addr.value = vpr::System::Htonl(mAddress);
   memset(buffer, '\0', sizeof(buffer));
   sprintf(buffer, "%u.%u.%u.%u", addr.bytes[0], addr.bytes[1],
           addr.bytes[2], addr.bytes[3]);
   //std::string result = buffer;

   return std::string(buffer);
}

} // End of vpr namespace
<|endoftext|>


<commit_before>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <QApplication>
#include <QComboBox>
#include <QLabel>
#include <QLayout>
#include <QTimer>
#include <QToolButton>

//Added by qt3to4:
#include <QHBoxLayout>
#include <QKeyEvent>

#include <kdialog.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>

#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget( QWidget *parent, const char *name )
    : QWidget( parent )
{
  setObjectName( name );
  QHBoxLayout *layout = new QHBoxLayout( this );
  layout->setSpacing( KDialog::spacingHint() );
  layout->setMargin( 2 );

  QToolButton *button = new QToolButton( this );
  button->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
  button->setIcon( SmallIcon( QApplication::isRightToLeft() ? "clear-left" : "locationbar-erase" ) );
  button->setShortcut( QKeySequence( Qt::CTRL+Qt::ALT+Qt::Key_S ) );
  button->setAutoRaise( true );
  button->setToolTip( i18n( "Reset" ) );
  layout->addWidget( button );

  QLabel *label = new QLabel( i18n( "Search:" ), this );
  label->setObjectName( "kde toolbar widget" );
  label->setAlignment( Qt::AlignVCenter | Qt::AlignRight );
  layout->addWidget( label );

  mSearchText = new KLineEdit( this );
  mSearchText->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Preferred );
  mSearchText->setWhatsThis( i18n( "The incremental search
Enter some text here will start the search for the contact, which matches the search pattern best. The part of the contact, which will be used for matching, depends on the field selection." ) );
  label->setBuddy( mSearchText );
  layout->addWidget( mSearchText );

  label = new QLabel( i18nc( "as in 'Search in:'", "&in:" ), this );
  label->setObjectName( "kde toolbar widget" );
  label->setAlignment( Qt::AlignVCenter | Qt::AlignRight );
  layout->addWidget( label );

  mFieldCombo = new QComboBox( this );
  mFieldCombo->setEditable( false );
  layout->addWidget( mFieldCombo );
  label->setBuddy(mFieldCombo);

  mFieldCombo->setToolTip( i18n( "Select incremental search field" ) );
  mFieldCombo->setWhatsThis( i18n( "Here you can choose the field, which shall be used for incremental search." ) );

  mInputTimer = new QTimer( this );
  mInputTimer->setSingleShot( true );

  connect( mInputTimer, SIGNAL( timeout() ),
           SLOT( timeout() ) );
  connect( mSearchText, SIGNAL( textChanged( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( mSearchText, SIGNAL( returnPressed() ),
           SLOT( announceDoSearch() ) );
  connect( mFieldCombo, SIGNAL( activated( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( button, SIGNAL( clicked() ),
           mSearchText, SLOT( clear() ) );
  connect( button, SIGNAL( clicked() ),
           SLOT( announceDoSearch() ) );

  initFields();

  mSearchText->installEventFilter( this );

  setFocusProxy( mSearchText );
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::announceDoSearch()
{
  if ( mInputTimer->isActive() )
    mInputTimer->stop();

  mInputTimer->start( 0 );
}

void IncSearchWidget::timeout()
{
  emit doSearch( mSearchText->text() );
}

void IncSearchWidget::initFields()
{
  mFieldList = KABC::Field::allFields();

  mFieldCombo->clear();
  mFieldCombo->addItem( i18n( "Visible Fields" ) );
  mFieldCombo->addItem( i18n( "All Fields" ) );

  KABC::Field::List::ConstIterator it;
  for ( it = mFieldList.begin(); it != mFieldList.end(); ++it )
    mFieldCombo->addItem( (*it)->label() );

  announceDoSearch();
}

KABC::Field::List IncSearchWidget::currentFields() const
{
  KABC::Field::List fieldList;

  if ( mFieldCombo->currentIndex() == 0 )
    fieldList = mViewFields;
  else if ( mFieldCombo->currentIndex() > 1 )
    fieldList.append( mFieldList[ mFieldCombo->currentIndex() - 2 ] );

  return fieldList;
}

void IncSearchWidget::setCurrentItem( int pos )
{
  mFieldCombo->setCurrentIndex( pos );
}

int IncSearchWidget::currentItem() const
{
  return mFieldCombo->currentIndex();
}

void IncSearchWidget::setViewFields( const KABC::Field::List &fields )
{
  mViewFields = fields;
}

void IncSearchWidget::clear()
{
  mSearchText->clear();
}

void IncSearchWidget::keyPressEvent( QKeyEvent *event )
{
  if ( event->key() == Qt::Key_Up ) {
    event->accept();
    emit scrollUp();
  } else if ( event->key() == Qt::Key_Down ) {
    event->accept();
    emit scrollDown();
  }
}

#include "incsearchwidget.moc"
<commit_msg>Clear button not necessary<commit_after>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <QApplication>
#include <QComboBox>
#include <QLabel>
#include <QLayout>
#include <QTimer>
#include <QToolButton>

//Added by qt3to4:
#include <QHBoxLayout>
#include <QKeyEvent>

#include <kdialog.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>

#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget( QWidget *parent, const char *name )
    : QWidget( parent )
{
  setObjectName( name );
  QHBoxLayout *layout = new QHBoxLayout( this );
  layout->setSpacing( KDialog::spacingHint() );
  layout->setMargin( 2 );

  QLabel *label = new QLabel( i18n( "Search:" ), this );
  label->setObjectName( "kde toolbar widget" );
  label->setAlignment( Qt::AlignVCenter | Qt::AlignRight );
  layout->addWidget( label );

  mSearchText = new KLineEdit( this );
  mSearchText->setClearButtonShown(true);
  mSearchText->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Preferred );
  mSearchText->setWhatsThis( i18n( "The incremental search
Enter some text here will start the search for the contact, which matches the search pattern best. The part of the contact, which will be used for matching, depends on the field selection." ) );
  label->setBuddy( mSearchText );
  layout->addWidget( mSearchText );

  label = new QLabel( i18nc( "as in 'Search in:'", "&in:" ), this );
  label->setObjectName( "kde toolbar widget" );
  label->setAlignment( Qt::AlignVCenter | Qt::AlignRight );
  layout->addWidget( label );

  mFieldCombo = new QComboBox( this );
  mFieldCombo->setEditable( false );
  layout->addWidget( mFieldCombo );
  label->setBuddy(mFieldCombo);

  mFieldCombo->setToolTip( i18n( "Select incremental search field" ) );
  mFieldCombo->setWhatsThis( i18n( "Here you can choose the field, which shall be used for incremental search." ) );

  mInputTimer = new QTimer( this );
  mInputTimer->setSingleShot( true );

  connect( mInputTimer, SIGNAL( timeout() ),
           SLOT( timeout() ) );
  connect( mSearchText, SIGNAL( textChanged( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( mSearchText, SIGNAL( returnPressed() ),
           SLOT( announceDoSearch() ) );
  connect( mFieldCombo, SIGNAL( activated( const QString& ) ),
           SLOT( announceDoSearch() ) );
  connect( mSearchText, SIGNAL( clearButtonClicked() ),
           SLOT( announceDoSearch() ) );

  initFields();

  mSearchText->installEventFilter( this );

  setFocusProxy( mSearchText );
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::announceDoSearch()
{
  if ( mInputTimer->isActive() )
    mInputTimer->stop();

  mInputTimer->start( 0 );
}

void IncSearchWidget::timeout()
{
  emit doSearch( mSearchText->text() );
}

void IncSearchWidget::initFields()
{
  mFieldList = KABC::Field::allFields();

  mFieldCombo->clear();
  mFieldCombo->addItem( i18n( "Visible Fields" ) );
  mFieldCombo->addItem( i18n( "All Fields" ) );

  KABC::Field::List::ConstIterator it;
  for ( it = mFieldList.begin(); it != mFieldList.end(); ++it )
    mFieldCombo->addItem( (*it)->label() );

  announceDoSearch();
}

KABC::Field::List IncSearchWidget::currentFields() const
{
  KABC::Field::List fieldList;

  if ( mFieldCombo->currentIndex() == 0 )
    fieldList = mViewFields;
  else if ( mFieldCombo->currentIndex() > 1 )
    fieldList.append( mFieldList[ mFieldCombo->currentIndex() - 2 ] );

  return fieldList;
}

void IncSearchWidget::setCurrentItem( int pos )
{
  mFieldCombo->setCurrentIndex( pos );
}

int IncSearchWidget::currentItem() const
{
  return mFieldCombo->currentIndex();
}

void IncSearchWidget::setViewFields( const KABC::Field::List &fields )
{
  mViewFields = fields;
}

void IncSearchWidget::clear()
{
  mSearchText->clear();
}

void IncSearchWidget::keyPressEvent( QKeyEvent *event )
{
  if ( event->key() == Qt::Key_Up ) {
    event->accept();
    emit scrollUp();
  } else if ( event->key() == Qt::Key_Down ) {
    event->accept();
    emit scrollDown();
  }
}

#include "incsearchwidget.moc"
<|endoftext|>


<commit_before>/**
 * \file
 * \brief MessageQueueBase class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-10-21
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_

#include "distortos/Semaphore.hpp"

#include "distortos/synchronization/QueueFunctor.hpp"
#include "distortos/synchronization/SemaphoreFunctor.hpp"

#include "distortos/allocators/FeedablePool.hpp"

#include <forward_list>

namespace distortos
{

namespace synchronization
{

/// MessageQueueBase class implements basic functionality of MessageQueue template class
class MessageQueueBase
{
public:

	/// entry in the MessageQueueBase
	struct Entry
	{
		/**
		 * \brief Entry's constructor
		 *
		 * \param [in] priorityy is the priority of the entry
		 * \param [in] storagee is the storage for the entry
		 */

		constexpr Entry(const uint8_t priorityy, void* const storagee) :
				priority{priorityy},
				storage{storagee}
		{

		}

		/// default copy constructor
		constexpr Entry(const Entry&) = default;

		/// priority of the entry
		uint8_t priority;

		/// storage for the entry
		void* storage;
	};

	/// link and Entry
	using LinkAndEntry = std::pair<void*, Entry>;

	/// type of uninitialized storage for Entry with link
	using EntryStorage = typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type;

	/**
	 * type of uninitialized storage for value
	 *
	 * \param T is the type of data in queue
	 */

	template<typename T>
	using ValueStorage = typename std::aligned_storage<sizeof(T), alignof(T)>::type;

	/// functor which gives descending priority order of elements on the list
	struct DescendingPriority
	{
		/**
		 * \brief DescendingPriority's function call operator
		 *
		 * \param [in] left is the object on the left side of comparison
		 * \param [in] right is the object on the right side of comparison
		 *
		 * \return true if left's priority is less than right's priority
		 */

		bool operator()(const Entry& left, const Entry& right) const
		{
			return left.priority < right.priority;
		}
	};

	/// type of pool
	using Pool = allocators::FeedablePool;

	/// type of pool allocator
	using PoolAllocator = allocators::PoolAllocator<Entry, Pool>;

	/// type of free entry list
	using FreeEntryList = std::forward_list<Entry, PoolAllocator>;

	/// type of entry list
	using EntryList = containers::SortedContainer<FreeEntryList, DescendingPriority>;

	/**
	 * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push()
	 * operations.
	 *
	 * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_.
	 * It should perform common actions and execute the QueueFunctor passed from callers.
	 */

	class InternalFunctor : public estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)>
	{

	};

	/**
	 * \brief MessageQueueBase's constructor
	 *
	 * \param [in] entryStorage is an array of EntryStorage elements
	 * \param [in] valueStorage is a memory block for elements, sufficiently large for \a maxElements, each
	 * \a elementSize bytes long
	 * \param [in] elementSize is the size of single queue element, bytes
	 * \param [in] maxElements is the number of elements in \a entryStorage array and valueStorage memory block
	 */

	MessageQueueBase(EntryStorage* entryStorage, void* valueStorage, size_t elementSize, size_t maxElements);

	/**
	 * \brief MessageQueueBase's destructor
	 */

	~MessageQueueBase();

	/**
	 * \brief Implementation of pop() using type-erased functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
	 * \param [out] priority is a reference to variable that will be used to return priority of popped value
	 * \param [in] functor is a reference to QueueFunctor which will execute actions related to popping - it will get a
	 * pointer to storage with element
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const QueueFunctor& functor);

	/**
	 * \brief Implementation of push() using type-erased functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
	 * \param [in] priority is the priority of new element
	 * \param [in] functor is a reference to QueueFunctor which will execute actions related to pushing - it will get a
	 * pointer to storage for element
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const QueueFunctor& functor);

private:

	/**
	 * \brief Implementation of pop() and push() using type-erased internal functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore
	 * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to
	 * popping/pushing
	 * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a
	 * pushSemaphore_ for push()
	 * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_
	 * for pop(), \a popSemaphore_ for push()
	 *
	 * \return zero if operation was successful, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor,
			Semaphore& waitSemaphore, Semaphore& postSemaphore);

	/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
	Semaphore popSemaphore_;

	/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
	Semaphore pushSemaphore_;

	/// FeedablePool used by \a poolAllocator_
	Pool pool_;

	/// PoolAllocator used by \a entryList_ and \a freeList_
	PoolAllocator poolAllocator_;

	/// list of available entries, sorted in descending order of priority
	EntryList entryList_;

	/// list of "free" entries
	FreeEntryList freeEntryList_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
<commit_msg>MessageQueueBase: add EntryStorageUniquePointer type alias<commit_after>/**
 * \file
 * \brief MessageQueueBase class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-10-22
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_

#include "distortos/Semaphore.hpp"

#include "distortos/memory/StorageUniquePointer.hpp"

#include "distortos/synchronization/QueueFunctor.hpp"
#include "distortos/synchronization/SemaphoreFunctor.hpp"

#include "distortos/allocators/FeedablePool.hpp"

#include <forward_list>

namespace distortos
{

namespace synchronization
{

/// MessageQueueBase class implements basic functionality of MessageQueue template class
class MessageQueueBase
{
public:

	/// entry in the MessageQueueBase
	struct Entry
	{
		/**
		 * \brief Entry's constructor
		 *
		 * \param [in] priorityy is the priority of the entry
		 * \param [in] storagee is the storage for the entry
		 */

		constexpr Entry(const uint8_t priorityy, void* const storagee) :
				priority{priorityy},
				storage{storagee}
		{

		}

		/// default copy constructor
		constexpr Entry(const Entry&) = default;

		/// priority of the entry
		uint8_t priority;

		/// storage for the entry
		void* storage;
	};

	/// link and Entry
	using LinkAndEntry = std::pair<void*, Entry>;

	/// type of uninitialized storage for Entry with link
	using EntryStorage = typename std::aligned_storage<sizeof(LinkAndEntry), alignof(LinkAndEntry)>::type;

	/// unique_ptr (with deleter) to EntryStorage[]
	using EntryStorageUniquePointer = std::unique_ptr<EntryStorage[], memory::StorageUniquePointer::deleter_type>;

	/**
	 * type of uninitialized storage for value
	 *
	 * \param T is the type of data in queue
	 */

	template<typename T>
	using ValueStorage = typename std::aligned_storage<sizeof(T), alignof(T)>::type;

	/// functor which gives descending priority order of elements on the list
	struct DescendingPriority
	{
		/**
		 * \brief DescendingPriority's function call operator
		 *
		 * \param [in] left is the object on the left side of comparison
		 * \param [in] right is the object on the right side of comparison
		 *
		 * \return true if left's priority is less than right's priority
		 */

		bool operator()(const Entry& left, const Entry& right) const
		{
			return left.priority < right.priority;
		}
	};

	/// type of pool
	using Pool = allocators::FeedablePool;

	/// type of pool allocator
	using PoolAllocator = allocators::PoolAllocator<Entry, Pool>;

	/// type of free entry list
	using FreeEntryList = std::forward_list<Entry, PoolAllocator>;

	/// type of entry list
	using EntryList = containers::SortedContainer<FreeEntryList, DescendingPriority>;

	/**
	 * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push()
	 * operations.
	 *
	 * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_.
	 * It should perform common actions and execute the QueueFunctor passed from callers.
	 */

	class InternalFunctor : public estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)>
	{

	};

	/**
	 * \brief MessageQueueBase's constructor
	 *
	 * \param [in] entryStorage is an array of EntryStorage elements
	 * \param [in] valueStorage is a memory block for elements, sufficiently large for \a maxElements, each
	 * \a elementSize bytes long
	 * \param [in] elementSize is the size of single queue element, bytes
	 * \param [in] maxElements is the number of elements in \a entryStorage array and valueStorage memory block
	 */

	MessageQueueBase(EntryStorage* entryStorage, void* valueStorage, size_t elementSize, size_t maxElements);

	/**
	 * \brief MessageQueueBase's destructor
	 */

	~MessageQueueBase();

	/**
	 * \brief Implementation of pop() using type-erased functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
	 * \param [out] priority is a reference to variable that will be used to return priority of popped value
	 * \param [in] functor is a reference to QueueFunctor which will execute actions related to popping - it will get a
	 * pointer to storage with element
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const QueueFunctor& functor);

	/**
	 * \brief Implementation of push() using type-erased functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
	 * \param [in] priority is the priority of new element
	 * \param [in] functor is a reference to QueueFunctor which will execute actions related to pushing - it will get a
	 * pointer to storage for element
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const QueueFunctor& functor);

private:

	/**
	 * \brief Implementation of pop() and push() using type-erased internal functor
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore
	 * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to
	 * popping/pushing
	 * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a
	 * pushSemaphore_ for push()
	 * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_
	 * for pop(), \a popSemaphore_ for push()
	 *
	 * \return zero if operation was successful, error code otherwise:
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor,
			Semaphore& waitSemaphore, Semaphore& postSemaphore);

	/// semaphore guarding access to "pop" functions - its value is equal to the number of available elements
	Semaphore popSemaphore_;

	/// semaphore guarding access to "push" functions - its value is equal to the number of free slots
	Semaphore pushSemaphore_;

	/// FeedablePool used by \a poolAllocator_
	Pool pool_;

	/// PoolAllocator used by \a entryList_ and \a freeList_
	PoolAllocator poolAllocator_;

	/// list of available entries, sorted in descending order of priority
	EntryList entryList_;

	/// list of "free" entries
	FreeEntryList freeEntryList_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_
<|endoftext|>


<commit_before>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*    David D. Marshall - initial code and implementation
********************************************************************************/

#ifndef eli_mutil_nls_newton_raphson_system_method_hpp
#define eli_mutil_nls_newton_raphson_system_method_hpp

#include "eli/code_eli.hpp"

#include "eli/mutil/nls/iterative_system_root_base_constrained.hpp"

namespace eli
{
  namespace mutil
  {
    namespace nls
    {
      // Small systems where N__<=4
      template<typename data__, size_t N__, size_t NSOL__=1>
      class newton_raphson_system_method : public iterative_system_root_base_constrained<data__, N__, NSOL__>
      {
        public:
          static const int hit_constraint = 101;

        public:
          newton_raphson_system_method()
          : iterative_system_root_base_constrained<data__, N__, NSOL__>()
          {
            x0.setConstant(static_cast<data__>(0));
          }

          newton_raphson_system_method(const newton_raphson_system_method<data__, N__, NSOL__> &nrm)
          : iterative_system_root_base_constrained<data__, N__, NSOL__>(nrm), x0(nrm.x0)
          {
          }

          ~newton_raphson_system_method()
          {
          }

          void set_initial_guess(const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &xg)
          {
            x0=xg;
          }

          const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix & get_initial_guess() const
          {
            return x0;
          }

          template<typename f__, typename g__>
          int find_root(typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &root, const f__ &fun, const g__ &fprime, const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &f0) const
          {
            typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix dx, x(x0), fx(fun(x0)), eval1, eval2, eval3;
            typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix fpx(fprime(x0));
            data__ abs_tol_norm, rel_tol_norm, abs_x_norm, rel_x_norm;
            typename iterative_root_base<data__>::iteration_type count;

            // calculate the function evaluated at the initial location
            eval1=fx-f0;
            abs_tol_norm=this->calculate_norm(eval1);
            eval2=(fx-f0).array()/f0.array();
            eval2.setConstant(1);
            rel_tol_norm=this->calculate_norm(eval2);
            if (this->test_converged(0, rel_tol_norm, abs_tol_norm, 0, 0))
            {
              root=x;
              return this->converged;
            }

            bool all_zero(false);
            abs_x_norm=0;
            rel_x_norm=0;
            count=0;
            while (!this->test_converged(count, rel_tol_norm, abs_tol_norm, rel_x_norm, abs_x_norm) && !all_zero)
            {
  // FIX: Don't have any easy (efficient) way of determining if matrix in invertible
  //            if (fpx==0)
  //              return iterative_root_base<data__>::no_root_found;

              bool invertible;
              bool modified = false;

                typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix inverse;
                fpx.computeInverseWithCheck(inverse, invertible);

                std::vector<bool> zerodx(N__);

                if (!invertible)
                {
                  size_t itries = 0;
                  while ( itries < N__ && !invertible )
                  {
                    size_t ismall = -1;
                    data__ fsmall = 1;

                    for (size_t i=0; i<N__; ++i)
                    {
                      if ( std::abs( fpx( i, i ) < fsmall ) )
                      {
                        fsmall = std::abs( fpx ( i, i ) );
                        ismall = i;
                      }
                    }
                    zerodx[ ismall ] = true;
                    for (size_t i=0; i<N__; ++i)
                    {
                      fpx( i, ismall ) = 0.0;
                    }
                    fpx( ismall, ismall ) = 1.0;
                    itries++;
                    modified = true;
                    fpx.computeInverseWithCheck(inverse, invertible);
                  }
                  assert(invertible);
                }

                if (invertible)
                {
                  dx = - inverse * eval1;

                  if (modified)
                  {
                    for (size_t i=0; i<N__; ++i)
                    {
                      if (zerodx[i])
                      {
                        dx(i) = 0;
                      }
                    }
                  }
                }
                else
                {
                  dx.setZero();
                }

              dx=this->calculate_delta_factor(x, dx);
              x+=dx;
              fx=fun(x);
              fpx=fprime(x);
              eval1=fx-f0;
              abs_tol_norm=this->calculate_norm(eval1);
              abs_x_norm=this->calculate_norm(dx);
              bool nonzero(false);
              all_zero=true;
              for (size_t i=0; i<N__; ++i)
              {
                // check if stuck and cannot move x anymore
                if (std::abs(dx(i))<=std::numeric_limits<data__>::epsilon())
                {
                  eval3(i)=std::numeric_limits<data__>::epsilon();
                }
                else
                {
                  all_zero=false;
                  eval3(i)=dx(i)/x0(i);
                }

                if (std::abs(f0(i))<=std::numeric_limits<data__>::epsilon())
                  eval2(i)=std::numeric_limits<data__>::epsilon();
                else
                {
                  nonzero=true;
                  eval2(i)=eval1(i)/f0(i);
                }
              }
              if (nonzero)
                rel_tol_norm=this->calculate_norm(eval2);
              else
                rel_tol_norm=static_cast<data__>(0);

              if (all_zero)
                rel_x_norm=static_cast<data__>(0);
              else
                rel_x_norm=this->calculate_norm(eval3);

              ++count;
            }

            root=x;
            if (this->max_iteration_reached(count))
              return this->max_iteration; // could not converge
            if (all_zero)
              return this->hit_constraint; // constraints limited convergence

            return this->converged;
          }

        private:
          typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix x0;
      };

      // Large systems where N__>4
      template<typename data__, size_t N__, size_t NSOL__ = 1>
      class newton_raphson_large_system_method : public iterative_system_root_base_constrained<data__, N__, NSOL__>
      {
      public:
          static const int hit_constraint = 101;

      public:
          newton_raphson_large_system_method()
              : iterative_system_root_base_constrained<data__, N__, NSOL__>()
          {
              x0.setConstant( static_cast<data__>(0) );
          }

          newton_raphson_large_system_method( const newton_raphson_large_system_method<data__, N__, NSOL__> &nrm )
              : iterative_system_root_base_constrained<data__, N__, NSOL__>( nrm ), x0( nrm.x0 )
          {
          }

          ~newton_raphson_large_system_method()
          {
          }

          void set_initial_guess( const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &xg )
          {
              x0 = xg;
          }

          const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix & get_initial_guess() const
          {
              return x0;
          }

          template<typename f__, typename g__>
          int find_root( typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &root, const f__ &fun, const g__ &fprime, const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &f0 ) const
          {
              typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix dx, x( x0 ), fx( fun( x0 ) ), eval1, eval2, eval3;
              typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix fpx( fprime( x0 ) );
              data__ abs_tol_norm, rel_tol_norm, abs_x_norm, rel_x_norm;
              typename iterative_root_base<data__>::iteration_type count;

              // calculate the function evaluated at the initial location
              eval1 = fx - f0;
              abs_tol_norm = this->calculate_norm( eval1 );
              eval2 = (fx - f0).array() / f0.array();
              eval2.setConstant( 1 );
              rel_tol_norm = this->calculate_norm( eval2 );
              if ( this->test_converged( 0, rel_tol_norm, abs_tol_norm, 0, 0 ) )
              {
                  root = x;
                  return this->converged;
              }

              bool all_zero( false );
              abs_x_norm = 0;
              rel_x_norm = 0;
              count = 0;
              while ( !this->test_converged( count, rel_tol_norm, abs_tol_norm, rel_x_norm, abs_x_norm ) && !all_zero )
              {
                  // FIX: Don't have any easy (efficient) way of determining if matrix in invertible
                  //            if (fpx==0)
                  //              return iterative_root_base<data__>::no_root_found;

                  dx = -fpx.lu().solve( eval1 );

                  dx = this->calculate_delta_factor( x, dx );
                  x += dx;
                  fx = fun( x );
                  fpx = fprime( x );
                  eval1 = fx - f0;
                  abs_tol_norm = this->calculate_norm( eval1 );
                  abs_x_norm = this->calculate_norm( dx );
                  bool nonzero( false );
                  all_zero = true;
                  for ( size_t i = 0; i<N__; ++i )
                  {
                      // check if stuck and cannot move x anymore
                      if ( std::abs( dx( i ) ) <= std::numeric_limits<data__>::epsilon() )
                      {
                          eval3( i ) = std::numeric_limits<data__>::epsilon();
                      }
                      else
                      {
                          all_zero = false;
                          eval3( i ) = dx( i ) / x0( i );
                      }

                      if ( std::abs( f0( i ) ) <= std::numeric_limits<data__>::epsilon() )
                          eval2( i ) = std::numeric_limits<data__>::epsilon();
                      else
                      {
                          nonzero = true;
                          eval2( i ) = eval1( i ) / f0( i );
                      }
                  }
                  if ( nonzero )
                      rel_tol_norm = this->calculate_norm( eval2 );
                  else
                      rel_tol_norm = static_cast<data__>(0);

                  if ( all_zero )
                      rel_x_norm = static_cast<data__>(0);
                  else
                      rel_x_norm = this->calculate_norm( eval3 );

                  ++count;
              }

              root = x;
              if ( this->max_iteration_reached( count ) )
                  return this->max_iteration; // could not converge
              if ( all_zero )
                  return this->hit_constraint; // constraints limited convergence

              return this->converged;
          }

      private:
          typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix x0;
      };
    }
  }
}
#endif
<commit_msg>Fix parenthesis typo for abs() call.<commit_after>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*    David D. Marshall - initial code and implementation
********************************************************************************/

#ifndef eli_mutil_nls_newton_raphson_system_method_hpp
#define eli_mutil_nls_newton_raphson_system_method_hpp

#include "eli/code_eli.hpp"

#include "eli/mutil/nls/iterative_system_root_base_constrained.hpp"

namespace eli
{
  namespace mutil
  {
    namespace nls
    {
      // Small systems where N__<=4
      template<typename data__, size_t N__, size_t NSOL__=1>
      class newton_raphson_system_method : public iterative_system_root_base_constrained<data__, N__, NSOL__>
      {
        public:
          static const int hit_constraint = 101;

        public:
          newton_raphson_system_method()
          : iterative_system_root_base_constrained<data__, N__, NSOL__>()
          {
            x0.setConstant(static_cast<data__>(0));
          }

          newton_raphson_system_method(const newton_raphson_system_method<data__, N__, NSOL__> &nrm)
          : iterative_system_root_base_constrained<data__, N__, NSOL__>(nrm), x0(nrm.x0)
          {
          }

          ~newton_raphson_system_method()
          {
          }

          void set_initial_guess(const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &xg)
          {
            x0=xg;
          }

          const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix & get_initial_guess() const
          {
            return x0;
          }

          template<typename f__, typename g__>
          int find_root(typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &root, const f__ &fun, const g__ &fprime, const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &f0) const
          {
            typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix dx, x(x0), fx(fun(x0)), eval1, eval2, eval3;
            typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix fpx(fprime(x0));
            data__ abs_tol_norm, rel_tol_norm, abs_x_norm, rel_x_norm;
            typename iterative_root_base<data__>::iteration_type count;

            // calculate the function evaluated at the initial location
            eval1=fx-f0;
            abs_tol_norm=this->calculate_norm(eval1);
            eval2=(fx-f0).array()/f0.array();
            eval2.setConstant(1);
            rel_tol_norm=this->calculate_norm(eval2);
            if (this->test_converged(0, rel_tol_norm, abs_tol_norm, 0, 0))
            {
              root=x;
              return this->converged;
            }

            bool all_zero(false);
            abs_x_norm=0;
            rel_x_norm=0;
            count=0;
            while (!this->test_converged(count, rel_tol_norm, abs_tol_norm, rel_x_norm, abs_x_norm) && !all_zero)
            {
  // FIX: Don't have any easy (efficient) way of determining if matrix in invertible
  //            if (fpx==0)
  //              return iterative_root_base<data__>::no_root_found;

              bool invertible;
              bool modified = false;

                typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix inverse;
                fpx.computeInverseWithCheck(inverse, invertible);

                std::vector<bool> zerodx(N__);

                if (!invertible)
                {
                  size_t itries = 0;
                  while ( itries < N__ && !invertible )
                  {
                    size_t ismall = -1;
                    data__ fsmall = 1;

                    for (size_t i=0; i<N__; ++i)
                    {
                      if ( std::abs( fpx( i, i ) ) < fsmall )
                      {
                        fsmall = std::abs( fpx ( i, i ) );
                        ismall = i;
                      }
                    }
                    zerodx[ ismall ] = true;
                    for (size_t i=0; i<N__; ++i)
                    {
                      fpx( i, ismall ) = 0.0;
                    }
                    fpx( ismall, ismall ) = 1.0;
                    itries++;
                    modified = true;
                    fpx.computeInverseWithCheck(inverse, invertible);
                  }
                  assert(invertible);
                }

                if (invertible)
                {
                  dx = - inverse * eval1;

                  if (modified)
                  {
                    for (size_t i=0; i<N__; ++i)
                    {
                      if (zerodx[i])
                      {
                        dx(i) = 0;
                      }
                    }
                  }
                }
                else
                {
                  dx.setZero();
                }

              dx=this->calculate_delta_factor(x, dx);
              x+=dx;
              fx=fun(x);
              fpx=fprime(x);
              eval1=fx-f0;
              abs_tol_norm=this->calculate_norm(eval1);
              abs_x_norm=this->calculate_norm(dx);
              bool nonzero(false);
              all_zero=true;
              for (size_t i=0; i<N__; ++i)
              {
                // check if stuck and cannot move x anymore
                if (std::abs(dx(i))<=std::numeric_limits<data__>::epsilon())
                {
                  eval3(i)=std::numeric_limits<data__>::epsilon();
                }
                else
                {
                  all_zero=false;
                  eval3(i)=dx(i)/x0(i);
                }

                if (std::abs(f0(i))<=std::numeric_limits<data__>::epsilon())
                  eval2(i)=std::numeric_limits<data__>::epsilon();
                else
                {
                  nonzero=true;
                  eval2(i)=eval1(i)/f0(i);
                }
              }
              if (nonzero)
                rel_tol_norm=this->calculate_norm(eval2);
              else
                rel_tol_norm=static_cast<data__>(0);

              if (all_zero)
                rel_x_norm=static_cast<data__>(0);
              else
                rel_x_norm=this->calculate_norm(eval3);

              ++count;
            }

            root=x;
            if (this->max_iteration_reached(count))
              return this->max_iteration; // could not converge
            if (all_zero)
              return this->hit_constraint; // constraints limited convergence

            return this->converged;
          }

        private:
          typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix x0;
      };

      // Large systems where N__>4
      template<typename data__, size_t N__, size_t NSOL__ = 1>
      class newton_raphson_large_system_method : public iterative_system_root_base_constrained<data__, N__, NSOL__>
      {
      public:
          static const int hit_constraint = 101;

      public:
          newton_raphson_large_system_method()
              : iterative_system_root_base_constrained<data__, N__, NSOL__>()
          {
              x0.setConstant( static_cast<data__>(0) );
          }

          newton_raphson_large_system_method( const newton_raphson_large_system_method<data__, N__, NSOL__> &nrm )
              : iterative_system_root_base_constrained<data__, N__, NSOL__>( nrm ), x0( nrm.x0 )
          {
          }

          ~newton_raphson_large_system_method()
          {
          }

          void set_initial_guess( const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &xg )
          {
              x0 = xg;
          }

          const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix & get_initial_guess() const
          {
              return x0;
          }

          template<typename f__, typename g__>
          int find_root( typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &root, const f__ &fun, const g__ &fprime, const typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix &f0 ) const
          {
              typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix dx, x( x0 ), fx( fun( x0 ) ), eval1, eval2, eval3;
              typename iterative_system_root_base<data__, N__, NSOL__>::jacobian_matrix fpx( fprime( x0 ) );
              data__ abs_tol_norm, rel_tol_norm, abs_x_norm, rel_x_norm;
              typename iterative_root_base<data__>::iteration_type count;

              // calculate the function evaluated at the initial location
              eval1 = fx - f0;
              abs_tol_norm = this->calculate_norm( eval1 );
              eval2 = (fx - f0).array() / f0.array();
              eval2.setConstant( 1 );
              rel_tol_norm = this->calculate_norm( eval2 );
              if ( this->test_converged( 0, rel_tol_norm, abs_tol_norm, 0, 0 ) )
              {
                  root = x;
                  return this->converged;
              }

              bool all_zero( false );
              abs_x_norm = 0;
              rel_x_norm = 0;
              count = 0;
              while ( !this->test_converged( count, rel_tol_norm, abs_tol_norm, rel_x_norm, abs_x_norm ) && !all_zero )
              {
                  // FIX: Don't have any easy (efficient) way of determining if matrix in invertible
                  //            if (fpx==0)
                  //              return iterative_root_base<data__>::no_root_found;

                  dx = -fpx.lu().solve( eval1 );

                  dx = this->calculate_delta_factor( x, dx );
                  x += dx;
                  fx = fun( x );
                  fpx = fprime( x );
                  eval1 = fx - f0;
                  abs_tol_norm = this->calculate_norm( eval1 );
                  abs_x_norm = this->calculate_norm( dx );
                  bool nonzero( false );
                  all_zero = true;
                  for ( size_t i = 0; i<N__; ++i )
                  {
                      // check if stuck and cannot move x anymore
                      if ( std::abs( dx( i ) ) <= std::numeric_limits<data__>::epsilon() )
                      {
                          eval3( i ) = std::numeric_limits<data__>::epsilon();
                      }
                      else
                      {
                          all_zero = false;
                          eval3( i ) = dx( i ) / x0( i );
                      }

                      if ( std::abs( f0( i ) ) <= std::numeric_limits<data__>::epsilon() )
                          eval2( i ) = std::numeric_limits<data__>::epsilon();
                      else
                      {
                          nonzero = true;
                          eval2( i ) = eval1( i ) / f0( i );
                      }
                  }
                  if ( nonzero )
                      rel_tol_norm = this->calculate_norm( eval2 );
                  else
                      rel_tol_norm = static_cast<data__>(0);

                  if ( all_zero )
                      rel_x_norm = static_cast<data__>(0);
                  else
                      rel_x_norm = this->calculate_norm( eval3 );

                  ++count;
              }

              root = x;
              if ( this->max_iteration_reached( count ) )
                  return this->max_iteration; // could not converge
              if ( all_zero )
                  return this->hit_constraint; // constraints limited convergence

              return this->converged;
          }

      private:
          typename iterative_system_root_base<data__, N__, NSOL__>::solution_matrix x0;
      };
    }
  }
}
#endif
<|endoftext|>


<commit_before>#include <image_cloud/common/small_helpers.hpp>
#include <image_cloud/common/type.hpp>
#include <image_cloud/common/calibration/structs.hpp>
#include <image_cloud/common/transform.hpp>

#include <math.h>
#include <opencv2/core/core.hpp>

#ifndef MUTLI_SCORE_H_
#define MUTLI_SCORE_H_

namespace score
{

template <typename PointT, typename ImageT>
inline void
multi_score(
		std::vector<Projected_pointcloud<PointT> > &idx,
		std::vector<cv::Mat> &edge_images,
		long unsigned &score)
{
	assert(idx.size() == edge_images.size());

	for(int i = 0; i< idx.size(); ++i){
		long unsigned score_temp;
		objective_function(idx.at(i), edge_images.at(i),score_temp);
		score += score_temp;
	}
}

/****
 * Transforms Pointclouds and calculates a result using the objective_function
 */
template <typename PointT, typename ImageT>
inline void
multi_score(
		const image_geometry::PinholeCameraModel &camera_model,
		std::vector<pcl::PointCloud<PointT> > pointclouds,
		std::vector<cv::Mat> &edge_images,
		search::Search_value &search
		)
{
	assert(pointclouds.size() == edge_images.size());

	for(int i = 0; i< pointclouds.size(); ++i){
		long unsigned score_temp;

		image_cloud::transform_pointcloud(pointclouds.at(i), search.x, search.y, search.z, search.roll, search.pitch, search.yaw);

		Projected_pointcloud<PointT> p;
		p.image_size.heigh = edge_images.at(i).rows;
		p.image_size.width = edge_images.at(i).cols;

		project2d::project_2d( camera_model, pointclouds.at(i), p);

		objective_function( pointclouds.at(i).at(i), edge_images.at(i), score_temp);

		search.result += score_temp;
	}
}

}

#endif
<commit_msg>adapted to templatet function<commit_after>#include <image_cloud/common/small_helpers.hpp>
#include <image_cloud/common/type.hpp>
#include <image_cloud/common/transform.hpp>
#include <image_cloud/common/calibration/structs.hpp>
#include <image_cloud/common/calibration/score.hpp>

#include <math.h>
#include <opencv2/core/core.hpp>

#ifndef MUTLI_SCORE_H_
#define MUTLI_SCORE_H_

namespace score
{

template <typename PointT, typename ImageT>
inline void
multi_score(
		std::vector<Projected_pointcloud<PointT> > &idx,
		std::vector<cv::Mat> &edge_images,
		long unsigned &score)
{
	assert(idx.size() == edge_images.size());

	for(int i = 0; i< idx.size(); ++i){
		long unsigned score_temp;
		objective_function(idx.at(i), edge_images.at(i),score_temp);
		score += score_temp;
	}
}

/****
 * Transforms Pointclouds and calculates a result using the objective_function
 */
template <typename PointT, typename ImageT>
inline void
multi_score(
		const image_geometry::PinholeCameraModel &camera_model,
		const std::vector<pcl::PointCloud<PointT> >& pointclouds,
		const std::vector<cv::Mat> &edge_images,
		search::Search_value &search
		)
{
	assert(pointclouds.size() == edge_images.size());

	for(int i = 0; i< pointclouds.size(); ++i){
		long unsigned score_temp;
		pcl::PointCloud<PointT> transformed;

		image_cloud::transform_pointcloud<PointT>(pointclouds.at(i), transformed, search.x, search.y, search.z, search.roll, search.pitch, search.yaw);

		Projected_pointcloud<PointT> p;

		project2d::project_2d<PointT>( camera_model, transformed, p, edge_images.at(i).cols, edge_images.at(i).rows );
		objective_function<PointT, ImageT>( p, edge_images.at(i), score_temp);

		search.result += score_temp;
	}
}

}

#endif
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Chris Kilner <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <alcommon-ng/common/client_node.hpp>
#include <alcommon-ng/messaging/client.hpp>

// would not be needed if we had a specific client
#include <alcommon-ng/messaging/call_definition.hpp>
#include <alcommon-ng/messaging/result_definition.hpp>

namespace AL {
  using namespace Messaging;
  namespace Common {

    ClientNode::ClientNode(
      const std::string& clientName,
      const std::string& masterAddress) :
        fClientName(clientName),
        fMasterAddress(masterAddress) {
      xInit();
    }

    ClientNode::~ClientNode() {}

    void ClientNode::xInit() {
      NodeInfo master("master", fMasterAddress);
      xCreateServerClient(master);
      xUpdateServicesFromMaster();
    }

    ResultDefinition ClientNode::call(const CallDefinition& callDef) {

        // todo lookup in services

        // todo make a hash from the calldef
        std::string hash = callDef.moduleName() + "." + callDef.methodName();
        std::string nodeName = fServiceCache.get(hash).nodeName;

        // get the relevant messaging client for the node that host the service
        NameLookup<boost::shared_ptr<DefaultClient> >::iterator it;
        it = fServerClients.find(hash);
        if (it == fServerClients.end()) {
           // create messaging client if needed ???
          std::cout << "Client: " << fClientName << ", could not find Server for message " << hash << std::endl;
          // throw?
          ResultDefinition r;
          return r;
        }

        // call
        std::cout << "Client: " << fClientName << ", found server for message " << hash << "." << callDef.methodName() <<  std::endl;
        ResultDefinition result = (it->second)->send(callDef);
        std::cout << "  Client: " << fClientName << ", received result" << std::endl;
        return result;
    }

    void ClientNode::xUpdateServicesFromMaster() {
      // if master is alive
      // get list of services
    }

    void ClientNode::xCreateServerClient(const NodeInfo& serverNodeInfo) {
      // TODO error handling
      boost::shared_ptr<DefaultClient> client =
        boost::shared_ptr<DefaultClient>(new DefaultClient(serverNodeInfo.address));

      // TODO find existing server and update if it exists

      // add server client
      // TODO mutex on service cache
      fServerClients.insert(make_pair(serverNodeInfo.name, client));
      fServerList.insert(make_pair(serverNodeInfo.name, serverNodeInfo)); // why not!
    }

    const std::string ClientNode::xLocateService(const std::string& methodHash) {
      // TODO mutex on service cache
      std::string nodeName = fServiceCache.get(methodHash).nodeName;

      // empty means not found
      if (!nodeName.empty()) {
        return nodeName;
      }

      if (fClientName != "master") {
        // cache lookup failed ... time to ask master

        // add service to cache

        // return it
      }

      return nodeName;
    }

  }
}
<commit_msg>use locateService ( tired today )<commit_after>/*
** Author(s):
**  - Chris Kilner <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <alcommon-ng/common/client_node.hpp>
#include <alcommon-ng/messaging/client.hpp>

// would not be needed if we had a specific client
#include <alcommon-ng/messaging/call_definition.hpp>
#include <alcommon-ng/messaging/result_definition.hpp>

namespace AL {
  using namespace Messaging;
  namespace Common {

    ClientNode::ClientNode(
      const std::string& clientName,
      const std::string& masterAddress) :
        fClientName(clientName),
        fMasterAddress(masterAddress) {
      xInit();
    }

    ClientNode::~ClientNode() {}

    void ClientNode::xInit() {
      NodeInfo master("master", fMasterAddress);
      xCreateServerClient(master);
      xUpdateServicesFromMaster();
    }

    ResultDefinition ClientNode::call(const CallDefinition& callDef) {

        // todo lookup in services

        // todo make a hash from the calldef
        std::string hash = callDef.moduleName() + "." + callDef.methodName();
        std::string nodeName = xLocateService(hash);

        // get the relevant messaging client for the node that host the service
        NameLookup<boost::shared_ptr<DefaultClient> >::iterator it;
        it = fServerClients.find(hash);
        if (it == fServerClients.end()) {
           // create messaging client if needed ???
          std::cout << "Client: " << fClientName << ", could not find Server for message " << hash << std::endl;
          // throw?
          ResultDefinition r;
          return r;
        }

        // call
        std::cout << "Client: " << fClientName << ", found server for message " << hash << "." << callDef.methodName() <<  std::endl;
        ResultDefinition result = (it->second)->send(callDef);
        std::cout << "  Client: " << fClientName << ", received result" << std::endl;
        return result;
    }

    void ClientNode::xUpdateServicesFromMaster() {
      // if master is alive
      // get list of services
    }

    void ClientNode::xCreateServerClient(const NodeInfo& serverNodeInfo) {
      // TODO error handling
      boost::shared_ptr<DefaultClient> client =
        boost::shared_ptr<DefaultClient>(new DefaultClient(serverNodeInfo.address));

      // TODO find existing server and update if it exists

      // add server client
      // TODO mutex on service cache
      fServerClients.insert(make_pair(serverNodeInfo.name, client));
      fServerList.insert(make_pair(serverNodeInfo.name, serverNodeInfo)); // why not!
    }

    const std::string ClientNode::xLocateService(const std::string& methodHash) {
      // TODO mutex on service cache
      std::string nodeName = fServiceCache.get(methodHash).nodeName;

      // empty means not found
      if (!nodeName.empty()) {
        return nodeName;
      }

      if (fClientName != "master") {
        // cache lookup failed ... time to ask master

        // add service to cache

        // return it
      }

      return nodeName;
    }

  }
}
<|endoftext|>