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

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/common/extensions/extension.h"
#include "gfx/gtk_util.h"
#include "grit/generated_resources.h"
#include "skia/ext/image_operations.h"

class Profile;

namespace {

const int kRightColumnWidth = 290;

const int kImageSize = 69;

// Padding on all sides of each permission in the permissions list.
const int kPermissionsPadding = 8;

// Make a GtkLabel with |str| as its text, using the formatting in |format|.
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
  GtkWidget* label = gtk_label_new(NULL);
  char* markup = g_markup_printf_escaped(format, str.c_str());
  gtk_label_set_markup(GTK_LABEL(label), markup);
  g_free(markup);

  // Left align it.
  gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);

  return label;
}

void OnDialogResponse(GtkDialog* dialog, int response_id,
                      ExtensionInstallUI::Delegate* delegate) {
  if (response_id == GTK_RESPONSE_ACCEPT) {
    delegate->InstallUIProceed(false);
  } else {
    delegate->InstallUIAbort();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog));
}

void ShowInstallPromptDialog2(GtkWindow* parent, SkBitmap* skia_icon,
                              Extension* extension,
                              ExtensionInstallUI::Delegate *delegate,
                              const std::vector<string16>& permissions) {
  // Build the dialog.
  GtkWidget* dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALL_PROMPT_TITLE).c_str(),
      parent,
      GTK_DIALOG_MODAL,
      NULL);
  GtkWidget* close_button = gtk_dialog_add_button(GTK_DIALOG(dialog),
      GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE);
  gtk_dialog_add_button(GTK_DIALOG(dialog),
      l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_INSTALL_BUTTON).c_str(),
      GTK_RESPONSE_ACCEPT);
  gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);

  // Create a two column layout.
  GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing);
  gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);

  // Resize the icon if necessary.
  SkBitmap scaled_icon = *skia_icon;
  if (scaled_icon.width() > kImageSize || scaled_icon.height() > kImageSize) {
    scaled_icon = skia::ImageOperations::Resize(scaled_icon,
        skia::ImageOperations::RESIZE_LANCZOS3,
        kImageSize, kImageSize);
  }

  // Put Icon in the left column.
  GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&scaled_icon);
  GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);
  g_object_unref(pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_hbox), icon, FALSE, FALSE, 0);
  // Top justify the image.
  gtk_misc_set_alignment(GTK_MISC(icon), 0.5, 0.0);

  // Create a new vbox for the right column.
  GtkWidget* right_column_area = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);

  std::string heading_text = l10n_util::GetStringFUTF8(
      IDS_EXTENSION_INSTALL_PROMPT_HEADING, UTF8ToUTF16(extension->name()));
  GtkWidget* heading_label = MakeMarkupLabel("%s",
                                             heading_text);
  gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);
  bool show_permissions = !permissions.empty();
  // If we are not going to show the permissions, vertically center the title.
  gtk_box_pack_start(GTK_BOX(right_column_area), heading_label,
                     !show_permissions, !show_permissions, 0);

  if (show_permissions) {
    GtkWidget* warning_label = gtk_label_new(l10n_util::GetStringUTF8(
        IDS_EXTENSION_PROMPT2_WILL_HAVE_ACCESS_TO).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE);
    gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1);
    gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5);
    gtk_box_pack_start(GTK_BOX(right_column_area), warning_label,
                       FALSE, FALSE, 0);

    GtkWidget* frame = gtk_frame_new(NULL);
    gtk_box_pack_start(GTK_BOX(right_column_area), frame, FALSE, FALSE, 0);

    GtkWidget* table = gtk_table_new(permissions.size(), 1, false);
    gtk_container_add(GTK_CONTAINER(frame), table);
    int row = 0;
    for (std::vector<string16>::const_iterator iter = permissions.begin();
         iter != permissions.end(); ++iter) {
      GtkWidget* entry = gtk_entry_new();
      GtkBorder border = { kPermissionsPadding, kPermissionsPadding,
                           row == 0 ? kPermissionsPadding : 0,
                           kPermissionsPadding };
      gtk_entry_set_inner_border(GTK_ENTRY(entry), &border);
      gtk_entry_set_text(GTK_ENTRY(entry), UTF16ToUTF8(*iter).c_str());
      gtk_entry_set_editable(GTK_ENTRY(entry), FALSE);
      gtk_entry_set_has_frame(GTK_ENTRY(entry), FALSE);

      gtk_table_attach_defaults(GTK_TABLE(table), entry,
                                0, 1, row, row + 1);
      ++row;
    }
  }

  g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), delegate);
  gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);

  gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE);
  gtk_widget_show_all(dialog);
  gtk_widget_grab_focus(close_button);
}

}  // namespace

void ExtensionInstallUI::ShowExtensionInstallUIPrompt2Impl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const std::vector<string16>& permissions) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>(
      browser->window());
  if (!browser_window) {
    delegate->InstallUIAbort();
    return;
  }

  ShowInstallPromptDialog2(browser_window->window(), icon, extension,
      delegate, permissions);
}
<commit_msg>GTK: let the extension install prompt permissions line wrap.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/common/extensions/extension.h"
#include "gfx/gtk_util.h"
#include "grit/generated_resources.h"
#include "skia/ext/image_operations.h"

class Profile;

namespace {

const int kRightColumnWidth = 290;

const int kImageSize = 69;

// Padding on all sides of each permission in the permissions list.
const int kPermissionsPadding = 8;

// Make a GtkLabel with |str| as its text, using the formatting in |format|.
GtkWidget* MakeMarkupLabel(const char* format, const std::string& str) {
  GtkWidget* label = gtk_label_new(NULL);
  char* markup = g_markup_printf_escaped(format, str.c_str());
  gtk_label_set_markup(GTK_LABEL(label), markup);
  g_free(markup);

  // Left align it.
  gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);

  return label;
}

void OnDialogResponse(GtkDialog* dialog, int response_id,
                      ExtensionInstallUI::Delegate* delegate) {
  if (response_id == GTK_RESPONSE_ACCEPT) {
    delegate->InstallUIProceed(false);
  } else {
    delegate->InstallUIAbort();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog));
}

void ShowInstallPromptDialog2(GtkWindow* parent, SkBitmap* skia_icon,
                              Extension* extension,
                              ExtensionInstallUI::Delegate *delegate,
                              const std::vector<string16>& permissions) {
  // Build the dialog.
  GtkWidget* dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_EXTENSION_INSTALL_PROMPT_TITLE).c_str(),
      parent,
      GTK_DIALOG_MODAL,
      NULL);
  GtkWidget* close_button = gtk_dialog_add_button(GTK_DIALOG(dialog),
      GTK_STOCK_CANCEL, GTK_RESPONSE_CLOSE);
  gtk_dialog_add_button(GTK_DIALOG(dialog),
      l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_INSTALL_BUTTON).c_str(),
      GTK_RESPONSE_ACCEPT);
  gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);

  // Create a two column layout.
  GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* icon_hbox = gtk_hbox_new(FALSE, gtk_util::kContentAreaSpacing);
  gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);

  // Resize the icon if necessary.
  SkBitmap scaled_icon = *skia_icon;
  if (scaled_icon.width() > kImageSize || scaled_icon.height() > kImageSize) {
    scaled_icon = skia::ImageOperations::Resize(scaled_icon,
        skia::ImageOperations::RESIZE_LANCZOS3,
        kImageSize, kImageSize);
  }

  // Put Icon in the left column.
  GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&scaled_icon);
  GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);
  g_object_unref(pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_hbox), icon, FALSE, FALSE, 0);
  // Top justify the image.
  gtk_misc_set_alignment(GTK_MISC(icon), 0.5, 0.0);

  // Create a new vbox for the right column.
  GtkWidget* right_column_area = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);

  std::string heading_text = l10n_util::GetStringFUTF8(
      IDS_EXTENSION_INSTALL_PROMPT_HEADING, UTF8ToUTF16(extension->name()));
  GtkWidget* heading_label = MakeMarkupLabel("%s",
                                             heading_text);
  gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);
  bool show_permissions = !permissions.empty();
  // If we are not going to show the permissions, vertically center the title.
  gtk_box_pack_start(GTK_BOX(right_column_area), heading_label,
                     !show_permissions, !show_permissions, 0);

  if (show_permissions) {
    GtkWidget* warning_label = gtk_label_new(l10n_util::GetStringUTF8(
        IDS_EXTENSION_PROMPT2_WILL_HAVE_ACCESS_TO).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(warning_label), TRUE);
    gtk_widget_set_size_request(warning_label, kRightColumnWidth, -1);
    gtk_misc_set_alignment(GTK_MISC(warning_label), 0.0, 0.5);
    gtk_box_pack_start(GTK_BOX(right_column_area), warning_label,
                       FALSE, FALSE, 0);

    GtkWidget* frame = gtk_frame_new(NULL);
    gtk_box_pack_start(GTK_BOX(right_column_area), frame, FALSE, FALSE, 0);

    GtkWidget* text_view = gtk_text_view_new();
    gtk_container_add(GTK_CONTAINER(frame), text_view);
    gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), FALSE);
    gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_view),
                                  kPermissionsPadding);
    gtk_text_view_set_right_margin(GTK_TEXT_VIEW(text_view),
                                   kPermissionsPadding);
    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD);
    GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view));
    GtkTextTagTable* tag_table = gtk_text_buffer_get_tag_table(buffer);

    GtkTextTag* padding_below_tag = gtk_text_tag_new(NULL);
    g_object_set(G_OBJECT(padding_below_tag), "pixels-below-lines",
                 kPermissionsPadding, NULL);
    g_object_set(G_OBJECT(padding_below_tag), "pixels-below-lines-set",
                 TRUE, NULL);
    gtk_text_tag_table_add(tag_table, padding_below_tag);
    g_object_unref(padding_below_tag);
    GtkTextTag* padding_above_tag = gtk_text_tag_new(NULL);
    g_object_set(G_OBJECT(padding_above_tag), "pixels-above-lines",
                 kPermissionsPadding, NULL);
    g_object_set(G_OBJECT(padding_above_tag), "pixels-above-lines-set",
                 TRUE, NULL);
    gtk_text_tag_table_add(tag_table, padding_above_tag);
    g_object_unref(padding_above_tag);

    GtkTextIter end_iter;
    gtk_text_buffer_get_end_iter(buffer, &end_iter);
    for (std::vector<string16>::const_iterator iter = permissions.begin();
         iter != permissions.end(); ++iter) {
      if (iter != permissions.begin())
        gtk_text_buffer_insert(buffer, &end_iter, "\n", -1);
      gtk_text_buffer_insert_with_tags(
          buffer, &end_iter, UTF16ToUTF8(*iter).c_str(), -1,
          padding_below_tag,
          iter == permissions.begin() ? padding_above_tag : NULL,
          NULL);
    }
  }

  g_signal_connect(dialog, "response", G_CALLBACK(OnDialogResponse), delegate);
  gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);

  gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE);
  gtk_widget_show_all(dialog);
  gtk_widget_grab_focus(close_button);
}

}  // namespace

void ExtensionInstallUI::ShowExtensionInstallUIPrompt2Impl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const std::vector<string16>& permissions) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>(
      browser->window());
  if (!browser_window) {
    delegate->InstallUIAbort();
    return;
  }

  ShowInstallPromptDialog2(browser_window->window(), icon, extension,
      delegate, permissions);
}
<|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_NormalsFromPoints_INL
#define SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL

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

#include "NormalsFromPoints.h"
#include <sofa/helper/gl/template.h>
#include <iostream>
#include <math.h>

namespace sofa
{

namespace component
{

namespace engine
{

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

template <class DataTypes>
NormalsFromPoints<DataTypes>::NormalsFromPoints()
    :   position(initData(&position,"position","Vertices of the mesh"))
    , triangles(initData(&triangles,"triangles","Triangles of the mesh"))
    , quads(initData(&quads,"quads","Quads of the mesh"))
    , normals(initData(&normals,"normals","Computed vertex normals of the mesh"))
    , invertNormals( initData (&invertNormals, false, "invertNormals", "Swap normals") )
    , useAngles( initData (&useAngles, false, "useAngles", "Use incident angles to weight faces normal contributions at each vertex") )

{
}

template <class DataTypes>
void NormalsFromPoints<DataTypes>::init()
{
    mstate = dynamic_cast< MechanicalState<DataTypes>* >(getContext()->getMechanicalState());
    addInput(&position);
    addInput(&triangles);
    addInput(&quads);
    addInput(&invertNormals);
    addInput(&useAngles);
    addOutput(&normals);
    setDirtyValue();
}

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

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

    helper::ReadAccessor<Data< VecCoord > > raPositions = position;
    helper::ReadAccessor<Data< helper::vector< helper::fixed_array <unsigned int,3> > > > raTriangles = triangles;
    helper::ReadAccessor<Data< helper::vector< helper::fixed_array <unsigned int,4> > > > raQuads = quads;
    helper::WriteAccessor<Data< VecCoord > > waNormals = normals;
    const bool useAngles = this->useAngles.getValue();
    const bool invertNormals = this->invertNormals.getValue();

    waNormals.resize(raPositions.size());

    for (unsigned int i = 0; i < raTriangles.size() ; i++)
    {
        const Coord  v1 = raPositions[raTriangles[i][0]];
        const Coord  v2 = raPositions[raTriangles[i][1]];
        const Coord  v3 = raPositions[raTriangles[i][2]];
        Coord n = cross(v2-v1, v3-v1);
        if (useAngles)
        {
            Real nnorm = n.norm();
            Coord e12 = v2-v1; Real e12norm = e12.norm();
            Coord e23 = v3-v2; Real e23norm = e23.norm();
            Coord e31 = v3-v1; Real e31norm = e31.norm();
            waNormals[raTriangles[i][0]] += n * (acos(-(e31*e12)/(e31norm*e12norm))/nnorm);
            waNormals[raTriangles[i][1]] += n * (acos(-(e12*e23)/(e12norm*e23norm))/nnorm);
            waNormals[raTriangles[i][2]] += n * (acos(-(e23*e31)/(e23norm*e31norm))/nnorm);
        }
        else
        {
            n.normalize();
            waNormals[raTriangles[i][0]] += n;
            waNormals[raTriangles[i][1]] += n;
            waNormals[raTriangles[i][2]] += n;
        }
    }
    for (unsigned int i = 0; i < raQuads.size() ; i++)
    {
        const Coord & v1 = raPositions[raQuads[i][0]];
        const Coord & v2 = raPositions[raQuads[i][1]];
        const Coord & v3 = raPositions[raQuads[i][2]];
        const Coord & v4 = raPositions[raQuads[i][3]];
        Coord n1 = cross(v2-v1, v4-v1); Real n1norm = n1.norm();
        Coord n2 = cross(v3-v2, v1-v2); Real n2norm = n2.norm();
        Coord n3 = cross(v4-v3, v2-v3); Real n3norm = n3.norm();
        Coord n4 = cross(v1-v4, v3-v4); Real n4norm = n4.norm();
        if (useAngles)
        {
            Coord e12 = v2-v1; Real e12norm = e12.norm();
            Coord e23 = v3-v2; Real e23norm = e23.norm();
            Coord e34 = v4-v3; Real e34norm = e34.norm();
            Coord e41 = v1-v4; Real e41norm = e41.norm();
            waNormals[raQuads[i][0]] += n1 * (acos(-(e41*e12)/(e41norm*e12norm))/n1norm);
            waNormals[raQuads[i][1]] += n2 * (acos(-(e12*e23)/(e12norm*e23norm))/n2norm);
            waNormals[raQuads[i][2]] += n3 * (acos(-(e23*e34)/(e23norm*e34norm))/n3norm);
            waNormals[raQuads[i][3]] += n4 * (acos(-(e34*e41)/(e34norm*e41norm))/n3norm);
        }
        else
        {
            waNormals[raQuads[i][0]] += n1 / n1norm;
            waNormals[raQuads[i][1]] += n2 / n2norm;
            waNormals[raQuads[i][2]] += n3 / n3norm;
            waNormals[raQuads[i][3]] += n4 / n4norm;
        }
    }

    if(invertNormals)
        for (unsigned int i = 0; i < waNormals.size(); i++)
            waNormals[i]=-waNormals[i];

    for (unsigned int i = 0; i < waNormals.size(); i++)
        waNormals[i].normalize();
}

} // namespace engine

} // namespace component

} // namespace sofa

#endif
<commit_msg>r12665/sofa-dev : FIX: sign error<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_NormalsFromPoints_INL
#define SOFA_COMPONENT_ENGINE_NormalsFromPoints_INL

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

#include "NormalsFromPoints.h"
#include <sofa/helper/gl/template.h>
#include <iostream>
#include <math.h>

namespace sofa
{

namespace component
{

namespace engine
{

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

template <class DataTypes>
NormalsFromPoints<DataTypes>::NormalsFromPoints()
    :   position(initData(&position,"position","Vertices of the mesh"))
    , triangles(initData(&triangles,"triangles","Triangles of the mesh"))
    , quads(initData(&quads,"quads","Quads of the mesh"))
    , normals(initData(&normals,"normals","Computed vertex normals of the mesh"))
    , invertNormals( initData (&invertNormals, false, "invertNormals", "Swap normals") )
    , useAngles( initData (&useAngles, false, "useAngles", "Use incident angles to weight faces normal contributions at each vertex") )

{
}

template <class DataTypes>
void NormalsFromPoints<DataTypes>::init()
{
    mstate = dynamic_cast< MechanicalState<DataTypes>* >(getContext()->getMechanicalState());
    addInput(&position);
    addInput(&triangles);
    addInput(&quads);
    addInput(&invertNormals);
    addInput(&useAngles);
    addOutput(&normals);
    setDirtyValue();
}

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

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

    helper::ReadAccessor<Data< VecCoord > > raPositions = position;
    helper::ReadAccessor<Data< helper::vector< helper::fixed_array <unsigned int,3> > > > raTriangles = triangles;
    helper::ReadAccessor<Data< helper::vector< helper::fixed_array <unsigned int,4> > > > raQuads = quads;
    helper::WriteAccessor<Data< VecCoord > > waNormals = normals;
    const bool useAngles = this->useAngles.getValue();
    const bool invertNormals = this->invertNormals.getValue();

    waNormals.resize(raPositions.size());

    for (unsigned int i = 0; i < raTriangles.size() ; i++)
    {
        const Coord  v1 = raPositions[raTriangles[i][0]];
        const Coord  v2 = raPositions[raTriangles[i][1]];
        const Coord  v3 = raPositions[raTriangles[i][2]];
        Coord n = cross(v2-v1, v3-v1);
        if (useAngles)
        {
            Real nnorm = n.norm();
            Coord e12 = v2-v1; Real e12norm = e12.norm();
            Coord e23 = v3-v2; Real e23norm = e23.norm();
            Coord e31 = v1-v3; Real e31norm = e31.norm();
            waNormals[raTriangles[i][0]] += n * (acos(-(e31*e12)/(e31norm*e12norm))/nnorm);
            waNormals[raTriangles[i][1]] += n * (acos(-(e12*e23)/(e12norm*e23norm))/nnorm);
            waNormals[raTriangles[i][2]] += n * (acos(-(e23*e31)/(e23norm*e31norm))/nnorm);
        }
        else
        {
            n.normalize();
            waNormals[raTriangles[i][0]] += n;
            waNormals[raTriangles[i][1]] += n;
            waNormals[raTriangles[i][2]] += n;
        }
    }
    for (unsigned int i = 0; i < raQuads.size() ; i++)
    {
        const Coord & v1 = raPositions[raQuads[i][0]];
        const Coord & v2 = raPositions[raQuads[i][1]];
        const Coord & v3 = raPositions[raQuads[i][2]];
        const Coord & v4 = raPositions[raQuads[i][3]];
        Coord n1 = cross(v2-v1, v4-v1); Real n1norm = n1.norm();
        Coord n2 = cross(v3-v2, v1-v2); Real n2norm = n2.norm();
        Coord n3 = cross(v4-v3, v2-v3); Real n3norm = n3.norm();
        Coord n4 = cross(v1-v4, v3-v4); Real n4norm = n4.norm();
        if (useAngles)
        {
            Coord e12 = v2-v1; Real e12norm = e12.norm();
            Coord e23 = v3-v2; Real e23norm = e23.norm();
            Coord e34 = v4-v3; Real e34norm = e34.norm();
            Coord e41 = v1-v4; Real e41norm = e41.norm();
            waNormals[raQuads[i][0]] += n1 * (acos(-(e41*e12)/(e41norm*e12norm))/n1norm);
            waNormals[raQuads[i][1]] += n2 * (acos(-(e12*e23)/(e12norm*e23norm))/n2norm);
            waNormals[raQuads[i][2]] += n3 * (acos(-(e23*e34)/(e23norm*e34norm))/n3norm);
            waNormals[raQuads[i][3]] += n4 * (acos(-(e34*e41)/(e34norm*e41norm))/n3norm);
        }
        else
        {
            waNormals[raQuads[i][0]] += n1 / n1norm;
            waNormals[raQuads[i][1]] += n2 / n2norm;
            waNormals[raQuads[i][2]] += n3 / n3norm;
            waNormals[raQuads[i][3]] += n4 / n4norm;
        }
    }

    if(invertNormals)
        for (unsigned int i = 0; i < waNormals.size(); i++)
            waNormals[i]=-waNormals[i];

    for (unsigned int i = 0; i < waNormals.size(); i++)
        waNormals[i].normalize();
}

} // namespace engine

} // namespace component

} // namespace sofa

#endif
<|endoftext|>


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

#include "chrome/browser/history/in_memory_history_backend.h"

#include "base/command_line.h"
#include "base/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/history/history_notifications.h"
#include "chrome/browser/history/in_memory_database.h"
#include "chrome/browser/history/in_memory_url_index.h"
#include "chrome/browser/history/url_database.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"

namespace history {

// If a page becomes starred we use this id in place of the real starred id.
// See note in OnURLsStarred.
static const StarID kBogusStarredID = 0x0FFFFFFF;

InMemoryHistoryBackend::InMemoryHistoryBackend()
    : profile_(NULL) {
}

InMemoryHistoryBackend::~InMemoryHistoryBackend() {
}

bool InMemoryHistoryBackend::Init(const FilePath& history_filename,
                                  URLDatabase* db,
                                  const std::string& languages) {
  db_.reset(new InMemoryDatabase);
  bool success = db_->InitFromDisk(history_filename);
  if (!CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableHistoryQuickProvider)) {
    index_.reset(new InMemoryURLIndex());
    base::TimeTicks beginning_time = base::TimeTicks::Now();
    index_->Init(db, languages);
    UMA_HISTOGRAM_TIMES("Autocomplete.HistoryDatabaseIndexingTime",
                        base::TimeTicks::Now() - beginning_time);
  }
  return success;
}

void InMemoryHistoryBackend::AttachToHistoryService(Profile* profile) {
  if (!db_.get()) {
    NOTREACHED();
    return;
  }

  profile_ = profile;

  // TODO(evanm): this is currently necessitated by generate_profile, which
  // runs without a browser process. generate_profile should really create
  // a browser process, at which point this check can then be nuked.
  if (!g_browser_process)
    return;

  // Register for the notifications we care about.
  // We only want notifications for the associated profile.
  Source<Profile> source(profile_);
  registrar_.Add(this, NotificationType::HISTORY_URL_VISITED, source);
  registrar_.Add(this, NotificationType::HISTORY_TYPED_URLS_MODIFIED, source);
  registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED, source);
}

void InMemoryHistoryBackend::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::HISTORY_URL_VISITED: {
      Details<history::URLVisitedDetails> visited_details(details);
      if (visited_details->row.typed_count() > 0) {
        URLsModifiedDetails modified_details;
        modified_details.changed_urls.push_back(visited_details->row);
        OnTypedURLsModified(modified_details);
      }
      break;
    }
    case NotificationType::HISTORY_TYPED_URLS_MODIFIED:
      OnTypedURLsModified(
          *Details<history::URLsModifiedDetails>(details).ptr());
      break;
    case NotificationType::HISTORY_URLS_DELETED:
      OnURLsDeleted(*Details<history::URLsDeletedDetails>(details).ptr());
      break;
    default:
      // For simplicity, the unit tests send us all notifications, even when
      // we haven't registered for them, so don't assert here.
      break;
  }
}

void InMemoryHistoryBackend::OnTypedURLsModified(
    const URLsModifiedDetails& details) {
  DCHECK(db_.get());

  // Add or update the URLs.
  //
  // TODO(brettw) currently the rows in the in-memory database don't match the
  // IDs in the main database. This sucks. Instead of Add and Remove, we should
  // have Sync(), which would take the ID if it's given and add it.
  std::vector<history::URLRow>::const_iterator i;
  for (i = details.changed_urls.begin();
       i != details.changed_urls.end(); i++) {
    URLID id = db_->GetRowForURL(i->url(), NULL);
    if (id)
      db_->UpdateURLRow(id, *i);
    else
      db_->AddURL(*i);
  }
}

void InMemoryHistoryBackend::OnURLsDeleted(const URLsDeletedDetails& details) {
  DCHECK(db_.get());

  if (details.all_history) {
    // When all history is deleted, the individual URLs won't be listed. Just
    // create a new database to quickly clear everything out.
    db_.reset(new InMemoryDatabase);
    if (!db_->InitFromScratch())
      db_.reset();
    return;
  }

  // Delete all matching URLs in our database.
  for (std::set<GURL>::const_iterator i = details.urls.begin();
       i != details.urls.end(); ++i) {
    URLID id = db_->GetRowForURL(*i, NULL);
    if (id) {
      // We typically won't have most of them since we only have a subset of
      // history, so ignore errors.
      db_->DeleteURLRow(id);
    }
  }
}

}  // namespace history
<commit_msg>Temporarily disable the HistoryQuickProvider and InMemoryURLIndex to see if it is causing a slowdown at startup.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history/in_memory_history_backend.h"

#include "base/command_line.h"
#include "base/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/history/history_notifications.h"
#include "chrome/browser/history/in_memory_database.h"
#include "chrome/browser/history/in_memory_url_index.h"
#include "chrome/browser/history/url_database.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"

namespace history {

// If a page becomes starred we use this id in place of the real starred id.
// See note in OnURLsStarred.
static const StarID kBogusStarredID = 0x0FFFFFFF;

InMemoryHistoryBackend::InMemoryHistoryBackend()
    : profile_(NULL) {
}

InMemoryHistoryBackend::~InMemoryHistoryBackend() {
}

bool InMemoryHistoryBackend::Init(const FilePath& history_filename,
                                  URLDatabase* db,
                                  const std::string& languages) {
  db_.reset(new InMemoryDatabase);
  bool success = db_->InitFromDisk(history_filename);
#if 0
  // TODO(mrossetti): Temporary removal to help determine if the
  // InMemoryURLIndex is contributing to a startup slowdown.
  if (!CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableHistoryQuickProvider)) {
    index_.reset(new InMemoryURLIndex());
    base::TimeTicks beginning_time = base::TimeTicks::Now();
    index_->Init(db, languages);
    UMA_HISTOGRAM_TIMES("Autocomplete.HistoryDatabaseIndexingTime",
                        base::TimeTicks::Now() - beginning_time);
  }
#endif
  return success;
}

void InMemoryHistoryBackend::AttachToHistoryService(Profile* profile) {
  if (!db_.get()) {
    NOTREACHED();
    return;
  }

  profile_ = profile;

  // TODO(evanm): this is currently necessitated by generate_profile, which
  // runs without a browser process. generate_profile should really create
  // a browser process, at which point this check can then be nuked.
  if (!g_browser_process)
    return;

  // Register for the notifications we care about.
  // We only want notifications for the associated profile.
  Source<Profile> source(profile_);
  registrar_.Add(this, NotificationType::HISTORY_URL_VISITED, source);
  registrar_.Add(this, NotificationType::HISTORY_TYPED_URLS_MODIFIED, source);
  registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED, source);
}

void InMemoryHistoryBackend::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::HISTORY_URL_VISITED: {
      Details<history::URLVisitedDetails> visited_details(details);
      if (visited_details->row.typed_count() > 0) {
        URLsModifiedDetails modified_details;
        modified_details.changed_urls.push_back(visited_details->row);
        OnTypedURLsModified(modified_details);
      }
      break;
    }
    case NotificationType::HISTORY_TYPED_URLS_MODIFIED:
      OnTypedURLsModified(
          *Details<history::URLsModifiedDetails>(details).ptr());
      break;
    case NotificationType::HISTORY_URLS_DELETED:
      OnURLsDeleted(*Details<history::URLsDeletedDetails>(details).ptr());
      break;
    default:
      // For simplicity, the unit tests send us all notifications, even when
      // we haven't registered for them, so don't assert here.
      break;
  }
}

void InMemoryHistoryBackend::OnTypedURLsModified(
    const URLsModifiedDetails& details) {
  DCHECK(db_.get());

  // Add or update the URLs.
  //
  // TODO(brettw) currently the rows in the in-memory database don't match the
  // IDs in the main database. This sucks. Instead of Add and Remove, we should
  // have Sync(), which would take the ID if it's given and add it.
  std::vector<history::URLRow>::const_iterator i;
  for (i = details.changed_urls.begin();
       i != details.changed_urls.end(); i++) {
    URLID id = db_->GetRowForURL(i->url(), NULL);
    if (id)
      db_->UpdateURLRow(id, *i);
    else
      db_->AddURL(*i);
  }
}

void InMemoryHistoryBackend::OnURLsDeleted(const URLsDeletedDetails& details) {
  DCHECK(db_.get());

  if (details.all_history) {
    // When all history is deleted, the individual URLs won't be listed. Just
    // create a new database to quickly clear everything out.
    db_.reset(new InMemoryDatabase);
    if (!db_->InitFromScratch())
      db_.reset();
    return;
  }

  // Delete all matching URLs in our database.
  for (std::set<GURL>::const_iterator i = details.urls.begin();
       i != details.urls.end(); ++i) {
    URLID id = db_->GetRowForURL(*i, NULL);
    if (id) {
      // We typically won't have most of them since we only have a subset of
      // history, so ignore errors.
      db_->DeleteURLRow(id);
    }
  }
}

}  // namespace history
<|endoftext|>


<commit_before>#include "omp.h"

 inline
 kth_cv_omp::kth_cv_omp(const std::string in_path,
		const std::string in_actionNames,
		const field<std::string> in_all_people,
		const int in_scale_factor,
		const int in_shift,
		const int in_scene, //only for kth
		const int in_segment_length,
		const int in_dim
 ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
 {
   actions.load( actionNames );

 }

 // Log-Euclidean Distance
 inline
 void
 kth_cv_omp::logEucl()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   //No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels
   float acc;
   acc = 0;

   //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
   int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;
   int sc = 1; // = total scenes

     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   cout << all_people (pe) << "_" << actions(act) << endl;

	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   // Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa
	   wall_clock timer;
	   timer.tic();

	   //#pragma omp parallel for
	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     //debe devolver el est_labe de ese segmento
	     est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   double n = timer.toc();
	   cout << "number of seconds: " << n << endl;
	   getchar();

	   //cout << "s: " << s << endl;

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
	   est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
	   test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();

       }

     }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 inline
 uword
 kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat logMtest_cov;
   logMtest_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     mat logMtrain_cov;
	     logMtrain_cov.load( load_cov_seg_tr.str() );

	     //logMtest_cov.print("logMtest_cov");
	     //train_cov.print("train_cov");

	     dist = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     ///crear un vec aca y guardar todas las distancias
	     if (dist < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 //DO IT
 // Stein Divergence

 inline
 void
 kth_cv_omp::SteinDiv()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

      int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Stein_div_real_labels.dat", raw_ascii);
	   est_labels.save("Stein_div__est_labels.dat", raw_ascii);
	   test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }

       }
     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 //DO IT!!!!!!!!!
 inline
 uword
 kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat test_cov;
   test_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist_stein, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     mat train_cov;
	     train_cov.load( load_cov_seg_tr.str() );

	     //Esto vienen de PartI4. No recuerdo mas :(
	     double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
	     double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
	     dist_stein =  log( det_op1 ) - 0.5*log( det_op2 ) ;

	     //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     if (dist_stein < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist_stein;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 <commit_msg>Run in parallel. Classification<commit_after>#include "omp.h"

 inline
 kth_cv_omp::kth_cv_omp(const std::string in_path,
		const std::string in_actionNames,
		const field<std::string> in_all_people,
		const int in_scale_factor,
		const int in_shift,
		const int in_scene, //only for kth
		const int in_segment_length,
		const int in_dim
 ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim)
 {
   actions.load( actionNames );

 }

 // Log-Euclidean Distance
 inline
 void
 kth_cv_omp::logEucl()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   //No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels
   float acc;
   acc = 0;

   //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3
   int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;
   int sc = 1; // = total scenes

     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   cout << all_people (pe) << "_" << actions(act) << endl;

	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   // Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa
	   wall_clock timer;
	   timer.tic();

	   #pragma omp parallel for
	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     //debe devolver el est_labe de ese segmento
	     est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   double n = timer.toc();
	   cout << "OpenMP number of seconds: " << n << endl;
	   getchar();

	   //cout << "s: " << s << endl;

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Log_Eucl_real_labels.dat", raw_ascii);
	   est_labels.save("Log_Eucl_est_labels.dat", raw_ascii);
	   test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();

       }

     }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 inline
 uword
 kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat logMtest_cov;
   logMtest_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5" << endl;
	     mat logMtrain_cov;
	     logMtrain_cov.load( load_cov_seg_tr.str() );

	     //logMtest_cov.print("logMtest_cov");
	     //train_cov.print("train_cov");

	     dist = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     ///crear un vec aca y guardar todas las distancias
	     if (dist < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 //DO IT
 // Stein Divergence

 inline
 void
 kth_cv_omp::SteinDiv()
 {

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   float acc;
   acc = 0;

      int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3

   vec real_labels;
   vec est_labels;
   field<std::string> test_video_list(n_test);

   real_labels.zeros(n_test);
   est_labels.zeros(n_test);

   int k=0;

   for (int sc = 1; sc<=total_scenes; ++sc) //scene
   {
     for (int pe = 0; pe< n_peo; ++pe)
     {
       for (int act=0; act<n_actions; ++act)
       {
	 if(  !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3
	 {
	   //load number of segments

	   vec total_seg;
	   int num_s;
	   std::stringstream load_sub_path;
	   std::stringstream load_num_seg;

	   load_sub_path  << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	   load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);
	   uvec  est_lab_segm;
	   est_lab_segm.zeros(num_s);
	   vec count = zeros<vec>( n_actions );

	   for (int s=0; s<num_s; ++s)
	   {
	     std::stringstream load_cov_seg;
	     load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(),  load_cov_seg.str());
	     count( est_lab_segm(s) )++;
	     //getchar();
	   }

	   uword  index_video;
	   double max_val = count.max(index_video);
	   //est_lab_segm.t().print("est_lab_segm");
	   cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl;

	   real_labels(k) = act;
	   est_labels(k) = index_video;
	   test_video_list(k) = load_sub_path.str();

	   real_labels.save("Stein_div_real_labels.dat", raw_ascii);
	   est_labels.save("Stein_div__est_labels.dat", raw_ascii);
	   test_video_list.save("Stein_div_test_video_list.dat", raw_ascii);
	   k++;

	   if (index_video == act)  {
	     acc++;

	   }

	   //getchar();
	 }

       }
     }
   }

   cout << "Performance: " << acc*100/n_test << " %" << endl;

 }

 //DO IT!!!!!!!!!
 inline
 uword
 kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name)
 {
   //wall_clock timer;
   //timer.tic();

   mat test_cov;
   test_cov.load(segm_name);

   int n_actions = actions.n_rows;
   int n_peo =  all_people.n_rows;

   double dist_stein, tmp_dist;
   tmp_dist = datum::inf;

   double est_lab;
   //cout << "Comparing with person ";

   for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr)
   {
     if (pe_tr!= pe_test)
     {

       //cout << " " << all_people (pe_tr);

       for (int sc = 1; sc<=total_scenes; ++sc) //scene
       {
	 for (int act=0; act<n_actions; ++act)
	 {
	   vec total_seg;
	   int num_s;
	   std::stringstream load_num_seg;
	   load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".dat";
	   total_seg.load( load_num_seg.str());
	   num_s = total_seg(0);

	   for (int s_tr=0; s_tr<num_s; ++s_tr)
	   {
	     std::stringstream load_cov_seg_tr;
	     load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim  << ".h5";

	     mat train_cov;
	     train_cov.load( load_cov_seg_tr.str() );

	     //Esto vienen de PartI4. No recuerdo mas :(
	     double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) );
	     double det_op2 = det( diagmat( ( test_cov%train_cov ) ) );
	     dist_stein =  log( det_op1 ) - 0.5*log( det_op2 ) ;

	     //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro");

	     //cout << "dist " << dist << endl;

	     if (dist_stein < tmp_dist)
	     {
	       //cout << "Es menor" << endl;
	       tmp_dist = dist_stein;
	       est_lab = act;
	     }
	     //cout << "Press a key" << endl;
	     //getchar();
	   }
	 }
       }
     }
   }

   //double n = timer.toc();
   //cout << "number of seconds: " << n << endl;
   //cout << " est_lab "<< est_lab << endl << endl;
   //getchar();
   return est_lab;

 }

 <|endoftext|>


<commit_before>#include "stdafx.h"
#include "CoreJobTest.h"
#include "CoreJob.h"
#include "move_only.h"
#include <boost/thread.hpp>

TEST_F(CoreJobTest, VerifySimpleProperties) {
  AutoRequired<CoreJob> jb;

  ASSERT_FALSE(m_create->IsInitiated()) << "CoreJob reported it could receive events before its enclosing context was created";

  // Create a thread which will delay for acceptance, and then quit:
  boost::thread t([this] {
    m_create->DelayUntilInitiated();
  });

  // Verify that this thread doesn't back out right away:
  ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << "CoreJob did not block a client who was waiting for its readiness to accept dispatchers";

  // Now start the context and verify that certain properties changed as anticipated:
  m_create->Initiate();
  ASSERT_TRUE(m_create->DelayUntilInitiated()) << "CoreJob did not correctly delay for dispatch acceptance";

  // Verify that the blocked thread has become unblocked and quits properly:
  ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << "CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers";
}

TEST_F(CoreJobTest, VerifySimpleSubmission) {
  AutoRequired<CoreJob> jb;

  auto myFlag = std::make_shared<bool>(false);
  *jb += [myFlag] {
    *myFlag = true;
  };

  // Kickoff, signal for a shutdown to take place, and then verify the flag
  AutoCurrentContext ctxt;
  ctxt->Initiate();
  ctxt->SignalShutdown(true);
  ASSERT_TRUE(*myFlag) << "CoreJob did not properly execute its thread";
}

TEST_F(CoreJobTest, VerifyTeardown) {
  AutoRequired<CoreJob> job;
  AutoCurrentContext ctxt;

  bool check1 = false;
  bool check2 = false;
  bool check3 = false;

  *job += [&check1] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(200));
    check1 = true;
  };
  *job += [&check2] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(200));
    check2 = true;
  };
  ctxt->Initiate();
  *job += [&check3] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    check3 = true;
  };

  ctxt->SignalShutdown(true);
  EXPECT_TRUE(check1) << "Lambda 1 didn't finish";
  EXPECT_TRUE(check2) << "Lambda 2 didn't finish";
  EXPECT_TRUE(check3) << "Lambda 3 didn't finish";
}

struct SimpleListen:
  virtual EventReceiver
{
  SimpleListen():
    m_flag(false)
  {}

  void SetFlag(){m_flag=true;}

  bool m_flag;
};

TEST_F(CoreJobTest, VerifyNoEventReceivers){
  AutoCreateContext ctxt1;
  CurrentContextPusher pshr1(ctxt1);

  AutoFired<SimpleListen> fire;
  ctxt1->Initiate();

  AutoCreateContext ctxt2;
  CurrentContextPusher pshr2(ctxt2);

  AutoRequired<SimpleListen> listener;
  ASSERT_FALSE(listener->m_flag) << "Flag was initialized improperly";

  fire(&SimpleListen::SetFlag)();
  EXPECT_FALSE(listener->m_flag) << "Lister recived event event though it wasn't initiated";
}

class CanOnlyMove {
public:
  CanOnlyMove(){}
  ~CanOnlyMove(){}
  CanOnlyMove(const CanOnlyMove& derp) = delete;
  CanOnlyMove(CanOnlyMove&& derp){}
};

TEST_F(CoreJobTest, MoveOnly){
  CanOnlyMove move;
  //CanOnlyMove derp = move; //error

  MoveOnly<CanOnlyMove> mo(std::move(move));

  MoveOnly<CanOnlyMove> first = mo;
  //MoveOnly<CanOnlyMove> second = mo; //error
}

TEST_F(CoreJobTest, AbandonedDispatchers) {
  auto v = std::make_shared<bool>(false);

  AutoRequired<CoreJob> cj;
  *cj += [v] { *v = true; };

  // Graceful shutdown on our enclosing context without starting it:
  AutoCurrentContext()->SignalShutdown(true);

  // Verify that all lambdas on the CoreThread got called as expected:
  ASSERT_FALSE(*v) << "Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started";
}

TEST_F(CoreJobTest, RecursiveAdd) {
  bool first = false;
  bool second = false;
  bool third = false;

  AutoRequired<CoreJob> cj;

  AutoCurrentContext()->Initiate();

  *cj += [&first,&second,&third, &cj] {
    first = true;
    *cj += [&first,&second,&third,&cj] {
      second = true;
      *cj += [&first,&second,&third,&cj] {
        third = true;
      };
      cj->Stop(true);
    };
  };

  cj->Wait();

  // Verify that all lambdas on the CoreThread got called as expected:
  EXPECT_TRUE(first) << "Appended lambda didn't set value";
  EXPECT_TRUE(second) << "Appended lambda didn't set value";
  EXPECT_TRUE(third) << "Appended lambda didn't set value";
}

TEST_F(CoreJobTest, RaceCondition) {

  for (int i=0; i<5; i++) {
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);
    AutoRequired<CoreJob> cj;
    ctxt->Initiate();

    bool first = false;
    bool second = false;

    *cj += [&first] {
      first = true;
    };

    boost::this_thread::sleep(boost::posix_time::milliseconds(i));

    *cj += [&second, &cj] {
      second = true;
    };

    ctxt->SignalShutdown(true);

    ASSERT_TRUE(first) << "Failed after set value in lambda";
    ASSERT_TRUE(second) << "Failed to set value when delayed " << i << " milliseconds";
  }
}
<commit_msg>Adding a unit test to validate context assignment during lambda execution<commit_after>#include "stdafx.h"
#include "CoreJobTest.h"
#include "CoreJob.h"
#include "move_only.h"
#include <boost/thread.hpp>

TEST_F(CoreJobTest, VerifySimpleProperties) {
  AutoRequired<CoreJob> jb;

  ASSERT_FALSE(m_create->IsInitiated()) << "CoreJob reported it could receive events before its enclosing context was created";

  // Create a thread which will delay for acceptance, and then quit:
  boost::thread t([this] {
    m_create->DelayUntilInitiated();
  });

  // Verify that this thread doesn't back out right away:
  ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << "CoreJob did not block a client who was waiting for its readiness to accept dispatchers";

  // Now start the context and verify that certain properties changed as anticipated:
  m_create->Initiate();
  ASSERT_TRUE(m_create->DelayUntilInitiated()) << "CoreJob did not correctly delay for dispatch acceptance";

  // Verify that the blocked thread has become unblocked and quits properly:
  ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << "CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers";
}

TEST_F(CoreJobTest, VerifySimpleSubmission) {
  AutoRequired<CoreJob> jb;

  auto myFlag = std::make_shared<bool>(false);
  *jb += [myFlag] {
    *myFlag = true;
  };

  // Kickoff, signal for a shutdown to take place, and then verify the flag
  AutoCurrentContext ctxt;
  ctxt->Initiate();
  ctxt->SignalShutdown(true);
  ASSERT_TRUE(*myFlag) << "CoreJob did not properly execute its thread";
}

TEST_F(CoreJobTest, VerifyTeardown) {
  AutoRequired<CoreJob> job;
  AutoCurrentContext ctxt;

  bool check1 = false;
  bool check2 = false;
  bool check3 = false;

  *job += [&check1] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(200));
    check1 = true;
  };
  *job += [&check2] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(200));
    check2 = true;
  };
  ctxt->Initiate();
  *job += [&check3] {
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    check3 = true;
  };

  ctxt->SignalShutdown(true);
  EXPECT_TRUE(check1) << "Lambda 1 didn't finish";
  EXPECT_TRUE(check2) << "Lambda 2 didn't finish";
  EXPECT_TRUE(check3) << "Lambda 3 didn't finish";
}

struct SimpleListen:
  virtual EventReceiver
{
  SimpleListen():
    m_flag(false)
  {}

  void SetFlag(){m_flag=true;}

  bool m_flag;
};

TEST_F(CoreJobTest, VerifyNoEventReceivers){
  AutoCreateContext ctxt1;
  CurrentContextPusher pshr1(ctxt1);

  AutoFired<SimpleListen> fire;
  ctxt1->Initiate();

  AutoCreateContext ctxt2;
  CurrentContextPusher pshr2(ctxt2);

  AutoRequired<SimpleListen> listener;
  ASSERT_FALSE(listener->m_flag) << "Flag was initialized improperly";

  fire(&SimpleListen::SetFlag)();
  EXPECT_FALSE(listener->m_flag) << "Lister recived event event though it wasn't initiated";
}

class CanOnlyMove {
public:
  CanOnlyMove(){}
  ~CanOnlyMove(){}
  CanOnlyMove(const CanOnlyMove& derp) = delete;
  CanOnlyMove(CanOnlyMove&& derp){}
};

TEST_F(CoreJobTest, MoveOnly){
  CanOnlyMove move;
  //CanOnlyMove derp = move; //error

  MoveOnly<CanOnlyMove> mo(std::move(move));

  MoveOnly<CanOnlyMove> first = mo;
  //MoveOnly<CanOnlyMove> second = mo; //error
}

TEST_F(CoreJobTest, AbandonedDispatchers) {
  auto v = std::make_shared<bool>(false);

  AutoRequired<CoreJob> cj;
  *cj += [v] { *v = true; };

  // Graceful shutdown on our enclosing context without starting it:
  AutoCurrentContext()->SignalShutdown(true);

  // Verify that all lambdas on the CoreThread got called as expected:
  ASSERT_FALSE(*v) << "Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started";
}

TEST_F(CoreJobTest, RecursiveAdd) {
  bool first = false;
  bool second = false;
  bool third = false;

  AutoRequired<CoreJob> cj;

  AutoCurrentContext()->Initiate();

  *cj += [&first,&second,&third, &cj] {
    first = true;
    *cj += [&first,&second,&third,&cj] {
      second = true;
      *cj += [&first,&second,&third,&cj] {
        third = true;
      };
      cj->Stop(true);
    };
  };

  cj->Wait();

  // Verify that all lambdas on the CoreThread got called as expected:
  EXPECT_TRUE(first) << "Appended lambda didn't set value";
  EXPECT_TRUE(second) << "Appended lambda didn't set value";
  EXPECT_TRUE(third) << "Appended lambda didn't set value";
}

TEST_F(CoreJobTest, RaceCondition) {
  for (int i=0; i<5; i++) {
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);
    AutoRequired<CoreJob> cj;
    ctxt->Initiate();

    bool first = false;
    bool second = false;

    *cj += [&first] {
      first = true;
    };

    boost::this_thread::sleep(boost::posix_time::milliseconds(i));

    *cj += [&second, &cj] {
      second = true;
    };

    ctxt->SignalShutdown(true);

    ASSERT_TRUE(first) << "Failed after set value in lambda";
    ASSERT_TRUE(second) << "Failed to set value when delayed " << i << " milliseconds";
  }
}

TEST_F(CoreJobTest, CorrectlyAssignedCurrentContext) {
  AutoCurrentContext()->Initiate();
  AutoRequired<CoreJob> job;

  std::shared_ptr<CoreContext> ctxt;
  *job += [&ctxt] { ctxt = AutoCurrentContext(); };
  *job += [job] { job->Stop(true); };
  ASSERT_TRUE(job->WaitFor(boost::chrono::seconds(5)));

  // Now verify that the job was run in the right thread context:
  ASSERT_EQ(AutoCurrentContext(), ctxt) << "Job lambda was not run with the correct CoreContext current";
}<|endoftext|>


<commit_before>// Day23.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

enum OpCode { hlf, tpl, inc, jmp, jie, jio };

struct CPUState {
	size_t InstructionPointer;

	size_t a;
	size_t b;

	CPUState()
		:InstructionPointer(0), a(0), b(0)
	{}
};

typedef std::function<void(CPUState &)> InstructionFunction;
typedef std::vector<InstructionFunction> InstructionVector;
typedef std::map<std::string, OpCode> StringOpCodeMap;
typedef std::function<size_t&(CPUState &)> RegisterFetchFunction;
typedef std::map<std::string, RegisterFetchFunction> StringRegisterFetchFunctionMap;

static CPUState Run(const std::string & InputFile);
static InstructionFunction ParseAssembly(const StringVector & Line);

static const StringOpCodeMap StringToOpCodeMap({ { "hlf", hlf },{ "tpl", tpl },{ "inc", inc },{ "jmp", jmp },{ "jie", jie },{ "jio", jio }, });
static const StringRegisterFetchFunctionMap StringToRegisterFetch({ {"a", [](CPUState & CPU)->size_t& { return CPU.a; }},{ "b", [](CPUState & CPU)->size_t& { return CPU.b; }} });

int main()
{
	CPUState State = Run("Input.txt");

	std::cout << "b: " << State.b << std::endl;

	system("pause");

	return 0;
}

static CPUState Run(const std::string & InputFile)
{
	StringVectorVector InputParts = GetFileLineParts(InputFile);
	InstructionVector ParsedInstructions(InputParts.size(), nullptr);

	CPUState CPU;
	while (CPU.InstructionPointer < ParsedInstructions.size())
	{
		if (!ParsedInstructions[CPU.InstructionPointer])
		{
			ParsedInstructions[CPU.InstructionPointer] = ParseAssembly(InputParts[CPU.InstructionPointer]);
		}

		ParsedInstructions[CPU.InstructionPointer](CPU);
	}

	return CPU;
}

static InstructionFunction ParseAssembly(const StringVector & Line)
{
	const OpCode Instruction = StringToOpCodeMap.find(Line[0])->second;

	RegisterFetchFunction RegisterFetch = nullptr;;
	switch (Instruction)
	{
	case hlf:
	case tpl:
	case inc:
		RegisterFetch = StringToRegisterFetch.find(Line[1])->second;
		break;
	case jie:
	case jio:
		RegisterFetch = StringToRegisterFetch.find(Line[1].substr(0, Line[1].size() - 1))->second;
		break;
	}

	int64_t JumpDistance = 0;
	switch (Instruction)
	{
	case jmp:
		JumpDistance = std::atoi(Line[1].c_str());
		break;
	case jie:
	case jio:
		JumpDistance = std::atoi(Line[2].c_str());
		break;
	}

	switch (Instruction)
	{
	case hlf:
		return [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) /= 2; ++CPU.InstructionPointer; };
	case tpl:
		return [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) *= 3; ++CPU.InstructionPointer; };
	case inc:
		return [RegisterFetch](CPUState & CPU) { ++RegisterFetch(CPU); ++CPU.InstructionPointer; };
	case jmp:
		return [JumpDistance](CPUState & CPU) { CPU.InstructionPointer += JumpDistance; };
	case jie:
		return [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += ((RegisterFetch(CPU) % 2) == 0) ? JumpDistance : 1; };
	case jio:
		return [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += (RegisterFetch(CPU) == 1) ? JumpDistance : 1; };
	}

	return nullptr;
}
<commit_msg>Add soltion for Day 23 part two<commit_after>// Day23.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

enum OpCode { hlf, tpl, inc, jmp, jie, jio };

struct CPUState {
	size_t InstructionPointer;

	size_t a;
	size_t b;

	CPUState()
		:InstructionPointer(0), a(0), b(0)
	{}

	CPUState(size_t a, size_t b)
		:InstructionPointer(0), a(a), b(b)
	{}
};

typedef std::function<void(CPUState &)> InstructionFunction;
typedef std::vector<InstructionFunction> InstructionVector;
typedef std::map<std::string, OpCode> StringOpCodeMap;
typedef std::function<size_t&(CPUState &)> RegisterFetchFunction;
typedef std::map<std::string, RegisterFetchFunction> StringRegisterFetchFunctionMap;

static CPUState Run(const std::string & InputFile, CPUState CPU = CPUState());
static InstructionFunction ParseAssembly(const StringVector & Line);

static const StringOpCodeMap StringToOpCodeMap({ { "hlf", hlf },{ "tpl", tpl },{ "inc", inc },{ "jmp", jmp },{ "jie", jie },{ "jio", jio }, });
static const StringRegisterFetchFunctionMap StringToRegisterFetch({ {"a", [](CPUState & CPU)->size_t& { return CPU.a; }},{ "b", [](CPUState & CPU)->size_t& { return CPU.b; }} });

int main()
{
	CPUState PartOne = Run("Input.txt");
	CPUState PartTwo = Run("Input.txt", CPUState(1, 0));

	std::cout << "b (Part One): " << PartOne.b << std::endl;
	std::cout << "b (Part Two): " << PartTwo.b << std::endl;

	system("pause");

	return 0;
}

static CPUState Run(const std::string & InputFile, CPUState CPU)
{
	StringVectorVector InputParts = GetFileLineParts(InputFile);
	InstructionVector ParsedInstructions(InputParts.size(), nullptr);

	while (CPU.InstructionPointer < ParsedInstructions.size())
	{
		if (!ParsedInstructions[CPU.InstructionPointer])
		{
			ParsedInstructions[CPU.InstructionPointer] = ParseAssembly(InputParts[CPU.InstructionPointer]);
		}

		ParsedInstructions[CPU.InstructionPointer](CPU);
	}

	return CPU;
}

static InstructionFunction ParseAssembly(const StringVector & Line)
{
	const OpCode Instruction = StringToOpCodeMap.find(Line[0])->second;

	RegisterFetchFunction RegisterFetch = nullptr;;
	switch (Instruction)
	{
	case hlf:
	case tpl:
	case inc:
		RegisterFetch = StringToRegisterFetch.find(Line[1])->second;
		break;
	case jie:
	case jio:
		RegisterFetch = StringToRegisterFetch.find(Line[1].substr(0, Line[1].size() - 1))->second;
		break;
	}

	int64_t JumpDistance = 0;
	switch (Instruction)
	{
	case jmp:
		JumpDistance = std::atoi(Line[1].c_str());
		break;
	case jie:
	case jio:
		JumpDistance = std::atoi(Line[2].c_str());
		break;
	}

	switch (Instruction)
	{
	case hlf:
		return [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) /= 2; ++CPU.InstructionPointer; };
	case tpl:
		return [RegisterFetch](CPUState & CPU) { RegisterFetch(CPU) *= 3; ++CPU.InstructionPointer; };
	case inc:
		return [RegisterFetch](CPUState & CPU) { ++RegisterFetch(CPU); ++CPU.InstructionPointer; };
	case jmp:
		return [JumpDistance](CPUState & CPU) { CPU.InstructionPointer += JumpDistance; };
	case jie:
		return [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += ((RegisterFetch(CPU) % 2) == 0) ? JumpDistance : 1; };
	case jio:
		return [RegisterFetch, JumpDistance](CPUState & CPU) { CPU.InstructionPointer += (RegisterFetch(CPU) == 1) ? JumpDistance : 1; };
	}

	return nullptr;
}
<|endoftext|>


<commit_before>// Copyright 2013 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 "ash/first_run/first_run_helper.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "chrome/browser/chromeos/first_run/first_run.h"
#include "chrome/browser/chromeos/first_run/first_run_controller.h"
#include "chrome/browser/chromeos/first_run/step_names.h"
#include "chrome/browser/chromeos/login/test/js_checker.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/test/test_utils.h"

namespace chromeos {

class FirstRunUIBrowserTest : public InProcessBrowserTest,
                              public FirstRunActor::Delegate {
 public:
  FirstRunUIBrowserTest()
      : initialized_(false),
        finalized_(false) {
  }

  // FirstRunActor::Delegate overrides.
  virtual void OnActorInitialized() OVERRIDE {
    initialized_ = true;
    if (!on_initialized_callback_.is_null())
      on_initialized_callback_.Run();
    controller()->OnActorInitialized();
  }

  virtual void OnNextButtonClicked(const std::string& step_name) OVERRIDE {
    controller()->OnNextButtonClicked(step_name);
  }

  virtual void OnStepShown(const std::string& step_name) OVERRIDE {
    if (!on_step_shown_callback_.is_null())
      on_step_shown_callback_.Run();
    controller()->OnStepShown(step_name);
  }

  virtual void OnStepHidden(const std::string& step_name) OVERRIDE {
    controller()->OnStepHidden(step_name);
  }

  virtual void OnHelpButtonClicked() OVERRIDE {
    controller()->OnHelpButtonClicked();
  }

  virtual void OnActorFinalized() OVERRIDE {
    finalized_ = true;
    if (!on_finalized_callback_.is_null())
      on_finalized_callback_.Run();
    controller()->OnActorFinalized();
  }

  virtual void OnActorDestroyed() OVERRIDE {
    controller()->OnActorDestroyed();
  }

  void LaunchTutorial() {
    chromeos::first_run::LaunchTutorial();
    EXPECT_TRUE(controller() != NULL);
    // Replacing delegate to observe all messages coming from WebUI to
    // controller.
    controller()->actor_->set_delegate(this);
    initialized_ = controller()->actor_->IsInitialized();
  }

  void WaitForInitialization() {
    if (initialized_)
      return;
    WaitUntilCalled(&on_initialized_callback_);
    EXPECT_TRUE(initialized_);
    js().set_web_contents(controller()->web_contents_for_tests_);
  }

  void WaitForStep(const std::string& step_name) {
    if (GetCurrentStepName() == step_name)
      return;
    WaitUntilCalled(&on_step_shown_callback_);
    EXPECT_EQ(GetCurrentStepName(), step_name);
  }

  void AdvanceStep() {
    js().Evaluate("cr.FirstRun.currentStep_.nextButton_.click()");
  }

  void WaitForFinalization() {
    if (!finalized_) {
      WaitUntilCalled(&on_finalized_callback_);
      EXPECT_TRUE(finalized_);
    }
  }

  void WaitUntilCalled(base::Closure* callback) {
    scoped_refptr<content::MessageLoopRunner> runner =
        new content::MessageLoopRunner;
    *callback = runner->QuitClosure();
    runner->Run();
    callback->Reset();
  }

  std::string GetCurrentStepName() {
    return js().GetString(
        "cr.FirstRun.currentStep_ ? cr.FirstRun.currentStep_.getName() : ''");
  }

  test::JSChecker& js() { return js_; }

  ash::FirstRunHelper* shell_helper() {
    return controller()->shell_helper_.get();
  }

  FirstRunController* controller() {
    return FirstRunController::GetInstanceForTest();
  }

 private:
  bool initialized_;
  bool finalized_;
  base::Closure on_initialized_callback_;
  base::Closure on_step_shown_callback_;
  base::Closure on_finalized_callback_;
  test::JSChecker js_;
};

// Disabled due to flakiness, see http://crbug.com/335280
IN_PROC_BROWSER_TEST_F(FirstRunUIBrowserTest, DISABLED_FirstRunFlow) {
  LaunchTutorial();
  WaitForInitialization();
  WaitForStep(first_run::kAppListStep);
  EXPECT_FALSE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForStep(first_run::kTrayStep);
  EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForStep(first_run::kHelpStep);
  EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForFinalization();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(controller(), (void*)NULL);
  // shell_helper() is destructed already, thats why we call Shell directly.
  EXPECT_FALSE(ash::Shell::GetInstance()->GetPrimarySystemTray()->
      HasSystemBubble());
}

}  // namespace chromeos

<commit_msg>Prevented flakiness in FirstRunUIBrowserTest.FirstRunFlow test.<commit_after>// Copyright 2013 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 "ash/first_run/first_run_helper.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "chrome/browser/chromeos/first_run/first_run.h"
#include "chrome/browser/chromeos/first_run/first_run_controller.h"
#include "chrome/browser/chromeos/first_run/step_names.h"
#include "chrome/browser/chromeos/login/test/js_checker.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/test/test_utils.h"

namespace chromeos {

class FirstRunUIBrowserTest : public InProcessBrowserTest,
                              public FirstRunActor::Delegate {
 public:
  FirstRunUIBrowserTest()
      : initialized_(false),
        finalized_(false) {
  }

  // FirstRunActor::Delegate overrides.
  virtual void OnActorInitialized() OVERRIDE {
    initialized_ = true;
    if (!on_initialized_callback_.is_null())
      on_initialized_callback_.Run();
    controller()->OnActorInitialized();
  }

  virtual void OnNextButtonClicked(const std::string& step_name) OVERRIDE {
    controller()->OnNextButtonClicked(step_name);
  }

  virtual void OnStepShown(const std::string& step_name) OVERRIDE {
    current_step_name_ = step_name;
    if (!on_step_shown_callback_.is_null())
      on_step_shown_callback_.Run();
    controller()->OnStepShown(step_name);
  }

  virtual void OnStepHidden(const std::string& step_name) OVERRIDE {
    controller()->OnStepHidden(step_name);
  }

  virtual void OnHelpButtonClicked() OVERRIDE {
    controller()->OnHelpButtonClicked();
  }

  virtual void OnActorFinalized() OVERRIDE {
    finalized_ = true;
    if (!on_finalized_callback_.is_null())
      on_finalized_callback_.Run();
    controller()->OnActorFinalized();
  }

  virtual void OnActorDestroyed() OVERRIDE {
    controller()->OnActorDestroyed();
  }

  void LaunchTutorial() {
    chromeos::first_run::LaunchTutorial();
    EXPECT_TRUE(controller() != NULL);
    // Replacing delegate to observe all messages coming from WebUI to
    // controller.
    controller()->actor_->set_delegate(this);
    initialized_ = controller()->actor_->IsInitialized();
  }

  void WaitForInitialization() {
    if (initialized_)
      return;
    WaitUntilCalled(&on_initialized_callback_);
    EXPECT_TRUE(initialized_);
    js().set_web_contents(controller()->web_contents_for_tests_);
  }

  void WaitForStep(const std::string& step_name) {
    if (current_step_name_ == step_name)
      return;
    WaitUntilCalled(&on_step_shown_callback_);
    EXPECT_EQ(current_step_name_, step_name);
  }

  void AdvanceStep() {
    js().Evaluate("cr.FirstRun.currentStep_.nextButton_.click()");
  }

  void WaitForFinalization() {
    if (!finalized_) {
      WaitUntilCalled(&on_finalized_callback_);
      EXPECT_TRUE(finalized_);
    }
  }

  void WaitUntilCalled(base::Closure* callback) {
    scoped_refptr<content::MessageLoopRunner> runner =
        new content::MessageLoopRunner;
    *callback = runner->QuitClosure();
    runner->Run();
    callback->Reset();
  }

  test::JSChecker& js() { return js_; }

  ash::FirstRunHelper* shell_helper() {
    return controller()->shell_helper_.get();
  }

  FirstRunController* controller() {
    return FirstRunController::GetInstanceForTest();
  }

 private:
  std::string current_step_name_;
  bool initialized_;
  bool finalized_;
  base::Closure on_initialized_callback_;
  base::Closure on_step_shown_callback_;
  base::Closure on_finalized_callback_;
  test::JSChecker js_;
};

IN_PROC_BROWSER_TEST_F(FirstRunUIBrowserTest, FirstRunFlow) {
  LaunchTutorial();
  WaitForInitialization();
  WaitForStep(first_run::kAppListStep);
  EXPECT_FALSE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForStep(first_run::kTrayStep);
  EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForStep(first_run::kHelpStep);
  EXPECT_TRUE(shell_helper()->IsTrayBubbleOpened());
  AdvanceStep();
  WaitForFinalization();
  content::RunAllPendingInMessageLoop();
  EXPECT_EQ(controller(), (void*)NULL);
  // shell_helper() is destructed already, thats why we call Shell directly.
  EXPECT_FALSE(ash::Shell::GetInstance()->GetPrimarySystemTray()->
      HasSystemBubble());
}

}  // namespace chromeos

<|endoftext|>